7

I would like to set the text of a QComboBox to some custom text (that is not in the QComboBox's list), without adding this text as an item of the QComboBox. This behaviour is achievable on an editable QComboBox with QComboBox::setEditText(const QString & text). On a non-editable QComboBox, however, this function does nothing.

Is it possible to programmatically set the display/edit text of a non-editable QComboBox to something that is not in its list? Or do I have to find another way (e.g. use a QPushButton with a popup menu)

EDIT: Consider an editable QComboBox with InsertPolicy QComboBox::NoInsert. If the user types in something and hits enter, the entered value will be used but not added to the list. What I want is this behaviour to change the 'current' text programmatically, but without allowing the user to type in some text himself. The user can choose something from the QComboBox, but some time later, I may want to override the 'current' text.

4

4 回答 4

6

当我进行子类QComboBox化以制作复选框组合框时,我遇到了同样的问题。我编写了一个小函数来以编程方式更改组合框中显示的文本,但我不想让用户编辑该文本。解决方案是将组合框设置为可编辑:

 this->setEditable(true);

QComboBox::lineEdit()只读。参考函数:

void CheckedComboBox::setText(QString text)
{
   QLineEdit *displayedText = this->lineEdit();
   displayedText->setText(text);
   displayedText->setReadOnly(true);
}
于 2014-10-01T14:21:22.097 回答
2

重新实现paintEvent:https ://github.com/qt/qtbase/blob/28d1d19a526148845107b631612520a3524b402b/src/widgets/widgets/qcombobox.cpp#L2995

并添加这一行:opt.currentText = QString(tr("My Custom Text"));

例子 :

QCustomCheckComboBoxFilter.h

...
protected:
    void paintEvent(QPaintEvent *e) Q_DECL_OVERRIDE;
...

QCustomCheckComboBoxFilter.cpp

...
void QCustomCheckComboBoxFilter::paintEvent(QPaintEvent *)
{
    QStylePainter painter(this);
    painter.setPen(palette().color(QPalette::Text));

    // draw the combobox frame, focusrect and selected etc.
    QStyleOptionComboBox opt;
    initStyleOption(&opt);
    opt.currentText = QString(tr("My Custom Text"));
    painter.drawComplexControl(QStyle::CC_ComboBox, opt);

    // draw the icon and text
    painter.drawControl(QStyle::CE_ComboBoxLabel, opt);
}
...
于 2017-08-31T08:10:26.943 回答
1

我最终使用了QPushButton带有弹出菜单的 a 。QComboBox我将我在我的列表中的项目添加QActions到菜单中。菜单可以设置QPushButton

QPushButton::setMenu(QMenu* menu)

. 按钮上的文本可以很容易地设置

QPushButton::setText(const QString &)

并且与弹出菜单中的文本无关,这是我想要的。

于 2013-04-19T08:28:15.570 回答
1

我假设您想要一个组合框,其中“A”、“B”、“C”作为实际数据,“这是 A”、“这是 B”和“这是 c”作为 QComboBox 中显示的内容。这是代码:

box.addItems(QStringList () << "This is A"<< "This is B"<< "This is C");
box.setItemData(0, "A");
box.setItemData(1, "B");
box.setItemData(2, "C");

您可以使用以下代码获取实际数据:

QString actual = box.itemData(0).toString();//actual will be = "A";
qDebug()<<actual;//"A"

注意:您几乎可以为组合框项设置所需的每种数据类型。更重要的是,您可以使用setItemData的第三个参数为每个项目设置更多的附加数据。

于 2013-04-18T11:26:40.967 回答