3

Select product

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 do not want the user to be able to select the "Select product" item. I just want the user to know what this combobox is used for selecting the product, and I do not wish to use QLabel to identify it.

page.comboBox.addItems(products)
page.comboBox.setPlaceHolderText("Please select")
page.comboBox.setGeometry(150, 30, 105, 40)
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
hope
  • 39
  • 4
  • 1
    Possible duplicate of [QComboBox - How to set hint text on combo box](https://stackoverflow.com/questions/6327964/qcombobox-how-to-set-hint-text-on-combo-box) – Frieder Nov 06 '19 at 08:52
  • @Frieder i tried using page.comboBox.lineEdit().setPlaceHolderText("Please select"); but it appears system mentions that object has no attribute of setplaceholdertext – hope Nov 06 '19 at 14:55

2 Answers2

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

class Window(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)

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

    def handleReset(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_())
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
0

Try using:

page.comboBox.setMinimumContentsLength(30) 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114