Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.






(C++) QTableViewExample6


QtQt CreatorLubuntu


QTableView example 6: two views on one model is a QTableView example.


This was to demonstrate that if two tables must remain identical, the model/view architecture is an easy way to do so: because the two views work on the same model, they cannot be different.


Technical facts


Application type(s)

Operating system(s) or programming environment(s)


Project type:

C++ standard:


Libraries used:






Qt project file: ./CppQTableViewExample6/CppQTableViewExample6.pro


QT       += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
QMAKE_CXXFLAGS += -Wall -Wextra -Werror
QMAKE_CXXFLAGS += -std=c++11
    qtdialog.cpp \

HEADERS  += qtdialog.h

FORMS    += qtdialog.ui








#ifndef QTDIALOG_H
#define QTDIALOG_H

#include <QDialog>

namespace Ui {
  class QtDialog;

struct MyModel;

class QtDialog : public QDialog
  explicit QtDialog(QWidget *parent = 0);
private slots:

  Ui::QtDialog *ui;

  ///The downcasted model
  MyModel* m_model;

#endif // QTDIALOG_H








#include "qtdialog.h"

#include <cassert>
#include <iostream>
#include <stdexcept>

#include <boost/lexical_cast.hpp>
#include <boost/numeric/conversion/cast.hpp>

#include <QHeaderView>
#include <QStandardItemModel>
#include "ui_qtdialog.h"

struct MyModel : public QStandardItemModel
  MyModel(QObject *parent = 0)
    : QStandardItemModel(parent)
    const int n_rows = 3;
    const int n_cols = 4;
    for (int row = 0; row!=n_rows; ++row)
      for (int col = 0; col!=n_cols; ++col)
        QStandardItem * const item = new QStandardItem;
        const std::string s
          + boost::lexical_cast<std::string>(row)
          + std::string(",")
          + boost::lexical_cast<std::string>(row)
          + std::string(")");


QtDialog::QtDialog(QWidget *parent) :
  ui(new Ui::QtDialog),
  m_model(new MyModel(this))

  assert(ui->table_left->model() == m_model);
  assert(ui->table_right->model() == m_model);

  delete ui;








#include <QApplication>
#include "qtdialog.h"

int main(int argc, char *argv[])
  QApplication a(argc, argv);
  QtDialog w;
  return a.exec();






Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.


Valid XHTML 1.0 Strict

This page has been created by the tool CodeToHtml