Show item in a QComboBox but not in its popup list

爷,独闯天下 提交于 2019-12-10 21:15:29

问题


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)

回答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:

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_())



回答2:


Try using:

page.comboBox.setMinimumContentsLength(30) 


来源:https://stackoverflow.com/questions/58726091/show-item-in-a-qcombobox-but-not-in-its-popup-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!