我有一个自定义存储,我想实现ListModel以QComboBox. 为简单起见,让我们假设我们有一个int模型数据列表,所以这是我的模型和测试程序的实现:
#include <QApplication>
#include <QDebug>
#include <QAbstractListModel>
#include <QComboBox>
#include <QHBoxLayout>
#include <QPushButton>
QList<int> list;
class MyModel : public QAbstractListModel
{
public:
MyModel( QWidget* parent ):
QAbstractListModel( parent )
{}
~MyModel()
{
qDebug() << __FUNCTION__;
}
QVariant data(const QModelIndex &index, int role) const
{
if ( !index.isValid() )
return QVariant();
if ( ( role == Qt::DisplayRole ) && ( index.row() < list.size() ) )
return QString::number( list.at( index.row() ) );
return QVariant();
}
int rowCount(const QModelIndex &parent) const
{
Q_UNUSED( parent )
return list.size();
}
};
int main ( int argc, char* argv[] )
{
QApplication app ( argc, argv );
QWidget w;
QHBoxLayout* l = new QHBoxLayout();
QComboBox* c = new QComboBox( &w );
c->setModel( new MyModel( c ) );
l->addWidget( c );
QPushButton* b = new QPushButton("+");
QObject::connect( b, &QPushButton::clicked, [](){
list.push_back( qrand() );
qDebug() << list;
} );
l->addWidget( b );
b = new QPushButton("-");
QObject::connect( b, &QPushButton::clicked, [](){
if ( !list.isEmpty() )
list.pop_back();
qDebug() << list;
} );
l->addWidget( b );
w.setLayout( l );
w.show();
return app.exec ();
}
Run Code Online (Sandbox Code Playgroud)
如果我只点击按钮添加一次然后检查列表,它看起来没问题,但是当我再次点击它时,QComboBox只显示第一个值和一个空行;继续添加新元素在 处无效QComboBox。如果我多次单击“添加”按钮,则可以在ComboBox.
我无法理解发生了什么以及我做错了什么。
我使用Qt5.5.1与VS2013 x32上Windows 7。
当数据实际发生变化时,您的模型需要发出正确的信号。这通常是通过调用受保护的函数 beginInsertRows、endInsertRows 等来完成的。因为这些是受保护的,所以它们只能被内部的成员函数调用MyModel。此外,为了良好的实践,实际数据(您的list)应该只由MyModel.
首先,创建list一个私有成员MyModel。不应从外部访问它。
private:
QList<int> list;
Run Code Online (Sandbox Code Playgroud)
在 MyModel 中添加两个公共函数用于管理list:
public:
void push(int value)
{
beginInsertRows(list.size(), list.size());
list.push_back(value);
endInsertRows();
}
void pop()
{
if(list.size()>0)
{
beginRemoveRows(list.size()-1, list.size()-1);
list.pop_back();
endRemoveRows();
}
}
Run Code Online (Sandbox Code Playgroud)
在 main 中,在您的模型上保留一个指针
MyModel * m = new MyModel(c);
Run Code Online (Sandbox Code Playgroud)
然后在里面使用这些函数main()而不是list直接附加到。
QObject::connect( b, &QPushButton::clicked, [m](){
m->push(qrand());
} );
QObject::connect( b, &QPushButton::clicked, [m](){
m->pop();
} );
Run Code Online (Sandbox Code Playgroud)
等等
替代的,更多的 Qt 方式
声明push并pop为slots:
public slots:
void push()
{
beginInsertRows(list.size(), list.size());
list.push_back(qrand());
endInsertRows();
}
void pop()
{
if(list.size()>0)
{
beginRemoveRows(list.size()-1, list.size()-1);
list.pop_back();
endRemoveRows();
}
}
Run Code Online (Sandbox Code Playgroud)
并将它们直接连接到 main 中的按钮:
QObject::connect( b, &QPushButton::clicked, m, &MyModel::push);
//...
QObject::connect( b, &QPushButton::clicked, m, &MyModel::pop);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2021 次 |
| 最近记录: |