Question

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?

Was it helpful?

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.

OTHER TIPS

Its a little late but if someone need a ComboBox which is readonly after setting a text to it you can use the setEnabled() method which disable any Qwidget.

so

self.cb = QComboBox()
self.cb.setEditText("Whatever")
self.cb.setEnabled(False)

I hope i could help

cb=QComboBox()
cb.lineEdit().setReadOnly(True)

or

LE=QLineEdit()
LE.setReadOnly(True)
self.comboBox.setLineEdit(LE)

QComboBox has a method lineEdit. just pass it so it can access QLineEdit methods

i hope this is what you're looking for.

your answer is you need to set the setEditable as False.

self.comboBox.setEditable(False)

and, you can also achieve this by not setting the Editable Flag in the Model

def flags( self,index):
    return QtCore.Qt.ItemIsEnabled |QtCore.Qt.ItemIsSelectable

This is unrelated but you seem to ask a lot of questions that can be solved just by looking at the PyQt Class Reference, We are happy to help you but asking questions that can be solved easily doesn't make sense and is a waste of your valuable time .

Here is the link to the reference . Reference Link

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top