【问题标题】:Show item in a QComboBox but not in its popup list在 QComboBox 中显示项目,但不在其弹出列表中
【发布时间】:2020-03-02 16:44:32
【问题描述】:

我有一些代码可以使用组合框来显示产品列表。我想在组合框中显示“选择产品”:

products = ["Select product", "223", "51443" , "7335"]

但我不希望用户能够选择“选择产品”项。我只是想让用户知道这个组合框是用来选择产品的,我不想用QLabel来识别它。

page.comboBox.addItems(products)
page.comboBox.setPlaceHolderText("Please select")
page.comboBox.setGeometry(150, 30, 105, 40)

【问题讨论】:

标签: python pyqt5 qcombobox


【解决方案1】:

弹出列表中的项目可以这样隐藏:

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

但是,这仍然允许使用键盘或鼠标滚轮选择隐藏的项目。为了防止这种情况,可以在连接到activated 信号的插槽中禁用隐藏项。这意味着一旦做出了有效的选择,该消息将不再显示。要恢复它(例如,在重置表单时),可以简单地重新启用该项目。

这是一个实现所有这些的基本演示:

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】:

    尝试使用:

    page.comboBox.setMinimumContentsLength(30) 
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-26
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    • 2012-04-17
    • 2014-02-27
    相关资源
    最近更新 更多