在 QComboBox 中显示项目但不在其弹出列表中 [英] 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"]
但我不希望用户能够选择选择产品"项目.我只是想让用户知道这个组合框是用来选择产品的,我不想用 QLabel
来识别它.
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)
推荐答案
弹出列表中的项目可以这样隐藏:
An item in the popup list can be hidden like this:
self.combo.view().setRowHidden(0, True)
但是,这仍然允许使用键盘或鼠标滚轮选择隐藏的项目.为了防止这种情况,可以在连接到 activated
信号的插槽中禁用隐藏项目.这意味着一旦做出了有效的选择,该消息将不再显示.要恢复它(例如在重置表单时),只需重新启用该项目即可.
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_())
这篇关于在 QComboBox 中显示项目但不在其弹出列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!