I want to write a proxy model that groups a flat table into a tree by the first (n) columns, similar to this UI library for React.
I am struggling to get this to work, even in its simplest form:
First question is: do i need to implement all four of the following or only mapToSource and mapFromSource?
https://doc.qt.io/qt-6/qidentityproxymodel.html#parent
https://doc.qt.io/qt-6/qidentityproxymodel.html#index
https://doc.qt.io/qt-6/qidentityproxymodel.html#mapToSource
https://doc.qt.io/qt-6/qidentityproxymodel.html#mapFromSource
If so, how can I achieve the behavior with the following code? I am trying around but I always come up with deadlocks or weird behavior.
#include <QApplication>
#include <QSqlDatabase>
#include <QSqlTableModel>
#include <QSqlError>
#include <QSqlQuery>
#include <QTreeView>
#include <QIdentityProxyModel>
class GroupByFirstColumnProxyModel : public QIdentityProxyModel {
Q_OBJECT
public:
GroupByFirstColumnProxyModel(QObject *parent = nullptr)
: QIdentityProxyModel{parent} {}
~GroupByFirstColumnProxyModel() {}
void setSourceModel(QAbstractItemModel* sourceModel) override {
return QIdentityProxyModel::setSourceModel(sourceModel);
}
int columnCount (const QModelIndex &parent=QModelIndex()) const override {
auto cols = QIdentityProxyModel::columnCount(parent);
qDebug() << "columnCount" << parent << cols << parent.isValid();
return cols;
}
QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override {
qDebug() << "index" << row << column << parent;
return QIdentityProxyModel::index(row, column, parent);
}
QModelIndex parent(const QModelIndex &child) const override {
if (!child.isValid()) {
return QModelIndex();
}
qDebug() << "parent" << child;
return QIdentityProxyModel::parent(child);
}
QModelIndex mapFromSource(const QModelIndex &sourceIndex) const override {
qDebug() << "mapFromSource" << sourceIndex;
return QIdentityProxyModel::mapFromSource(sourceIndex);
}
QModelIndex mapToSource(const QModelIndex &proxyIndex) const override {
if (!proxyIndex.isValid()) {
return QModelIndex();
}
qDebug() << "mapToSource" << proxyIndex;
return QIdentityProxyModel::mapToSource(proxyIndex);
}
};
static bool createConnection()
{
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(":memory:");
if (!db.open()) {
return false;
}
QSqlQuery query;
query.exec("create table simple (A int, B int)");
query.exec("insert into simple values(1, 2)");
return true;
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
if (!createConnection())
return EXIT_FAILURE;
QSqlTableModel *model = new QSqlTableModel;
model->setTable("simple");
model->select();
QTreeView *view = new QTreeView;
GroupByFirstColumnProxyModel *proxy = new GroupByFirstColumnProxyModel;
proxy->setSourceModel(model);
view->setModel(proxy);
view->show();
return a.exec();
}
#include "main.moc"
I want to copy the selected column of a QTableWidget to another one.
So I tried to make selected columns draggable by adding this code:
void makeDraggable(QTableWidget *table)
{
table->setDragEnabled(true);
table->setAcceptDrops(true);
table->setSelectionBehavior(QAbstractItemView::SelectColumns);
}
Result I got:
But I want to drag a whole column (horizontal and vertical headers) by clicking on headers only, not on cells, and copy its data to another table including the header text.
Dragging between different tables inside one application can be done with reimplementing custom QHeaderView and QTableWidget. In my example I generate text with indecies of table and column for drag event. Custom header:
#include <QHeaderView>
class ITableManager;
class DraggableHeaderView : public QHeaderView
{
Q_OBJECT
public:
explicit DraggableHeaderView(Qt::Orientation orientation, QWidget *parent = 0);
int tag() const;
void setTag(const int tag);
void setTableManager(ITableManager* manager);
protected:
void mouseMoveEvent(QMouseEvent *e);
void dragEnterEvent(QDragEnterEvent *event);
void dragMoveEvent(QDragMoveEvent *event);
void dropEvent(QDropEvent *event);
signals:
public slots:
private:
int m_tag; //internal index of table
ITableManager *m_tableManager; //manager will convert table index into pointer
};
Custom header cpp
#include <QMouseEvent>
#include <QDrag>
#include <QMimeData>
#include <QDebug>
#include <QTableWidget>
#include <ITableManager.h>
DraggableHeaderView::DraggableHeaderView(Qt::Orientation orientation, QWidget *parent) :
QHeaderView(orientation, parent)
{
m_tag = 0;
m_tableManager = 0;
setAcceptDrops(true);
}
void DraggableHeaderView::mouseMoveEvent(QMouseEvent *e)
{
if (e->buttons() & Qt::LeftButton)
{
int index = logicalIndexAt(e->pos());
QDrag *drag = new QDrag(this);
QMimeData *mimeData = new QMimeData;
//custom drag text with indecies inside
QString mimeTxt = "MoveHeader;Table:" + QString::number(m_tag) +
";Index:" + QString::number(index);
mimeData->setText(mimeTxt);
drag->setMimeData(mimeData);
Qt::DropAction dropAction = drag->exec();
}
}
int DraggableHeaderView::tag() const
{
return m_tag;
}
void DraggableHeaderView::setTag(const int tag)
{
m_tag = tag;
}
void DraggableHeaderView::dragEnterEvent(QDragEnterEvent *event)
{
if (!m_tableManager)
{
event->ignore();
return;
}
QString dragText = event->mimeData()->text();
int index = dragText.indexOf("MoveHeader;");
if (index == 0)
{
event->accept();
}
else
{
event->ignore();
}
}
void DraggableHeaderView::dropEvent(QDropEvent *event)
{
if (!m_tableManager)
{
event->ignore();
return;
}
QStringList dragText = event->mimeData()->text().split(';');
if (dragText.count() < 3 || dragText.at(0) != "MoveHeader")
{
event->ignore();
return;
}
int tableIndex = dragText.at(1).mid(6).toInt();//6 - length 'Table:'
QTableWidget* tableSrc = m_tableManager->getTableFromIndex(tableIndex);
if (!tableSrc)
{
event->ignore();
return;
}
//dst table as parent for header view
QTableWidget *tableDst = qobject_cast<QTableWidget*> (this->parentWidget());
if (!tableDst)
{
event->ignore();
return;
}
//move column: modify for your needs
//now moves only items text
int columnIndex = logicalIndexAt(event->pos());
int srcColumnIndex = dragText.at(2).mid(6).toInt(); //6 - length of 'Index:'
tableDst->insertColumn(columnIndex);
for (int iRow = 0; iRow < tableDst->rowCount() && iRow < tableSrc->rowCount(); ++iRow)
{
if (tableSrc->item(iRow, srcColumnIndex))
{
tableDst->setItem(iRow, columnIndex,
new QTableWidgetItem(tableSrc->item(iRow, srcColumnIndex)->text()));
}
else
{
tableDst->setItem(iRow, columnIndex, new QTableWidgetItem());
}
}
tableSrc->removeColumn(srcColumnIndex);
}
void DraggableHeaderView::setTableManager(ITableManager *manager)
{
m_tableManager = manager;
}
Now create custom QTableWidget with DraggableHeaderView inside
class CustomTableWidget : public QTableWidget
{
Q_OBJECT
public:
explicit CustomTableWidget(QWidget *parent = 0);
void setTag(const int tag);
void setTableManager(ITableManager* manager);
};
CustomTableWidget::CustomTableWidget(QWidget *parent) :
QTableWidget(parent)
{
DraggableHeaderView *headerView = new DraggableHeaderView(Qt::Horizontal, this);
setHorizontalHeader(headerView);
setAcceptDrops(true);
}
void CustomTableWidget::setTag(const int tag)
{
DraggableHeaderView *header = qobject_cast<DraggableHeaderView*> (horizontalHeader());
if (header)
{
header->setTag(tag);
}
}
void CustomTableWidget::setTableManager(ITableManager *manager)
{
DraggableHeaderView *header = qobject_cast<DraggableHeaderView*> (horizontalHeader());
if (header)
{
header->setTableManager(manager);
}
}
For converting table index to pointer I use ITableManager
class ITableManager
{
public:
virtual QTableWidget* getTableFromIndex(const int index) = 0;
};
And implement it in QMainWindow
class MainWindow : public QMainWindow, ITableManager
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
QTableWidget* getTableFromIndex(const int index);
}
QTableWidget * MainWindow::getTableFromIndex(const int index)
{
switch (index)
{
case 1:
return ui->tableWidget;
case 2:
return ui->tableWidget_2;
default:
return nullptr;
}
}
Dont forget setup tags (indecies) and table manager for tables (in main window constructor)
ui->tableWidget->setTag(1);
ui->tableWidget_2->setTag(2);
ui->tableWidget->setTableManager(this);
ui->tableWidget_2->setTableManager(this);
EDIT: If you want change custom pixmap for dragging just set QDrag::setPixmap
void DraggableHeaderView::mouseMoveEvent(QMouseEvent *e)
{
if (e->buttons() & Qt::LeftButton)
{
int index = logicalIndexAt(e->pos());
QDrag *drag = new QDrag(this);
QMimeData *mimeData = new QMimeData;
QString mimeTxt = "MoveHeader;Table:" + QString::number(m_tag) +
";Index:" + QString::number(index);
mimeData->setText(mimeTxt);
drag->setMimeData(mimeData);
drag->setPixmap(pixmapForDrag(index));
Qt::DropAction dropAction = drag->exec();
}
}
And method for taking pixmap of column can be like this
QPixmap DraggableHeaderView::pixmapForDrag(const int columnIndex) const
{
QTableWidget *table = qobject_cast<QTableWidget*> (this->parentWidget());
if (!table)
{
return QPixmap();
}
//image for first 5 row
int height = table->horizontalHeader()->height();
for (int iRow = 0; iRow < 5 && iRow < table->rowCount(); ++iRow)
{
height += table->rowHeight(iRow);
}
//clip maximum size
if (height > 200)
{
height = 200;
}
QRect rect(table->columnViewportPosition(columnIndex) + table->verticalHeader()->width(),
table->rowViewportPosition(0),
table->columnWidth(columnIndex),
height);
QPixmap pixmap(rect.size());
table->render(&pixmap, QPoint(), QRegion(rect));
return pixmap;
}
I have a SQLite database with three tables:
graph(ID int primary key, name varchar(64));
vertex(ID int primary key, graphID int references graph(ID), name varchar(64), x int default 0, y int default 0);
edge(ID int primary key, graphID int references graph(ID), sourceID int references vertex(ID), targetID int references vertex(ID), weight real default 1);
In my desktop app I'm using custom classes for model/view
MyTableView : public QTableView
VertexTableModel : public QSqlTableModel
EdgeTableModel : public QSqlRelationalTableModel
I'm setting them up like this:
GraphyEditor::GraphyEditor(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::GraphyEditor),
vertexModel(new VertexTableModel(parent)),
edgeModel(new EdgeTableModel(parent)) {
ui->setupUi(this);
vertexModel->setTable("vertex");
ui->vertices->setModel(vertexModel); // ui->vertices is *MyTableView
edgeModel->setTable("edge");
//TODO find fix to the issue
// edgeModel->setRelation(2, QSqlRelation("vertex", "ID", "name"));
// edgeModel->setRelation(3, QSqlRelation("vertex", "ID", "name"));
ui->edges->setModel(edgeModel); // ui->egdes is *MyTableView
}
This code works and displays the data correctly, but I would like to substitute columns 2 and 3 (sourceID and targetID) in edgeModel from vertex.ID to vertex.name
I did some searching and found the setRelation method (the same I commented out in my code), but when I use it the edgeModel table shows no edges.
Is it because of my tables schemas or is there something wrong in my code?
How do I achieve this?
EDIT:
Here are implementations of classes I'm using:
MyTableModel.h/cpp
#include <QtSql/QSqlTableModel>
class MyTableModel : public QSqlTableModel {
Q_OBJECT
public:
explicit MyTableModel(QObject *parent = nullptr);
void refresh();
[[nodiscard]] Qt::ItemFlags flags(const QModelIndex &index) const override = 0;
bool setData(const QModelIndex &index, const QVariant &value, int role) override = 0;
signals:
void databaseUpdated();
};
#endif
#include "MyTableModel.h"
#include <QDebug>
#include <utility>
#include <database/DBManager.h>
MyTableModel::MyTableModel(QObject *parent) :
QSqlTableModel(parent) {}
void MyTableModel::refresh() { select(); }
VertexTableModel.h/cpp
#include <model/MyTableModel.h>
class VertexTableModel : public MyTableModel {
Q_OBJECT
public:
explicit VertexTableModel(QObject *parent = nullptr);
[[nodiscard]] Qt::ItemFlags flags(const QModelIndex &index) const override;
bool setData(const QModelIndex &index, const QVariant &value, int role) override;
};
#endif
bool VertexTableModel::setData(const QModelIndex &index, const QVariant &value, int role) {
// checks if value is valid and updates database
}
Qt::ItemFlags VertexTableModel::flags(const QModelIndex &index) const {
auto flags = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
if (index.column() == 2) flags |= Qt::ItemIsEditable;
return flags;
}
VertexTableModel::VertexTableModel(QObject *parent) : MyTableModel(parent) {}
EdgeTableModel.h/cpp
class EdgeTableModel : public QSqlRelationalTableModel {
Q_OBJECT
public:
explicit EdgeTableModel(QObject *parent = nullptr);
void refresh();
[[nodiscard]] Qt::ItemFlags flags(const QModelIndex &index) const override;
bool setData(const QModelIndex &index, const QVariant &value, int role) override;
signals:
void databaseUpdated();
};
#endif
EdgeTableModel::EdgeTableModel(QObject *parent) : QSqlRelationalTableModel(parent) {
refresh();
}
void EdgeTableModel::refresh() { select(); }
bool EdgeTableModel::setData(const QModelIndex &index, const QVariant &value, int role) {
// checks if value is valid and updates the database
}
Qt::ItemFlags EdgeTableModel::flags(const QModelIndex &index) const {
auto flags = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
if (index.column() == 4) flags |= Qt::ItemIsEditable;
return flags;
}
GraphyEditor.h/cpp
#ifndef GRAPHY_EDITOR_H
#define GRAPHY_EDITOR_H
#include <QMainWindow>
#include <model/vertex/VertexTableModel.h>
#include <model/edge/EdgeTableModel.h>
#include <QtGui/QRegExpValidator>
#include <QtSql/QSqlRelationalDelegate>
QT_BEGIN_NAMESPACE
namespace Ui { class GraphyEditor; }
QT_END_NAMESPACE
class GraphyEditor : public QMainWindow {
Q_OBJECT
Ui::GraphyEditor *ui;
QSqlTableModel *vertexModel;
QSqlRelationalTableModel *edgeModel;
QSqlRelationalDelegate *delegate;
QString graphID = "";
public:
explicit GraphyEditor(QWidget *parent = nullptr);
void setGraphID(const QString &newGraphID);
~GraphyEditor() override;
};
#endif
#include <QtWidgets/QWidget>
#include "GraphyEditor.h"
#include <model/vertex/VertexTableModel.h>
#include <model/edge/EdgeTableModel.h>
#include <QtSql/QSqlRelationalDelegate>
GraphyEditor::GraphyEditor(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::GraphyEditor),
// vertexModel(new VertexTableModel(parent)),
vertexModel(new QSqlTableModel(parent)),
// edgeModel(new EdgeTableModel(parent)) {
edgeModel(new QSqlRelationalTableModel(parent)) {
ui->setupUi(this);
vertexModel->setTable("vertex");
vertexModel->setHeaderData(1, Qt::Horizontal, "Vertex ID");
vertexModel->setHeaderData(2, Qt::Horizontal, "Vertex Name");
ui->vertices->setModel(vertexModel);
// ui->vertices->hideColumn(0);
ui->vertices->hideColumn(1);
ui->vertices->hideColumn(3);
ui->vertices->hideColumn(4);
edgeModel->setTable("edge");
//TODO find fix to the issue
// edgeModel->setRelation(2, QSqlRelation("vertex", "ID", "name"));
// edgeModel->setRelation(3, QSqlRelation("vertex", "ID", "name as targetName"));
edgeModel->setHeaderData(2, Qt::Horizontal, "Source Vertex", Qt::DisplayRole);
edgeModel->setHeaderData(3, Qt::Horizontal, "Target Vertex", Qt::DisplayRole);
edgeModel->setHeaderData(4, Qt::Horizontal, "Weight");
delegate = new QSqlRelationalDelegate(this);
ui->edges->setModel(edgeModel);
ui->edges->setItemDelegate(delegate);
// ui->edges->setItemDelegateForColumn(2, delegate);
// ui->edges->setItemDelegateForColumn(3, delegate);
ui->edges->hideColumn(0);
ui->edges->hideColumn(1);
ui->canvas->setVertices(vertexModel);
ui->canvas->setEdges(edgeModel);
}
GraphyEditor::~GraphyEditor() {
delete ui;
delete vertexModel;
delete edgeModel;
delete delegate;
}
void GraphyEditor::setGraphID(const QString &newGraphID) {
GraphyEditor::graphID = newGraphID;
vertexModel->setFilter("graphID = " + newGraphID);
edgeModel->setFilter("graphID = " + newGraphID);
ui->canvas->setGraphID(newGraphID);
ui->canvas->refresh();
}
GraphyCanvas.h/cpp
#ifndef GRAPHY_CANVAS_H
#define GRAPHY_CANVAS_H
#include <QWidget>
#include <model/vertex/VertexTableModel.h>
#include <model/edge/EdgeTableModel.h>
class GraphyCanvas : public QWidget {
Q_OBJECT
QSqlTableModel *vertexModel = nullptr;
QSqlRelationalTableModel *edgeModel = nullptr;
QString graphID = "";
public:
void setGraphID(const QString &newGraphID);
explicit GraphyCanvas(QWidget *parent = nullptr);
void setVertices(QSqlTableModel *vertexTableModel);
void setEdges(QSqlRelationalTableModel *edgeTableModel);
public slots:
void refresh();
};
#endif
#include <QPainter>
#include <QPen>
#include <QDebug>
#include <QtWidgets/QtWidgets>
#include <cmath>
#include "GraphyCanvas.h"
GraphyCanvas::GraphyCanvas(QWidget *parent) : QWidget(parent) {
QPalette newPalette = palette();
newPalette.setColor(QPalette::Window, Qt::white);
setPalette(newPalette);
}
void GraphyCanvas::refresh() {
vertexModel->select();
edgeModel->select();
for (auto child : children()) child->deleteLater();
int edgesCount = edgeModel->rowCount();
for (int e = 0; e < edgesCount; ++e) {
//paints edge objects
}
int verticesCount = vertexModel->rowCount();
for (int v = 0; v < verticesCount; ++v) {
//paints vertex objects
}
}
void GraphyCanvas::setVertices(QSqlTableModel *vertexTableModel) {
GraphyCanvas::vertexModel = vertexTableModel;
connect(vertexModel, SIGNAL(databaseUpdated()), this, SLOT(refresh()));
}
void GraphyCanvas::setEdges(QSqlRelationalTableModel *edgeTableModel) {
GraphyCanvas::edgeModel = edgeTableModel;
connect(edgeModel, SIGNAL(databaseUpdated()), this, SLOT(refresh()));
}
void GraphyCanvas::setGraphID(const QString &newGraphID) { GraphyCanvas::graphID = newGraphID; }
main.cpp
#include "setup/GraphySetup.h"
#include <QApplication>
#include <database/DBManager.h>
int main(int argc, char *argv[]) {
QApplication application(argc, argv);
DBManager::initialize();
GraphyEditor editor;
editor.setGraphID("1");
editor.showMaximized();
return QApplication::exec();
}
DBManager is a helper class that's responsible for initializing and accessing the database
In GraphyEditor.cpp, function GraphyEditor::setGraphID, this line
edgeModel->setFilter("graphID = " + newGraphID);
should be
edgeModel->setFilter("edge.graphID = " + newGraphID);
The underlying query is a join, where the field name graphID belongs to more than one table, so the table name has to be specified along with the field name.
Your problem is probably hidden in some other place in your project that you don't provide in your question, but not in the code using QSqlRelationalTableModel.
There is only a minimal problem in your (commented) code: the two replaced columns would be having the same name: "name", but you can rename both columns while defining the QSqlRelation.
Here is a m.r.e. to illustrate how to deal with your two tables and a QSqlRelationalTableModel, just in case someone else comes to stackoverflow asking a similar question.
SQLite database dump:
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE `vertex` (
`ID` INTEGER,
`name` TEXT,
PRIMARY KEY(`ID`)
);
INSERT INTO vertex VALUES(1,'one');
INSERT INTO vertex VALUES(2,'two');
INSERT INTO vertex VALUES(3,'three');
INSERT INTO vertex VALUES(4,'four');
INSERT INTO vertex VALUES(5,'five');
INSERT INTO vertex VALUES(6,'six');
INSERT INTO vertex VALUES(7,'seven');
INSERT INTO vertex VALUES(8,'eight');
INSERT INTO vertex VALUES(9,'nine');
CREATE TABLE IF NOT EXISTS "edge" (
"ID" INTEGER,
"sourceID" INTEGER,
"targetID" INTEGER,
FOREIGN KEY("targetID") REFERENCES "vertex"("ID"),
PRIMARY KEY("ID"),
FOREIGN KEY("sourceID") REFERENCES "vertex"("ID")
);
INSERT INTO edge VALUES(1,1,4);
INSERT INTO edge VALUES(2,2,5);
INSERT INTO edge VALUES(3,3,6);
INSERT INTO edge VALUES(4,4,7);
INSERT INTO edge VALUES(5,5,8);
INSERT INTO edge VALUES(6,6,9);
COMMIT;
test.pro
QT = core sql
CONFIG += c++11 console
SOURCES += main.cpp
main.cpp
#include <QCoreApplication>
#include <QTextStream>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlRelationalTableModel>
#include <QSqlRecord>
#include <QSqlField>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QTextStream cout(stdout, QIODevice::WriteOnly);
QTextStream cerr(stderr, QIODevice::WriteOnly);
auto db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("test.db");
if (!db.open()) {
cerr << db.lastError().text() << endl;
return 1;
}
QSqlRelationalTableModel model;
model.setTable("edge");
model.setRelation(1, QSqlRelation("vertex", "ID", "name as sourceName"));
model.setRelation(2, QSqlRelation("vertex", "ID", "name as targetName"));
model.select();
auto rec = model.record();
// headers output
cout << qSetFieldWidth(15);
for(int i=0; i<rec.count(); ++i) {
cout << rec.field(i).name();
}
cout << endl;
// rows output
for(int i=0; i<model.rowCount(); ++i) {
rec = model.record(i);
cout << rec.value("ID").toInt() << rec.value("sourceName").toString() << rec.value("targetName").toString() << endl;
}
}
And this is the output of the program:
ID sourceName targetName
1 one four
2 two five
3 three six
4 four seven
5 five eight
6 six nine
Maybe modify selectStatement:
QString QSqlRelationalTableModel::selectStatement() const
......
//!!! my
fList.append(QLatin1String(", "));
fList.append(relTableAlias);
fList.append(QLatin1String("."));
fList.append(relation.indexColumn());
fList.append(QLatin1String(" as "));
fList.append(relation.tableName());
fList.append(QLatin1String("_"));
fList.append(relation.indexColumn());
Maybe you can look our open Qt project:
[github][1]
This project contains a wrapper above QSqlTableModel + QTableView and realize PblTableDlg class with basic table functionaliy.
We use a new variant of QSqlRelationalTableModel = PblSqkRelationalTableModel.
There is PblTableView (inherited by QTableView) and PblTableDlg that contains a db table view with all controls.
[1]:https://github.com/PavelDorofeev/Fork-Sql-Qt-4.8.1--SQLite-3--relations--calc-fields
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();
}
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/