[英]PyQt5 ComboBox dummy placeholder
我碰巧使用了 qcombobox,但找不到添加虚拟占位符的方法(就像我们在 tkinter 中所做的那样)。 例如,我想要的 combobox 是这样的:
- 选一个 -
苹果
香蕉
猕猴桃
我已经有了要素; Apple、Banana、Kiwi 就位,但我希望——选择一个——在我单击它时消失。
**Tkinter version**
from tkinter import ttk
#---
#some code here
#---
lst = ['Apple','Banana','Kiwi']
self.w0 = ttk.Combobox(self, values = lst, state='readonly')
self.w0.set('--Choose One--') ### This is the functionality that I need
self.w0.pack()
**PyQt version**
from PyQt5 import QtWidgets
lst = ['Apple','Banana','Kiwi']
#---
#some code here
#---
self.comboBox = QtWidgets.QComboBox()
self.comboBox.addItems(lst)
self.layout.addWidget(self.comboBox) ## self.layout is defined but not shown here
### I might add it as an item of the comboBox like
### self.comboBox.addItem('--Choose One--') but it then becomes selectable
### which I don't want it to.
等效于ttk.Combobox
的set()
方法(在示例中)是QComboBox
的placeholderText
属性:
self.comboBox.setPlaceholderText("--Choose One--")
这只是 Qt 5.15.2 中占位符文本错误的简单解决方法,这是非常重要的版本,因为它是 Qt5 有史以来的最后一个非商业版本。 在 Qt 5.15.2 中,当isEditable
为 false 时,占位符文本不可见。 它是用 C++ 编写的,但您可以弄清楚如何将其转换为 Python。
#include <QApplication>
#include <QComboBox>
#include <QLabel>
#include <QVBoxLayout>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QComboBox combo;
combo.show();
combo.addItem("AAAA");
combo.addItem("BBBB");
// The following line does not work e.g. in Qt 5.15.2.
//combo.setPlaceholderText("Select something...");
// This is a simple workaround:
auto space = QString(" ");
auto placeholder = new QLabel(space + "Select something...");
combo.setLayout(new QVBoxLayout());
combo.layout()->setContentsMargins(0, 0, 0, 0);
combo.layout()->addWidget(placeholder);
QObject::connect(&combo, &QComboBox::currentIndexChanged, &combo, [placeholder](int index){ placeholder->setVisible(index == -1); });
combo.setCurrentIndex(-1);
return a.exec();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.