简体   繁体   中英

PyQt5 ComboBox dummy placeholder

I happen to have used the qcombobox, but could not find a way to add a dummy placeholder (like we have in tkinter). For example, the combobox I'd like to have is something like this:

--Choose One--

Apple

Banana

Kiwi

I already have the elements; Apple, Banana, Kiwi in place but I want the --Choose One-- vanished when I click on it.

**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.Comboboxset()方法(在示例中)是QComboBoxplaceholderText属性:

self.comboBox.setPlaceholderText("--Choose One--")

Here is just a simple workaround for the placeholder text bug in Qt 5.15.2, which is very important version because it is the last non-commercial version ever for Qt5. In Qt 5.15.2 the placeholder text is not visible when isEditable is false. It is in C++ but you can figure it out how to translate it to 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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM