QComboBox model
Verfasst: 26. November 2005 12:06
Hallo zusammen,
ich versuche eine QComboBox an ein Datenmodel zu binden. Dazu habe ich mein eigenes Model implementiert
wenn ich jetzt einer ComboBox das Model zuweise, dann kann ich zwar die Einträge des Datenmodels sehen, aber auswählen kann ich sie nicht. Sprich, die Combobox klappt aus -- mit allen Einträgen --, ich wähle einen Eintrag aus, die ComboBox Auswahl bleibt jedoch leer. Wieso?
Hier noch die main()
Das Ganze mit Qt 4.0.1 unter Opensuse 10.0
ich versuche eine QComboBox an ein Datenmodel zu binden. Dazu habe ich mein eigenes Model implementiert
Code: Alles auswählen
#ifndef MYMODEL_H_
#define MYMODEL_H_
#include <QAbstractListModel>
#include <QStringList>
class MyModel : public QAbstractListModel
{
Q_OBJECT
public:
MyModel(const QStringList&, QObject*);
virtual ~MyModel();
int rowCount(const QModelIndex&) const;
QVariant data(const QModelIndex&, int role) const;
bool setData(const QModelIndex&, const QVariant&, int);
QVariant headerData(int, Qt::Orientation, int) const;
Qt::ItemFlags flags(const QModelIndex&) const;
private:
QStringList entries;
};
#endif /*MYMODEL_H_*/
#include "mymodel.h"
MyModel::MyModel(const QStringList &strings, QObject *parent)
: QAbstractListModel(parent), entries(strings)
{
}
MyModel::~MyModel()
{
}
int MyModel::rowCount(const QModelIndex &parent = QModelIndex()) const
{
Q_UNUSED(parent);
return entries.count();
}
QVariant MyModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid()) {
return QVariant();
}
if (index.row() < 0 || index.row() >= entries.size()) {
return QVariant();
}
if (role == Qt::DisplayRole) {
return entries.at(index.row());
} else {
return QVariant();
}
}
bool MyModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
if (index.isValid() && role == Qt::EditRole) {
entries.replace(index.row(), value.toString());
emit dataChanged(index, index);
return true;
}
return false;
}
QVariant MyModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role != Qt::DisplayRole) {
return QVariant();
}
if (orientation == Qt::Horizontal) {
return QString(tr("Columnt %1")).arg(section);
} else {
return QString(tr("Row %1")).arg(section);
}
}
Qt::ItemFlags MyModel::flags(const QModelIndex &index) const
{
if (!index.isValid()) {
return Qt::ItemIsEnabled;
}
return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
}Hier noch die main()
Code: Alles auswählen
#include <QApplication>
#include <QComboBox>
#include "mymodel.h"
int main(int argc, char **argv) {
QApplication app(argc, argv);
QStringList entries;
entries << "eins" << "zwei";
MyModel *model = new MyModel(entries, 0);
QComboBox cBox;
cBox.setModel(model);
cBox.show();
return app.exec();
}