Search code examples
pythonpyqtqcombobox

PyQT: How to set Combobox Read-Only


I know there is .setEnabled(bool) method available for Combobox widget. But aside from making it unavailable this method grays this widget out. What I need is to set Combobox so it appears an active but yet remains read only. Any ideas?


Solution

  • One way to do this would be to clobber the appropriate event handlers. This could be done with either a subclass:

    class ComboBox(QtGui.QComboBox):
        def __init__(self, parent):
            QtGui.QComboBox.__init__(self, parent)
            self.readonly = False
    
        def mousePressEvent(self, event):
            if not self.readonly:
                QtGui.QComboBox.mousePressEvent(self, event)
    
        def keyPressEvent(self, event):
            if not self.readonly:
                QtGui.QComboBox.keyPressEvent(self, event)
    
        def wheelEvent(self, event):
            if not self.readonly():
                QtGui.QComboBox.wheelEvent(self, event)
    

    or with an event-filter:

    class Window(QtGui.QWidget):
        def __init__(self):
            QtGui.QWidget.__init__(self)  
            self.combo = QtGui.QComboBox(self)
            self.combo.readonly = False
            self.combo.installEventFilter(self)
            ...
    
        def eventFilter(self, source, event):
            if (source is self.combo and self.combo.readonly and (
                event.type() == QtCore.QEvent.MouseButtonPress or
                event.type() == QtCore.QEvent.KeyPress or
                event.type() == QtCore.QEvent.Wheel)):
                return True
            return QtGui.QWidget.eventFilter(self, source, event)
    

    Personally, though, I would prefer to either disable the combo box, or perhaps reset its list of items so there was only one choice.