gpt4 book ai didi

c++ - 如何在 QComboBox 中显示短值并在其下拉列表中显示长值?

转载 作者:太空宇宙 更新时间:2023-11-04 12:49:13 27 4
gpt4 key购买 nike

我正在尝试让 QComboBox 显示一个短值(例如“1”、“2”或“3”),但组合框的下拉列表显示较长的值,例如“第一”, “二号”或“三号”。

这是我所拥有的...

QString max_dropdown_len, styleSheet;

max_dropdown_len = QString::number(300);
styleSheet = "QComboBox QAbstractItemView { min-width: %1; }";

cb = new QComboBox();

model = qobject_cast<QStandardItemModel*>(cb->model());
model->setColumnCount(2);
model->appendRow(QList<QStandardItem*>() <<
(new QStandardItem("Number One")) << (new QStandardItem("1")));
model->appendRow(QList<QStandardItem*>() <<
(new QStandardItem("Number Two")) << (new QStandardItem("2")));
model->appendRow(QList<QStandardItem*>() <<
(new QStandardItem("Number Three")) << (new QStandardItem("3")));

view = qobject_cast<QListView*>(cb->view());
view->setModelColumn(0);

cb->setModelColumn(1);
cb->setStyleSheet(styleSheet.arg(max_dropdown_len));

aLayout = new QFormLayout;
aLayout->addRow(new QLabel(tr("Test: ")), cb);

aGroup = new QGroupBox(tr("Testing"));
aGroup->setLayout(aLayout);

return aGroup;

问题是,组合框只显示“1”,当我单击箭头下拉列表时,选项是“1”、“2”或“3”,而不是较长的字符串值.

我这样做是为了显示一个短值吗?想法?

最佳答案

一个可能的解决方案是将长文本添加为​​ UserData,并为选择长文本的 QComboBox 建立一个委托(delegate)。

#include <QApplication>
#include <QComboBox>
#include <QStandardItemModel>
#include <QStyledItemDelegate>

class ComboBoxDelegate: public QStyledItemDelegate{
public:
using QStyledItemDelegate::QStyledItemDelegate;
void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override{
QStyleOptionViewItem opt(option);
initStyleOption(&opt, index);
opt.text = index.data(Qt::UserRole).toString();
const QWidget *widget = opt.widget;
QStyle *style = widget ? widget->style() : QApplication::style();
style->drawControl(QStyle::CE_ItemViewItem, &opt, painter, widget);
}
};

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QComboBox combo;
combo.addItem("1", "Number One");
combo.addItem("2", "Number Two");
combo.addItem("3", "Number Three");
combo.setItemDelegate(new ComboBoxDelegate(&combo));
combo.show();
return a.exec();
}

enter image description here

关于c++ - 如何在 QComboBox 中显示短值并在其下拉列表中显示长值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49837326/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com