我正在处理的应用程序GUI需要一个下拉框供用户选择项目。当应用程序启动时,该下拉框将显示一条提示文本,类似于“请选择”,而不是显示下拉框的第一项。我找不到任何设置提示文本的方法在http://doc.qt.io/qt-5/qcombobox.html#currentText-prop上。提前感谢!
如果QComboBox
是可编辑的,那么有一个优雅的解决方案:点击此处了解更多
myQComboBox->lineEdit()->setPlaceHolderText("Please select");
不可编辑
的QComboBox
中没有QLineEdit
,因此这种方法对它们无效。
import sys
from PyQt5.QtCore import Qt, QT_VERSION_STR, QAbstractProxyModel, QModelIndex, QItemSelection
from PyQt5.QtGui import QStandardItemModel, QStandardItem
from PyQt5.QtWidgets import (QApplication, QGridLayout, QWidget, QComboBox)
from typing import Any
class Main(QWidget):
def __init__(self):
super().__init__()
self.setGeometry(50,50,320,200)
self.setWindowTitle(f"Qt Version {QT_VERSION_STR}")
layout = QGridLayout()
cmbox = QComboBox()
model = QStandardItemModel()
for i in range(1, 11):
model.appendRow(QStandardItem(f"Item {i}"))
cmbox.setModel(ProxyModel(model, '---PlaceholderText---'))
cmbox.setCurrentIndex(0)
layout.addWidget(cmbox, 0, 0)
self.setLayout(layout)
self.show()
class ProxyModel(QAbstractProxyModel):
def __init__(self, model, placeholderText='---', parent=None):
super().__init__(parent)
self._placeholderText = placeholderText
self.setSourceModel(model)
def index(self, row: int, column: int, parent: QModelIndex = ...) -> QModelIndex:
return self.createIndex(row, column)
def parent(self, index: QModelIndex = ...) -> QModelIndex:
return QModelIndex()
def rowCount(self, parent: QModelIndex = ...) -> int:
return self.sourceModel().rowCount()+1 if self.sourceModel() else 0
def columnCount(self, parent: QModelIndex = ...) -> int:
return self.sourceModel().columnCount() if self.sourceModel() else 0
def data(self, index: QModelIndex, role: int = Qt.DisplayRole) -> Any:
if index.row() == 0 and role == Qt.DisplayRole:
return self._placeholderText
elif index.row() == 0 and role == Qt.EditRole:
return None
else:
return super().data(index, role)
def mapFromSource(self, sourceIndex: QModelIndex):
return self.index(sourceIndex.row()+1, sourceIndex.column())
def mapToSource(self, proxyIndex: QModelIndex):
return self.sourceModel().index(proxyIndex.row()-1, proxyIndex.column())
def mapSelectionFromSource(self, sourceSelection: QItemSelection):
return super().mapSelection(sourceSelection)
def mapSelectionToSource(self, proxySelection: QItemSelection):
return super().mapSelectionToSource(proxySelection)
def headerData(self, section: int, orientation: Qt.Orientation, role: int = Qt.DisplayRole):
if not self.sourceModel():
return None
if orientation == Qt.Vertical:
return self.sourceModel().headerData(section-1, orientation, role)
else:
return self.sourceModel().headerData(section, orientation, role)
def removeRows(self, row: int, count: int, parent: QModelIndex = ...) -> bool:
return self.sourceModel().removeRows(row, count -1)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Main()
sys.exit(app.exec_())
无法为QComboBox
设置占位符文本。但是您可以解决此问题。使用setEditText(const QString&)
槽来设置您的文本。如果用户选择了comboBox
中的项目,则该项目的文本将被设置。但是,如果用户选择文本,删除它,并选择其他控件元素(组合框失去焦点),则您的文本将不再存在。可以通过继承QComboBox
并重新实现focusOutEvent(...)
来解决这个问题,在其中检查:if (currentIndex() == -1) setEditText(tr("Please select"));
。不要忘记首先调用QComboBox::focusOutEvent(...)
。
这里有一个更简单的解决方案,用于解决Qt 5.15.2中的占位符文本错误,这是非常重要的版本,因为它是Qt5的最后一个非商业版本。它修复了当combo.isEditable() == false
时不可见的占位符文本。
#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();
}
CB_SETCUEBANNER
消息。使用非原生小部件会有一些成本。 - Cody Gray