I am new to Qt5 and trying to create a QTableView widget using QtCreator. As for as I understand QTableView can be connected to a model via a setModel method and Model must be an instance QtAbstractTableModel
#ifndef FILELIST_H
#define FILELIST_H
#include <QAbstractTableModel>
namespace Ui {
class FileList;
}
class FileList : public QAbstractTableModel
{
Q_OBJECT
public:
FileList(QObject *parent=nullptr);
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
};
#endif // FILELIST_H
Here is the Implementation FileList.cpp
#include <QFont>
#include <QBrush>
#include <QDebug>
#include "FileList.h"
FileList::FileList(QObject *parent) : QAbstractTableModel(parent)
{
qDebug() << QString("Constructor...");
}
int FileList::rowCount(const QModelIndex &parent) const
{
return 2;
}
int FileList::columnCount(const QModelIndex &parent) const
{
return 3;
}
QVariant FileList::data(const QModelIndex &index, int role) const
{
int row = index.row();
int col = index.column();
// generate a log message when this method gets called
qDebug() << QString("row %1, col%2, role %3")
.arg(row).arg(col).arg(role);
switch (role) {
case Qt::DisplayRole:
if (row == 0 && col == 1) return QString("<--left");
if (row == 1 && col == 1) return QString("right-->");
return QString("Row%1, Column%2")
.arg(row + 1)
.arg(col +1);
case Qt::FontRole:
if (row == 0 && col == 0) { //change font only for cell(0,0)
QFont boldFont;
boldFont.setBold(true);
return boldFont;
}
break;
case Qt::BackgroundRole:
if (row == 1 && col == 2) //change background only for cell(1,2)
return QBrush(Qt::red);
break;
case Qt::TextAlignmentRole:
if (row == 1 && col == 1) //change text alignment only for cell(1,1)
return Qt::AlignRight + Qt::AlignVCenter;
break;
case Qt::CheckStateRole:
if (row == 1 && col == 0) //add a checkbox to cell(1,0)
return Qt::Checked;
break;
}
return QVariant();
}
Now when I attach the QTableView widget to my main window the data does not show up in the table view and I get a blank empty TableView
CloudSync.cpp
#include <QDebug>
#include "CloudSync.h"
#include "ui_cloudsync.h"
#include "FileList.h"
CloudSync::CloudSync(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::CloudSync)
{
ui->setupUi(this);
FileList fileList;
qDebug() << QString("row %1, col%2, role %3");
ui->listView->setModel(&fileList);
//ui->listView->show();
setCentralWidget(ui->listView);
}
CloudSync::~CloudSync()
{
delete ui;
}
and main.cpp
#include "CloudSync.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
CloudSync w;
w.show();
return a.exec();
}
Now what I am doing wrong here? The qDebug inside the ::data method does not output anything into the console which makes me the thing that the model is not properly connected
Final Output