How can I set the enabled property of a row of a QComboBox
? I want it to have some disabled and some enabled rows.
Asked
Active
Viewed 3,913 times
3 Answers
3
Here is a working example of a QComboBox, where items 1 and 4 (as specified in the list disable
) are disabled. I used this example. See also the documentation for the setData method.
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_())

Junuxx
- 14,011
- 5
- 41
- 71
-
1Compatibility note: if you're using PySide rather than PyQt, replace `QtCore.QVariant(0)` with `0`. – Mark Dickinson Jul 11 '14 at 15:12
1
Based on this answer, we can simplify Junuxx's answer to :
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_())
0
Add each QComboBox
from a row to a list, then work through the list setting the state.
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_())

Gary Hughes
- 4,400
- 1
- 26
- 40
-
-
Do you mean you interpreted the question as 'a row of comboboxes'? I hadn't thought of that. After seeing my edit to the question, what do you think is more likely? – Junuxx Jun 19 '12 at 13:30