首页 > 解决方案 > PyQt5 ComboBox 虚拟占位符

问题描述

我碰巧使用了 qcombobox,但找不到添加虚拟占位符的方法(就像我们在 tkinter 中一样)。例如,我想要的组合框是这样的:

- 选一个 -

苹果

香蕉

猕猴桃

我已经有了元素;Apple、Banana、Kiwi 就位,但我希望--Choose One--在我单击它时消失。

**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.

标签: pythonpyqt5qcombobox

解决方案


(在示例中)的set()方法等价于的属性:ttk.ComboboxplaceholderTextQComboBox

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

推荐阅读