Creating a simple table cell in Qt

I want to create a simple table cell in Qt. So I wrote the following code

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QTableView>
#include <QSqlQueryModel>

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);

     QTableView *view = new QTableView;
     QStringListModel *model;
     view->setModel(model);
     view->show();
     model->setHeaderData(0, Qt::Horizontal, QObject::tr("ID"));
     model->setHeaderData(1, Qt::Horizontal, QObject::tr("Name"));
     model->setHeaderData(2, Qt::Horizontal, QObject::tr("City"));
     model->setHeaderData(3, Qt::Horizontal, QObject::tr("Country"));
}

MainWindow::~MainWindow()
{
    delete ui;
}

      

main.cpp

#include <QtGui/QApplication>
#include "mainwindow.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

      

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
    class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

      

But in the mainwindow.cpp file, I get the error "Model is not declared in this scope. Its inability to include the QSqlQueryModel header in the included part of mainwindow.cpp."

Can anyone point me to where I am doing wrong?

Thanks and Regards, Sid

+3


source to share


1 answer


I think you want a multidimensional table, but the QStringListModel is one dimensional, so you can try this code. I think it works the way you want, you get headers and you can set data in the model in the future

     QTableView *view = new QTableView;
      QStandardItemModel *mod = new QStandardItemModel;
      QStandardItem *it = new QStandardItem(QObject::tr("ID"));
      mod->setHorizontalHeaderItem(0,it);
      QStandardItem *it1 = new QStandardItem(QObject::tr("Name"));
      mod->setHorizontalHeaderItem(1,it1);
  QStandardItem *it2 = new QStandardItem(QObject::tr("City"));
  mod->setHorizontalHeaderItem(2,it2);
  QStandardItem *it3 = new QStandardItem(QObject::tr("Country"));
  mod->setHorizontalHeaderItem(3,it3);
//and so on
      view->setModel(mod);
      view->show();

      



About future. If you write QStandardItemModel * mod and after that write mod-> setHorizontalHeaderItem (), your program will crash because you are using a bad pointer. You must allocate memory before using

+3


source







All Articles