我正在尝试使我的QComboBox可检查。我搜索了类似的帖子,但其中许多仍未得到答复,我没有设法应用此处发布的解决方案(QCombobox of Checkboxes)。目前我定义了这个类:
class myCombo(QComboBox):
def __init__(self, parent = None):
super(myCombo, self).__init__(parent)
self.setStyleSheet("QComboBox{"
"font-size:12px;"
"color:black;"
"background-color:white;"
"border:1px solid black;"
"padding:1px;""}")
self.setEditable(True)
self.lineEdit().setAlignment(Qt.AlignCenter)
self.lineEdit().setReadOnly(True)
我的目标是添加一个属性,该属性可以检查项目,以便可以进行多项选择。这可以在没有将这个'复选框'硬编码到QComboBox中的情况下进行管理吗?
上面定义的QComboBox类使用如下:
class sWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
years = [' ', '2017', '2018', '2019', '2020']
months = [' ', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
self.setMinimumSize(QSize(360, 140))
self.setWindowTitle("Dialog")
self.yearLabel = QLabel(self)
self.yearLabel.setText('Select Year(s):')
self.firstLine = myCombo(self)
self.firstLine.addItems(years)
self.firstLine.move(120, 20)
self.firstLine.resize(200, 32)
self.yearLabel.move(20, 20)
self.monthLabel = QLabel(self)
self.monthLabel.setText('Select Month(s):')
self.secondLine = myCombo(self)
self.secondLine.addItems(months)
self.secondLine.move(120, 60)
self.secondLine.resize(200, 32)
self.monthLabel.move(20, 60)
okButton = QPushButton('OK', self)
okButton.clicked.connect(self.okClicked)
okButton.resize(100, 32)
okButton.move(120, 100)
cancelB = QPushButton('Cancel', self)
cancelB.clicked.connect(self.cancelClicked)
cancelB.resize(100, 32)
cancelB.move(220, 100)
def okClicked(self):
self.close()
def cancelClicked(self):
self.close()
if __name__ == '__main__':
app = QApplication(sys.argv)
main = sWindow()
main.show()
sys.exit(app.exec_())
我希望能够在月份组合框中选择1,2,3。谢谢你的任何建议!
答案 0 :(得分:0)
使用这个有用的链接:
PyQt: How to set Combobox Items be Checkable?
我设法让它工作(例如,一个组合框包含可检查的年份):
class CheckableComboBox(QComboBox):
def __init__(self, parent = None):
super(CheckableComboBox, self).__init__(parent)
self.view().pressed.connect(self.handleItemPressed)
self.setModel(QStandardItemModel(self))
def handleItemPressed(self, index):
item = self.model().itemFromIndex(index)
if item.checkState() == Qt.Checked:
item.setCheckState(Qt.Unchecked)
else:
item.setCheckState(Qt.Checked)
class Dialog_01(QMainWindow):
def __init__(self):
super(QMainWindow,self).__init__()
years = ['2017', '2018', '2019', '2020']
myQWidget = QWidget()
myBoxLayout = QVBoxLayout()
myQWidget.setLayout(myBoxLayout)
self.setCentralWidget(myQWidget)
self.ComboBox = CheckableComboBox()
for index, element in enumerate(years):
self.ComboBox.addItem(element)
item = self.ComboBox.model().item(index, 0)
item.setCheckState(Qt.Unchecked)
myBoxLayout.addWidget(self.ComboBox)
if __name__ == '__main__':
app = QApplication(sys.argv)
main = Dialog_01()
main.show()
sys.exit(app.exec_())