gpt4 book ai didi

c++ - 如何在数据更改时强制模型更新 QComboBox?

转载 作者:行者123 更新时间:2023-12-04 17:24:04 26 4
gpt4 key购买 nike

我为 QComboBox 创建了模型:

#ifndef QCOMBOBOXMODEL_H
#define QCOMBOBOXMODEL_H

#include <QModelIndex>


class QComboBoxModel : public QAbstractListModel
{
public:
QComboBoxModel(QObject *parent=nullptr);
int rowCount(const QModelIndex &) const;
QVariant data(const QModelIndex &index, int role) const;
void populate(const QList<QPair<int,QString>> &values);

private:
QList<QPair<int,QString>> values;
};

#endif // QCOMBOBOXMODEL_H
代码
#include "qcomboboxmodel.h"

#include <QModelIndex>

QComboBoxModel::QComboBoxModel(QObject *parent)
:QAbstractListModel(parent)
{
}

int QComboBoxModel::rowCount(const QModelIndex &) const
{
return values.count();
}


QVariant QComboBoxModel::data( const QModelIndex &index, int role ) const
{

QVariant value;

switch ( role )
{
case Qt::DisplayRole: //string
{
value = this->values.value(index.row()).second;
}
break;

case Qt::UserRole: //data
{
value = this->values.value(index.row()).first;
}
break;

default:
break;
}

return value;
}

void QComboBoxModel::populate(const QList<QPair<int,QString>> &values)
{
this->values = values;
}
现在我用它
    values.append(QPair<int,QString>(-1,"Select item"));
values.append(QPair<int,QString>(10,"item1(0)"));
values.append(QPair<int,QString>(11,"item1(1)"));
values.append(QPair<int,QString>(21,"item1(2)"));
values.append(QPair<int,QString>(32,"item1(3)"));
values.append(QPair<int,QString>(44,"item1(4)"));

newidx = 50;


model = new QComboBoxModel();
model->populate(values);
this->ui->comboBox->setModel(model);
并在按钮上单击我将新项目添加到组合框
newidx++;
QString strIdx = QString().number(newidx);
values.append(QPair<int,QString>(newidx,"New item("+strIdx+")"));

model = new QComboBoxModel();
model->populate(values);
this->ui->comboBox->setModel(model);
它似乎一切正常,但这里的问题是我每次向组合框数据添加新项目时都需要重新创建模型
model = new QComboBoxModel();
model->populate(values);
this->ui->comboBox->setModel(model);
这是这样做的正确方法吗?或者还有另一种方法可以在数据更新时强制模型更新组合框?

最佳答案

根据文档中的“模型子类化引用”,您必须做更多的事情来制作可编辑的模型。是否有理由不使用像 QStandardItemModel 这样的现成模型?

    comboModel = new QStandardItemModel(0, 2, this);
ui->comboBox1->setModel(comboModel);
comboModel->insertRow(0);
comboModel->setData(comboModel->index(0, 0), -1);
comboModel->setData(comboModel->index(0, 1), "Select item");
//and so on
//and the data is available as
int number = comboModel->data(comboModel->index(0, 0)).toInt();
QString itemtext = comboModel->data(comboModel->index(0, 1)).toString();

关于c++ - 如何在数据更改时强制模型更新 QComboBox?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64530632/

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