Qt - QVector 和模型视图 - 从列表视图获取自定义类的最佳方法是什么?
Qt - QVector and Model View - what's the best way to get a custom class from a listView?
我有一个名为Foo
的自定义类,我将此类的实例存储在向量中:
class Foo{
public:
QString name;
int second_property;
}
//...
QVector<Foo> foos = {test1, test2, test3};
我想在listView
中显示name
属性,所以我创建了一个模型,然后用名称填充它:
in .h
QStandardItemModel model;
QStandardItem* root;
QStandardItem* item;
in .cpp
root = model.invisibleRootItem();
ui->listView->setModel(&model);
foreach(Foo foo, foos){
item = new QStandardItem(foo.name);
root->appendRow(item);
}
现在,在我单击 UI 中的项后,我希望能够访问整个Foo
类及其属性和方法,因此我使用 loop 来查找我的对象:
void MainWindow::on_listView_clicked(const QModelIndex &index)
{
foreach(Foo foo, foos){
if(foo.name==index.data().toString()){
qDebug()<<"You found the object! Second property: " + foo.second_property);
}
}
}
它确实有效,但我觉得这不是很好的方法(如果两个对象具有相同的name
怎么办?
===============
有没有更好的解决方案解决这个问题?我可以放弃QVector或模型/视图列表视图或此代码中的任何其他愚蠢的东西。
TL;DR:
基本上,我想在listView
(或listWidget
(中显示对象的一个属性(QString name
(,单击它后,我想访问其类的每个属性和方法。
===============
编辑:
所以我用QAbstractListModel做了我自己的模型:
class myOwnModel : public QAbstractListModel
{
Q_OBJECT
public:
myOwnModel(const QStringList &strings={""}, QObject *parent = nullptr);
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role) const override;
Qt::ItemFlags flags(const QModelIndex &index) const;
bool setData(const QModelIndex &index, const QVariant &value,
int role = Qt::EditRole);
bool insertRows(int position, int rows, const QModelIndex &index = QModelIndex());
private:
QStringList stringList;
};
我仍然使用循环来填充这个模型QVector<Foo> foos
name
属性:
myOwnModel* myModel = new myOwnModel();
for(int row=0; row<foos.size(); row++){
myModel->insertRows(row,1);
QModelIndex index = myModel->index(row,0);
myModel->setData(index,foos[row].name);
}
ui->view->setModel(myModel);
然后我仍然使用循环来获取我想要的对象的第二个属性:
void MainWindow::on_view_clicked(const QModelIndex &index)
{
for(int i=0;i<foos.size();i++){
if(index.data().toString()==foos[i].name){
qDebug() << "You found " << foos[i].name + " and the second property is " << foos[i].second_property;
}
}
}
我正在复制数据,就像以前使用QStandartItemModel一样,对吧?
我试图像康斯坦丁T所说的那样使用QAbstractListModel,但我认为我对模型的理解不够好,并且以正确的方式使用它......
使用QStandardItemModel几乎总是一个坏主意。您正在QVector和模型中复制数据。保持数据一致性变得非常困难。
在您的情况下,更好的方法是改用QAbstractListModel。
相关文章:
- 在C#中处理C++指针而不使用unsafe的最佳方法
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 视图中的参数推导失败:take_while
- 在c代码之间共享数据的最佳方式
- 使用std::source_location报告错误的最佳实践
- 派生类销毁的最佳实践是什么
- 将寄存器设计成可由C和C++访问的外设的最佳实践
- 如何维护资源管理器项目视图中当前可见的项目列表
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- 使用QQuickFramebufferObject时同步数据的最佳方式是什么
- 在C++中向零方向近似的最佳方法
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 在另一个类视图中添加最多2个图表的正确方法是什么
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 检测win32服务创建和删除的最佳方法
- Qt - QVector 和模型视图 - 从列表视图获取自定义类的最佳方法是什么?
- XE2 - Indy TCPServer:编写和读取列表视图的最佳方式是什么