PyQt设置了一行QComboBox的启用属性

时间:2012-06-19 11:27:14

标签: python qt pyqt python-2.7 pyqt4

如何设置QComboBox行的启用属性?我希望它有一些禁用和一些启用的行。

3 个答案:

答案 0 :(得分:3)

以下是QComboBox的工作示例,其中禁用了项目1和4(在列表disable中指定)。我使用this示例。另请参阅setData方法的文档。

from PyQt4 import QtCore, QtGui
import sys

class Foo(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)

        items = ['foo', 'bar', 'yib','nuz', 'pip', 'rof']
        cb = QtGui.QComboBox(self)
        for i in items:
            cb.addItem(i)

        disable = [1,4]
        for i in disable:
            j = cb.model().index(i,0)
            cb.model().setData(j, QtCore.QVariant(0), QtCore.Qt.UserRole-1)

if __name__ == "__main__":
    app = QtGui.QApplication([])
    foobar = Foo()
    foobar.show()
    sys.exit(app.exec_())

答案 1 :(得分:1)

基于MSDN: Addition Operator (+) (VBScript),我们可以简化Junuxx的答案:

from PyQt4 import QtGui
import sys


class Foo(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)

        items = ['foo', 'bar', 'yib', 'nuz', 'pip', 'rof']
        cb = QtGui.QComboBox(self)
        for i in items:
            cb.addItem(i)

        disable = [1, 4]
        for i in disable:
            cb.model().item(i).setEnabled(False)

if __name__ == "__main__":
    app = QtGui.QApplication([])
    foobar = Foo()
    foobar.show()
    sys.exit(app.exec_())

答案 2 :(得分:0)

将每行QComboBox添加到列表中,然后通过列表设置状态。

from PyQt4 import QtCore, QtGui
import sys

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()                
        self.create_combos()

    def create_combos(self):
        widget = QtGui.QWidget()
        self.setCentralWidget(widget)   

        # Create combo boxes and add them to a list.
        self.combo1 = QtGui.QComboBox()
        self.combo2 = QtGui.QComboBox()
        self.combo3 = QtGui.QComboBox()
        self.combobox_row = [self.combo1, self.combo2, self.combo3]

        # Create a toggle button and connect it to the toggle method.
        self.button = QtGui.QPushButton('Toggle')
        self.button.setCheckable(True)
        self.button.setChecked(True)
        self.button.toggled.connect(self.enable_combobox_row)

        # Create layout.
        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(self.combo1)
        vbox.addWidget(self.combo2)
        vbox.addWidget(self.combo3)
        vbox.addWidget(self.button)
        widget.setLayout(vbox)

    def enable_combobox_row(self, enabled):
        # Work through combo boxes and set the passed enabled state.
        for combobox in self.combobox_row:
            combobox.setEnabled(enabled)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    mainwindow = MainWindow()
    mainwindow.show()
    sys.exit(app.exec_())