在Qt中,我想为QComBox
中的每个项目添加一个短项目字符串。这意味着当我在QComBox
中选择一个项目时,我想显示相应的短项目字符串而不是所选的项目字符串。
例如,
对于QComBox
。我添加了" aaa"," bbb"以及" aaa"我设置了一个名为" a"的短字符串,以及" b"为" bbb"
当我选择" aaa"时,我想要" a"在现场展示,而不是" aaa"。
而且我希望这些项目不像标准QComBox
那样可编辑,我的意思是外观应该与不可编辑的QComBox
相同。
如何在Qt中实现此行为,提前感谢。
答案 0 :(得分:2)
我们的想法是为组合框的下拉菜单设置自定义项目deledate,以便它使用其他数据进行显示。 ""和" b"将是主要项目文本," aaa"和" bbb"将被分配到Qt::UserRole
。工作示例:
class MyItemDelegate : public QStyledItemDelegate {
Q_OBJECT
public:
MyItemDelegate() {
fake_model.setColumnCount(1);
fake_model.setRowCount(1);
fake_model.setItem(0, 0, new QStandardItem());
}
void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index) const {
fake_model.item(0, 0)->setText(index.data(Qt::UserRole).toString());
QStyledItemDelegate::paint(painter, option, fake_model.index(0, 0));
}
private:
QStandardItemModel fake_model;
};
//...
ui->comboBox->addItem("a", "aaa");
ui->comboBox->addItem("b", "bbb");
ui->comboBox->setItemDelegate(new MyItemDelegate());
如果您想要其他人使用UserRole
,可以切换到其他角色:使用ui->comboBox->setItemData(0, "aaa", otherRole)
设置数据并更改paint
方法实施中的角色。
答案 1 :(得分:1)
根据Pavel Strakhov的建议,您不需要操纵代金券。只有当您想要对已查看项目进行非常具体的自定义时,才需要代表。在您的情况下,它足以操纵QComboBox的数据模型:
// Adding item:
void addItem( QComboBox *cb, const QString& name, const QString& userData )
{
QStandardItemModel *model = qobject_cast< QStandardItemModel * >( cb->model() );
QStandardItem *newItem = new QStandardItem();
newItem->setData( name, Qt::DisplayRole );
newItem->setData( userData , Qt::UserRole );
model->appendRow( newItem );
}
// Getting item data
void getItemData( QComboBox *cb, const int index, QString& name, QString& userData )
{
QStandardItemModel *model = qobject_cast< QStandardItemModel * >( cb->model() );
QStandardItem *item = model->item( index );
name = item ->data( name, Qt::DisplayRole ).toString();
userData = item ->data( Qt::UserRole ).toString();
}
最好在那里使用Qt MVC。您将拥有许多额外功能,例如禁用项目,添加复选框,更改字体等。
您需要为我的示例添加数据验证(检查指针/索引)。我只想展示主要想法。
答案 2 :(得分:0)
您可以从QComboBox派生自己的组合框类并覆盖这些功能,以便打开自定义菜单进行选择。在此自定义菜单中,您可以为项目使用与ComboBox本身不同的名称。所以QCombobox会保存项目&#34; a&#34;,&#34; b&#34;等等,而在菜单中你创建条目&#34; aaa&#34;,&#34; bbb&#34; 。连接&#34; a&#34;的逻辑到&#34; aaa&#34;是你的工作,但很容易。您只需使用项目的索引即可。
以下是一个示例,其中出于不同的原因实现了这个想法: http://svn.gerbilvis.org/wsvn/Gerbil/gui/widgets/ahcombobox.h http://svn.gerbilvis.org/wsvn/Gerbil/gui/widgets/ahcombobox.cpp
组合框的行为与经典组合略有不同,但可用性是相同的。在某些情况下,QComboBox使用这样的菜单来显示,在其他情况下,它会执行下拉列表。使用这种方法,它只是一个菜单。