[SOLVED] Model/View QTable displays nothing - just a white field :(
-
Hey Guys,
I have some problems with the Model/View Architecture from QT. I want to display some data into a QTableView from my own Model.
generalmodel.h
@namespace Ui {
class MainWindow;
}class GeneralModel: public QAbstractTableModel
{
Q_OBJECT
public:
GeneralModel(QWidget *parent);
int rowCount(const QModelIndex &parent = QModelIndex()) const;
int columnCount(const QModelIndex &parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;void test();
private:
Ui::MainWindow *mainWindow;
};
@generalmodel.cpp
@GeneralModel::GeneralModel(QWidget *parent)
:QAbstractTableModel(parent){
}
int GeneralModel::rowCount(const QModelIndex & /parent/) const
{
return 2;
}int GeneralModel::columnCount(const QModelIndex & /parent/) const
{
return 3;
}QVariant GeneralModel::data(const QModelIndex &index, int role) const
{
if (role == Qt::DisplayRole)
{
return QString("Row%1, Column%2")
.arg(index.row() + 1)
.arg(index.column() +1);
}
return QVariant();
}void GeneralModel::test()
{
qDebug() << "DATAMODEL!";
}@I declare the model and table in a mainwindow class in the constructor.
mainwindow.h
@
class GeneralModel;namespace Ui {
class MainWindow;
}class MainWindow : public QMainWindow
{
Q_OBJECTpublic:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();private slots:
void on_generalSafeButton_clicked();void on_action_ffnen_triggered();
private:
Ui::MainWindow *ui;
Api *api;
QTableView *qTable;
GeneralModel *gModel;};@
mainwindow.cpp
@MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
api(new Api)
{ui->setupUi(this); GeneralModel gm(0); static QTableView *qTable = new QTableView(); qTable->setModel(&gm); qTable->show();
}@
Well, when I compile my program I only get an empty table. But I don't understand why. The funny thing is, when I paste the exactly same code in my main class it works. Like this.
main class
@int main(int argc, char *argv[])
{QApplication a(argc, argv); GeneralModel gm(0); QTableView *qTable = new QTableView(); qTable->setModel(&gm); qTable->show(); MainWindow w; w.show(); return a.exec();
}@
Please help me. I am looking for hours to fix this problem.
-
Hi and welcome to devnet,
In mainwindow.cpp, as soon as your constructor ends gm goes out of scope and is destroyed hence you don't see anything because the model is gone even before the table view is shown.
-
Okay and how could my gm Model lives out of scope?
-
Create it on the heap.
Also be aware that with your current code you are likely to get into trouble.
You should take a look at Qt's documentation model/view examples before going further.
-
Yeah thank you :). It's working now. The current code was only an example to show you my problem earlier.