I have a custom storage and I want to implement ListModel to display it with QComboBox. For simplicity let's assume that we have a list of int as a model's data, so here is my implementation of a model and test program:
#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 ();
}
If I hit button Add only once and then check list, it looks okay, but when I hit it again, QComboBox displays only the first value and an empty line; continuing adding new elements has no effect at QComboBox.
If I click on button Add many times, then I can see the correct list in ComboBox.
I can't understand what is going on and what I do wrong.
I am using Qt5.5.1 with VS2013 x32 on Windows 7.