Skip to content Skip to sidebar Skip to footer

Show Item In A Qcombobox But Not In Its Popup List

I have some code to use a combobox to show a list of products. I would like to show 'Select product' in the combobox: products = ['Select product', '223', '51443' , '7335'] but I

Solution 1:

An item in the popup list can be hidden like this:

self.combo.view().setRowHidden(0, True)

However, this still allows the hidden item to be selected using the keyboard or mouse-wheel. To prevent this, the hidden item can be disabled in a slot connected to the activated signal. This means that once a valid choice has been made, the message is never shown again. To get it back (e.g. when resetting the form), the item can simply be re-enabled.

Here is a basic demo that implements all that:

enter image description here

import sys
from PyQt5 import QtCore, QtWidgets

classWindow(QtWidgets.QWidget):
    def__init__(self):
        super(Window, self).__init__()
        self.button = QtWidgets.QPushButton('Reset')
        self.button.clicked.connect(self.handleReset)
        self.combo = QtWidgets.QComboBox()
        layout = QtWidgets.QHBoxLayout(self)
        layout.addWidget(self.combo)
        layout.addWidget(self.button)
        products = ['Select product', '223', '51443' , '7335']
        self.combo.addItems(products)
        self.combo.view().setRowHidden(0, True)
        self.combo.activated.connect(self.showComboMessage)

    defshowComboMessage(self, index=-1, enable=False):
        if index:
            self.combo.model().item(0).setEnabled(enable)

    defhandleReset(self):
        self.showComboMessage(enable=True)
        self.combo.setCurrentIndex(0)

if __name__ == '__main__':

    app = QtWidgets.QApplication(sys.argv)
    window = Window()
    window.setWindowTitle('Combo Demo')
    window.setGeometry(600, 100, 100, 75)
    window.show()
    sys.exit(app.exec_())

Solution 2:

Try using:

page.comboBox.setMinimumContentsLength(30) 

Post a Comment for "Show Item In A Qcombobox But Not In Its Popup List"