我有一个包含QGroupBox的QDialog,其中包含一些QPushButton。我想要区分QPushButton的背光颜色和所有剩余的QPushButton。如何使用pyqgis实现这一目标?
答案 0 :(得分:3)
确保按钮都是组框的子项,然后使用findChildren迭代它们。您还可以使用QButtonGroup来帮助管理按钮。
这是一个演示脚本,展示如何完成:
from PyQt4 import QtCore, QtGui
class Dialog(QtGui.QDialog):
def __init__(self):
QtGui.QDialog.__init__(self)
layout = QtGui.QVBoxLayout(self)
self.groupBox = QtGui.QGroupBox(self)
layout.addWidget(self.groupBox)
layout = QtGui.QVBoxLayout(self.groupBox)
for index in range(5):
button = QtGui.QPushButton('Button %d' % index, self.groupBox)
layout.addWidget(button)
self.buttonGroup = QtGui.QButtonGroup(self)
self.buttonGroup.buttonClicked.connect(self.handleButtonClicked)
self.updateButtonGroup()
def updateButtonGroup(self):
for button in self.groupBox.findChildren(QtGui.QPushButton):
if self.buttonGroup.id(button) < 0:
self.buttonGroup.addButton(button)
def handleButtonClicked(self, button):
for item in self.buttonGroup.buttons():
if button is item:
item.setStyleSheet('background-color: orange')
else:
item.setStyleSheet('')
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Dialog()
window.show()
sys.exit(app.exec_())
答案 1 :(得分:0)
如果使用类QtGui.QGroupBox
的原因是选择按钮就像单选按钮一样,您可以使用Qt样式表设置不同的背景颜色;
import sys
from PyQt4 import QtGui
class QCustomDialog (QtGui.QDialog):
def __init__(self, *args, **kwargs):
QtGui.QDialog.__init__(self, *args, **kwargs)
myQVBoxLayout = QtGui.QVBoxLayout()
for text in ['PyQt', 'Stack', 'Overflow']:
myQPushButton = QtGui.QPushButton(text)
myQPushButton.setCheckable(True)
myQPushButton.setAutoExclusive(True)
myQVBoxLayout.addWidget(myQPushButton)
myQVBoxLayout.addStretch(1)
myQGroupBox = QtGui.QGroupBox()
myQGroupBox.setStyleSheet('''
QPushButton {
border: 0px;
color: rgb(255, 255, 255);
background-color: rgb(0, 0, 0);
}
QPushButton:checked {
border: 0px;
color: rgb(255, 255, 255);
background-color: rgb(255, 0, 0);
}
''')
myQGroupBox.setLayout(myQVBoxLayout)
allQVBoxLayout = QtGui.QVBoxLayout()
allQVBoxLayout.addWidget(myQGroupBox)
self.setLayout(allQVBoxLayout)
myQApplication = QtGui.QApplication([])
myQCustomDialog = QCustomDialog()
myQCustomDialog.show()
sys.exit(myQApplication.exec_())