My simple QTableView code crashes - c++

I wrote a simple code to try and learn about QTableView. When I build my project it doesnt give any errors but when I try to run it says:
C:\Users\Eren\Documents\build-QTableViewUygulama-Desktop_Qt_5_8_0_MSVC2015_64bit-Debug\debug\QTableViewUygulama.exe exited with code 255
or
The program has unexpectedly finished.
C:\Users\Eren\Documents\build-QTableViewUygulama-Desktop_Qt_5_8_0_MSVC2015_64bit-Debug\debug\QTableViewUygulama.exe crashed.
I have some knowledge about C++ but I dont know much about Qt. I have no idea why I keep getting this error. Here is my code
//Class Model(aracmodel.cpp)
#include "aracmodel.h"
AracModel::AracModel(QObject* parent = 0) : QAbstractTableModel(parent) {
}
int AracModel::rowCount(const QModelIndex &) const {
return 3;
}
int AracModel::columnCount(const QModelIndex &) const {
return Araclar.size();
}
QVariant AracModel::data(const QModelIndex &index, int role) const {
if(role != Qt::DisplayRole && role != Qt::EditRole) return 0;
const Arac& arac = Araclar[index.row()];
switch(index.column()){
case 0 : return arac.id;
case 1 : return QString::fromStdString(arac.marka);
case 2 : return QString::fromStdString(arac.model);
default : return 0;
}
return QVariant();
}
QVariant AracModel::headerData(int section, Qt::Orientation orientation, int
role){
if(orientation != Qt::Horizontal || role != Qt::DisplayRole) return 0;
switch(section){
case 0 : return "ID";
case 1 : return "Marka";
case 2 : return "Model";
default : return 0;
}
return QVariant();
}
//Class Model (aracmodel.h)
#ifndef ARACMODEL_H
#define ARACMODEL_H
#include <QAbstractTableModel>
#include "arac.h"
class Arac;
class AracModel : public QAbstractTableModel
{
public:
QList<Arac> Araclar;
AracModel(QObject*);
int rowCount(const QModelIndex&) const override;
int columnCount(const QModelIndex&) const override;
QVariant data(const QModelIndex& index, int role) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role);
};
#endif // ARACMODEL_H
//Class Header arac.h
#ifndef ARAC_H
#define ARAC_H
#include <string>
class Arac
{
public:
int id;
std::string marka;
std::string model;
Arac(int, std::string, std::string);
};
#endif // ARAC_H
Arac::Arac(int i, std::string ma, std::string mo) : id(i), marka(ma), model(mo){} //This constructor is in arac.cpp
//MainWindow.cpp (only copying the parts i've changed)
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->tableView->setModel(model);
}
//MainWindow.hh(only copying the parts i've changed
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
AracModel* model;
~MainWindow();
private:
Ui::MainWindow *ui;
};

Instantiate model pointer using :
model = new AracModel(this);
before setting this model to tableView.
Have a look at this simple example:
http://www.thedazzlersinc.com/source/2012/06/04/qt-qtableview-example-short-and-quick/

Related

QML ListView in qml is not updated when model changed

I am trying to update a model in a QML ListView from a cpp file..
Here is my implemenation. I copied evrything to this therfore it will be a little bit bigger from code size.
this is my model implementation albummodel.h
#include <QAbstractListModel>
#include <QStringList>
#include <QQmlListProperty>
class Album
{
public:
Album(const QString &type, const QString &size);
QString type() const;
QString size() const;
private:
QString m_type;
QString m_size;
};
class AlbumModel : public QAbstractListModel
{
Q_OBJECT
Q_PROPERTY(QQmlListProperty<QObject> myModel NOTIFY listChanged)
public:
enum AlbumRoles {
TypeRole = Qt::UserRole + 1,
SizeRole
};
AlbumModel(QObject *parent = 0);
//QQmlListProperty<QObject> getList();
void addAlbum(const Album &album);
int rowCount(const QModelIndex & parent = QModelIndex()) const;
QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const;
protected:
QHash<int, QByteArray> roleNames() const;
private:
QList<Album> m_albums;
signals:
void listChanged();
#include <QAbstractListModel>
#include <QStringList>
#include <QQmlListProperty>
class Album
{
public:
Album(const QString &type, const QString &size);
QString type() const;
QString size() const;
private:
QString m_type;
QString m_size;
};
class AlbumModel : public QAbstractListModel
{
Q_OBJECT
Q_PROPERTY(QQmlListProperty<QObject> myModel NOTIFY listChanged)
public:
enum AlbumRoles {
TypeRole = Qt::UserRole + 1,
SizeRole
};
AlbumModel(QObject *parent = 0);
//QQmlListProperty<QObject> getList();
void addAlbum(const Album &album);
int rowCount(const QModelIndex & parent = QModelIndex()) const;
QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const;
protected:
QHash<int, QByteArray> roleNames() const;
private:
QList<Album> m_albums;
signals:
void listChanged();
};
This is my albummodel.cpp
#include "albummodel_mediaplayer.h"
Album::Album(const QString &type, const QString &size)
: m_type(type), m_size(size)
{
}
QString Album::type() const
{
return m_type;
}
QString Album::size() const
{
return m_size;
}
AlbumModel::AlbumModel(QObject *parent)
: QAbstractListModel(parent)
{
}
void AlbumModel::addAlbum(const Album &album)
{
beginInsertRows(QModelIndex(), rowCount(), rowCount());
m_albums << album;
endInsertRows();
emit listChanged();
}
int AlbumModel::rowCount(const QModelIndex & parent) const {
Q_UNUSED(parent);
return m_albums.count();
}
QVariant AlbumModel::data(const QModelIndex & index, int role) const {
if (index.row() < 0 || index.row() >= m_albums.count())
return QVariant();
const Album &Album = m_albums[index.row()];
if (role == TypeRole)
return Album.type();
else if (role == SizeRole)
return Album.size();
return QVariant();
}
QHash<int, QByteArray> AlbumModel::roleNames() const {
QHash<int, QByteArray> roles;
roles[TypeRole] = "type";
roles[SizeRole] = "size";
return roles;
}
/*QQmlListProperty<QObject> AlbumModel::getList(){
return QQmlListProperty<QObject>(this, *list);
}*/
and my qml file
import AlbumModel 1.0
ListView {
model: AlbumModel.myModel
delegate: playListThumbnail
Component {
id: playListThumbnail
Item {
Text {
id: albumTitleText
text: type//item_title
}}
....
}
I added the main Programm Code. Hope this is enough for a mvp
Main.cpp
void main() {
qmlRegisterType<AlbumModel>("AlbumModel",1,0,"AlbumModel");
Album g("test", "test");
AlbumModel h();
h.addAlbum(g);
}
But the model isn't updated. Which signal did i miss?

QAbstractListModel::Data() method is never called

I am trying to view a list of c++ models in qml by subclassing QAbstractListModel following this tutorial Models and Views: AbstractItemModel Example
Here is my implementation:
Item model class
class User
{
private:
QString m_macAddr;
QString m_firstName;
QString m_lastName;
public:
User();
User(const QString &mac);
QString macAddr() const;
void setMacAddr(QString &mac);
};
User::User()
{}
User::User(const QString &mac){
m_macAddr = mac;
}
QString User::macAddr() const{
return m_macAddr;
}
void User::setMacAddr(QString &mac){
if(mac == m_macAddr)
return;
m_macAddr = mac;
// emit macAddrChanged();
}
QAbstractListModel subclass
class UserListModel : public QAbstractListModel
{
Q_OBJECT
public:
// User model roles
enum roles{
macRole = Qt::UserRole + 1
};
UserListModel(QObject *parent = nullptr);
QModelIndex index(int row, int column,
const QModelIndex &parent = QModelIndex()) const override;
QModelIndex parent(const QModelIndex &index) const override;
QModelIndex getIndex(int r, int c, void *p);
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
void addUser(const User &user);
private:
QList<User> m_users;
protected:
QHash<int, QByteArray> rolesNames() const;
};
// Class inplementation.
UserListModel::UserListModel(QObject *parent)
: QAbstractListModel(parent)
{
}
void UserListModel::addUser(const User &user){
beginInsertRows(QModelIndex(), rowCount(), rowCount());
m_users << user;
endInsertRows();
}
int UserListModel::rowCount(const QModelIndex &parent) const
{
return m_users.count();
}
QVariant UserListModel::data(const QModelIndex &index, int role) const
{
if (index.row() < 0 || index.row() >= rowCount())
return QVariant();
const User &user = m_users[index.row()];
if(role == macRole){
return user.macAddr();
}
return QVariant();
}
QModelIndex UserListModel::index(int row, int column, const QModelIndex &parent) const
{
return parent;
}
QModelIndex UserListModel::parent(const QModelIndex &index) const
{
return index;
}
QModelIndex UserListModel::getIndex(int r, int c, void *p) {
return this->createIndex(r, c, p);
}
QHash<int, QByteArray> UserListModel::rolesNames() const {
QHash<int, QByteArray> roles;
roles[macRole] = "mac";
return roles;
}
main.cpp
QQmlApplicationEngine engine;
QString mac = "12:3e:3w:4r:33";
userlistModel->addUser(User(mac));
userlistModel->addUser(User(mac));
userlistModel->addUser(User(mac));
userlistModel->addUser(User(mac));
engine.rootContext()->setContextProperty("usersModel", userlistModel);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
QModelIndex id = userlistModel->getIndex(1, 0, 0);
QVariant v1 = userlistModel->data(id, Qt::UserRole + 1);
qDebug() << "===========" << v1.toString();
controller::DatabaseService<SqliteDB> *sqliteDb = new controller::DatabaseService<SqliteDB>();
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
QML
ListView{
id: listView
anchors.fill: parent
model:usersModel
delegate: Component { HorizontalListItem{mac: mac}}
}
The Problem is :
In main function I am adding 4 models to the list model but, They are shown in qml without data. althought, I am trying to view mac role.
what I tried
I tried to add a breakpoint inside methodes rolesNames() and data()
but, It seems that the compiler is not getting inside anyone of them.
I tried to invoke data() method in main function and it returns the desired data.
It is not necessary that you override the index, or parent methods, nor do you create the getIndex method. In your case you need to implement the roleNames method:
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QAbstractListModel>
#include <QDebug>
class User
{
QString m_macAddr;
public:
User(){}
User(const QString &mac): m_macAddr(mac){}
QString macAddr() const{return m_macAddr;}
void setMacAddr(QString &mac){m_macAddr = mac;}
};
class UserListModel : public QAbstractListModel
{
public:
enum roles{
macRole = Qt::UserRole + 1
};
explicit UserListModel(QObject *parent = nullptr)
: QAbstractListModel(parent){}
int rowCount(const QModelIndex &parent = QModelIndex()) const override {
if (parent.isValid())
return 0;
return m_users.count();
}
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override {
if (!index.isValid())
return QVariant();
if (index.row() < 0 || index.row() >= rowCount())
return QVariant();
const User &user = m_users[index.row()];
if(role == macRole)
return user.macAddr();
return QVariant();
}
QHash<int, QByteArray> roleNames() const override{
QHash<int, QByteArray> roles;
roles[macRole] = "mac";
return roles;
}
void addUser(const User &user){
beginInsertRows(QModelIndex(), rowCount(), rowCount());
m_users << user;
endInsertRows();
}
private:
QList<User> m_users;
};
int main(int argc, char *argv[])
{
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
UserListModel userlistModel;
QString mac = "12:3e:3w:4r:33";
userlistModel.addUser(User(mac));
userlistModel.addUser(User(mac));
userlistModel.addUser(User(mac));
userlistModel.addUser(User(mac));
QModelIndex ix = userlistModel.index(1, 0);
QVariant v = userlistModel.data(ix, UserListModel::macRole);
qDebug() << "===========" << v.toString();
engine.rootContext()->setContextProperty("usersModel", &userlistModel);
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
if (engine.rootObjects().isEmpty())
return -1;
return app.exec();
}
main.qml
import QtQuick 2.9
import QtQuick.Window 2.2
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
ListView{
anchors.fill: parent
model:usersModel
delegate: Component
{
Text{
text: model.mac
}
}
}
}

Qt Model-View custom delegate not working

I'm studying model-view programming in Qt. I'm trying to implement a custom list model with a custom delegate. It's a simple list widget with with in every row a widget with a few of label.
The widget show nothing. Debugging I noticed the delegates method are never called, so of course I'm missing something, but I can't figure out what it is.
userinfo.h
#ifndef USERINFO_H
#define USERINFO_H
#include <QString>
#include <QTime>
#include <QImage>
class UserInfo
{
public:
UserInfo();
UserInfo(const UserInfo&);
~UserInfo();
QString getTitle() const;
QString getSubtitle() const;
QTime getTime() const;
QImage getAvatar() const;
void setTitle(const QString& value);
void setSubtitle(const QString& value);
void setTime(const QTime& value);
void setAvatar(const QImage& value);
private:
UserInfo(const QString& title);
UserInfo(const QString& title, const QString& subtitle, const QTime& time, const QImage& icon);
QString title;
QString subtitle;
QTime time;
QImage avatar;
};
Q_DECLARE_METATYPE(UserInfo)
#endif // USERINFO_H
userinfo.cpp
#include "userinfo.h"
static const int _regUserInfo = qRegisterMetaType<UserInfo>("UserInfo");
UserInfo::UserInfo()
: UserInfo("User")
{
}
UserInfo::UserInfo(const QString& title)
: UserInfo(title, "Comment", QTime(0,0,0,0), QImage(":/resources/icon.png"))
{
}
UserInfo::UserInfo(const QString& title, const QString& subtitle, const QTime& time, const QImage& icon) :
title(title),
subtitle(subtitle),
time(time),
avatar(icon)
{
}
QImage UserInfo::getAvatar() const
{
return avatar;
}
void UserInfo::setAvatar(const QImage& value)
{
avatar = value;
}
QTime UserInfo::getTime() const
{
return time;
}
void UserInfo::setTime(const QTime& value)
{
time = value;
}
QString UserInfo::getSubtitle() const
{
return subtitle;
}
void UserInfo::setSubtitle(const QString& value)
{
subtitle = value;
}
QString UserInfo::getTitle() const
{
return title;
}
void UserInfo::setTitle(const QString& value)
{
title = value;
}
UserInfo::UserInfo(const UserInfo&) = default;
UserInfo::~UserInfo() = default;
userlistmodel.h
#ifndef USERMODEL_H
#define USERMODEL_H
#include <QAbstractListModel>
#include "userinfo.h"
class UserListModel : public QAbstractListModel
{
public:
UserListModel(QObject* parent = nullptr);
int rowCount(const QModelIndex& parent) const;
QVariant data(const QModelIndex& index, int role) const;
bool setData(const QModelIndex& index, const QVariant& value, int role);
QVariant headerData(int section, Qt::Orientation orientation,
int role = Qt::DisplayRole) const;
bool insertRows(int position, int row, const QModelIndex& parent=QModelIndex());
private:
QList<UserInfo> users;
};
#endif // USERMODEL_H
userlistmodel.cpp
#include "userlistmodel.h"
#include <QDebug>
UserListModel::UserListModel(QObject* parent) : QAbstractListModel(parent)
{
}
int UserListModel::rowCount(const QModelIndex& parent) const
{
Q_UNUSED(parent)
return users.size();
}
QVariant UserListModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid())
return QVariant();
if (role != Qt::DisplayRole)
return QVariant();
if (index.row() >= users.size())
return QVariant();
return QVariant::fromValue<UserInfo>(users.at(index.row()));
}
bool UserListModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
qDebug() << index.isValid();
qDebug() << (role == Qt::EditRole) ;
qDebug() <<value.canConvert<UserInfo>();
if (index.isValid() && role == Qt::EditRole && value.canConvert<UserInfo>()) {
users.replace(index.row(), value.value<UserInfo>());
emit dataChanged(index, index);
return true;
}
return false;
}
QVariant UserListModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (role != Qt::DisplayRole)
return QVariant();
if (orientation == Qt::Horizontal)
return QString("Column %1").arg(section);
else
return QString("Row %1").arg(section);
}
bool UserListModel::insertRows(int position, int rows, const QModelIndex &parent)
{
beginInsertRows(QModelIndex(), position, position+rows-1);
for (int row = 0; row < rows; ++row) {
users.insert(position, UserInfo());
}
endInsertRows();
return true;
}
userentrywidget.h
#ifndef USERENTRYWIDGET_H
#define USERENTRYWIDGET_H
#include <QWidget>
#include <QLabel>
#include "userinfo.h"
class UserEntryWidget : public QWidget
{
Q_OBJECT
public:
explicit UserEntryWidget(QWidget* parent = nullptr);
void setUserInfo(const UserInfo& user);
private:
QLabel *avatar, *title, *subtitle, *time;
};
#endif // USERENTRYWIDGET_H
userentrywidget.cpp
#include "userentrywidget.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLabel>
UserEntryWidget::UserEntryWidget(QWidget* parent) : QWidget(parent)
{
avatar = new QLabel();
title = new QLabel("title");
subtitle = new QLabel("subtitle");
time = new QLabel("00:00");
auto layout = new QHBoxLayout();
layout->addWidget(avatar);
auto centralColumn = new QVBoxLayout();
centralColumn->addWidget(title);
centralColumn->addWidget(subtitle);
layout->addItem(centralColumn);
layout->addWidget(time);
this->setLayout(layout);
}
void UserEntryWidget::setUserInfo(const UserInfo& user)
{
avatar->setPixmap(QPixmap::fromImage(user.getAvatar()));
title->setText(user.getTitle());
subtitle->setText(user.getSubtitle());
time->setText(user.getTime().toString("hh:mm"));
}
useritemdelegate.h
#ifndef USERITEMDELEGATE_H
#define USERITEMDELEGATE_H
#include <QStyledItemDelegate>
#include "userentrywidget.h"
class UserItemDelegate : public QStyledItemDelegate
{
public:
UserItemDelegate(QObject* parent = nullptr);
QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const;
void setEditorData(QWidget* editor, const QModelIndex& index) const;
};
#endif // USERITEMDELEGATE_H
useritemdelegate.cpp
#include "useritemdelegate.h"
UserItemDelegate::UserItemDelegate(QObject* parent) : QStyledItemDelegate (parent)
{
}
QWidget* UserItemDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
if (index.data().canConvert<UserInfo>()) {
UserInfo user = qvariant_cast<UserInfo>(index.data());
auto editor = new UserEntryWidget(parent);
editor->setUserInfo(user);
return editor;
} else {
return QStyledItemDelegate::createEditor(parent, option, index);
}
}
void UserItemDelegate::setEditorData(QWidget* editor, const QModelIndex& index) const
{
if (index.data().canConvert<UserInfo>()) {
UserInfo user = qvariant_cast<UserInfo>(index.data());
UserEntryWidget* userEditor = qobject_cast<UserEntryWidget*>(editor);
userEditor->setUserInfo(user);
} else {
QStyledItemDelegate::setEditorData(editor, index);
}
}
main.cpp
#include <QApplication>
#include <QListView>
#include <QListWidget>
#include <QIcon>
#include <QLabel>
#include <QDebug>
#include "userentrywidget.h"
#include "useritemdelegate.h"
#include "userlistmodel.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
qRegisterMetaType<UserInfo>("UserInfo");
qDebug() << QMetaType::type("UserInfo");
auto lm = new UserListModel();
lm->insertRows(0, 5);
auto widget = new QListView();
widget->setModel(lm);
widget->setItemDelegate(new UserItemDelegate());
widget->resize(500, 300);
widget->show();
return a.exec();
}

Spanning horizontal header in Qt

I want to merge(span) horizontal headers in QTableWidget. I tried googling for the same, but no luck and hence posting it. Please guide me.
You can subclass QHeaderView and create one section for each of the groups of columns/rows you would like to span and connect signals and slots to have them react to the different columns/rows.
The following example is for spanning the horizontal header:
#include <QtGui>
class MyHeaderModel : public QAbstractItemModel
{
public:
MyHeaderModel(QObject *parent = 0) : QAbstractItemModel(parent) {}
int columnCount(const QModelIndex &parent = QModelIndex()) const { return 2; }
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const { return QVariant(); }
QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const { return QModelIndex(); }
QModelIndex parent(const QModelIndex &index) const { return QModelIndex(); }
int rowCount(const QModelIndex &parent = QModelIndex()) const { return 0; }
};
class MyHeader : public QHeaderView
{
Q_OBJECT
public:
MyHeader(QHeaderView *header, QWidget *parent = 0) : QHeaderView(Qt::Horizontal, header), mainHeader(header)
{
setModel(new MyHeaderModel(this));
// This example uses hardcoded groups, you can extend
// this yourself to save the groups
// Group 1 is 0-2 and Group 2 is 3-4
resizeSection(0, getSectionSizes(0, 2));
resizeSection(1, getSectionSizes(3, 4));
connect(this, SIGNAL(sectionResized(int,int,int)), this, SLOT(updateSizes()));
connect(((QTableWidget *)(mainHeader->parentWidget()))->horizontalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(updateOffset()));
setGeometry(0, 0, header->width(), header->height());
updateOffset();
mainHeader->installEventFilter(this);
}
public slots:
void updateSizes()
{
setOffset(mainHeader->offset());
mainHeader->resizeSection(2, mainHeader->sectionSize(2) + (sectionSize(0) - getSectionSizes(0, 2)));
mainHeader->resizeSection(4, mainHeader->sectionSize(4) + (sectionSize(1) - getSectionSizes(3, 4)));
}
void updateOffset()
{
setOffset(mainHeader->offset());
}
protected:
bool eventFilter(QObject *o, QEvent *e)
{
if (o == mainHeader) {
if (e->type() == QEvent::Resize) {
setOffset(mainHeader->offset());
setGeometry(0, 0, mainHeader->width(), mainHeader->height());
}
return false;
}
return QHeaderView::eventFilter(o, e);
}
private:
int getSectionSizes(int first, int second)
{
int size = 0;
for (int a=first;a<=second;++a)
size += mainHeader->sectionSize(a);
return size;
}
QHeaderView *mainHeader;
};
#include "main.moc"
int main(int argc, char **argv)
{
QApplication a(argc, argv);
QWidget w;
QVBoxLayout *vbox = new QVBoxLayout;
QTableWidget *tw = new QTableWidget(5, 5);
MyHeader *h = new MyHeader(tw->horizontalHeader());
vbox->addWidget(tw);
w.setLayout(vbox);
w.show();
return a.exec();
}

Using proxy models

I've created Proxy model by subclassing QAbstractProxyModel and connected it as a model to my view. I also set up source model for this proxy model. Unfortunately something is wrong because I'm not getting anything displayed on my listView (it works perfectly when I have my model supplied as a model to view but when I supply this proxy model it just doesn't work). Here are some snippets from my code:
#ifndef FILES_PROXY_MODEL_H
#define FILES_PROXY_MODEL_H
#include <QAbstractProxyModel>
#include "File_List_Model.h"
class File_Proxy_Model: public QAbstractProxyModel
{
public:
explicit File_Proxy_Model(File_List_Model* source_model)
{
setSourceModel(source_model);
}
virtual QModelIndex mapFromSource(const QModelIndex & sourceIndex) const
{
return index(sourceIndex.row(),sourceIndex.column());
}
virtual QModelIndex mapToSource(const QModelIndex & proxyIndex) const
{
return index(proxyIndex.row(),proxyIndex.column());
}
virtual int columnCount(const QModelIndex & parent = QModelIndex()) const
{
return sourceModel()->columnCount();
}
virtual int rowCount(const QModelIndex & parent = QModelIndex()) const
{
return sourceModel()->rowCount();
}
virtual QModelIndex index(int row, int column, const QModelIndex & parent = QModelIndex()) const
{
return createIndex(row,column);
}
virtual QModelIndex parent(const QModelIndex & index) const
{
return QModelIndex();
}
};
#endif // FILES_PROXY_MODEL_H
//and this is a dialog class:
Line_Counter::Line_Counter(QWidget *parent) :
QDialog(parent), model_(new File_List_Model(this)),
proxy_model_(new File_Proxy_Model(model_)),
sel_model_(new QItemSelectionModel(proxy_model_,this))
{
setupUi(this);
setup_mvc_();
}
void Line_Counter::setup_mvc_()
{
listView->setModel(proxy_model_);
listView->setSelectionModel(sel_model_);
}
mapToSource should return an index from the source model:
virtual QModelIndex mapToSource(const QModelIndex & proxyIndex) const
{
return sourceModel()->index(proxyIndex.row(),proxyIndex.column());
}
I tested with that code:
#include <QtGui>
#include "file_proxy_model.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QDir dir(QDesktopServices::storageLocation(QDesktopServices::HomeLocation));
File_List_Model model(dir.entryList());
File_Proxy_Model proxy(&model);
QListView listView;
listView.setModel(&proxy);
listView.show();
return a.exec();
}
// In "File_List_Model.h"
class File_List_Model : public QStringListModel
{
public:
explicit File_List_Model(const QStringList & list, QObject *parent = 0)
: QStringListModel(list, parent)
{
}
};