QStandardItemModel TableView


Create new Qt project. Drop a table view onto the designer surface. Set layout to vertical layout. Declare model in dialog.h and put the prototype for the init member function. Declare slot called itemChanged in dialog.h




class Dialog : public QDialog
{
    Q_OBJECT

public:
    Dialog(QWidget *parent = nullptr);
    ~Dialog();

private slots:
    void itemChanged(QStandardItem *item);

private:
    Ui::Dialog *ui;
    QStandardItemModel model;
    void init();
};

In dialog.cpp, implement init as follows: Set a table 4x4, fill it with QstandardItems whose text contains the coordinates. Connect the model's itemchanged (which happens when user changes the item in the UI) to the itemChanged slot.



void Dialog::init()
{
    model.insertRows(0,4);
    model.insertColumns(0,4);

    for(int r = 0; r < model.rowCount(); r++)
    {
        for(int c = 0; c < model.columnCount(); c++)
        {
            QStandardItem* item = new QStandardItem(QString("row %0 col %1").arg(r).arg(c));
            model.setItem(r,c,item);
        }
    }
    ui->tableView->setModel(&model);
    connect(&model, &QStandardItemModel::itemChanged,this,&Dialog::itemChanged);

}

The itemChanged slot is as follows:

void Dialog::itemChanged(QStandardItem *item)
{
    qInfo() << "Index: "<<item->index().row()<<item->index().column()<< " = "<<item->text();

}

The output is as follows:


Comments

Popular posts from this blog

QTreeView and QTableView dynamic changes

C++ strings and string_view

C++ Tour Part III