updating rows in QStandardItemModel
-
Using the documentation provided here and some research, I was able to implement a program which updates
listView
whenever user sends some text from text box.Below given function works well but I only have one small problem of updating row as user clicks.
listView
overwrites the previous entry as the user sends new text from text box by clicking button. It has something to do with row value getting incremented dynamically.void MainWindow::on_pushButton_clicked() { QStandardItemModel* model = new QStandardItemModel(this); QStandardItem* rowlist = new QStandardItem(QString(ui->textEdit->toPlainText())); int row=0; // what should be value here model -> setItem(row++, 0, rowlist); //how to update new row dynamically on every new button press ui->listView->setModel(model); }
I want values of
listView
printed on individual row as user presses button. In above code I believe I am missing just very small logic.Thank you.
-
Hi,
Why are you creating a new model each time ? Just update the existing one.
-
To update the existing model I tried keeping these two declarations outside the function:
QStandardItemModel* model = new QStandardItemModel(this); QStandardItem* rowlist = new QStandardItem(QString(ui->textEdit->toPlainText()));
but it shows error as
model
not declared in scope. Can you tell me where I can put them? so that they can be available through out all the functions.this is my mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include "QStandardItemModel" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked() { QStandardItemModel* model = new QStandardItemModel(this); QStandardItem* rowlist = new QStandardItem(QString(ui->textEdit->toPlainText())); //model->appendRow(rowlist); int row=0; model -> setItem(row++, 0, rowlist); ui->listView->setModel(model); }
Thank you.
-
hi
You must put
QStandardItemModel* model;
in mainwindow.hclass MainWindow : public QMainWindow
{
Q_OBJECT
QStandardItemModel* model;
...that way its available to all member functions of mainwindow.
BUT this is just the declaration, you still need to new it.
This you can do in mainwindow constructor
MainWindow::MainWindow(QWidget* parent) { ...
ui->setupUi(this);
model = new QStandardItemModel(this);
}the
QStandardItem* rowlist = new QStandardItem(QString(ui->textEdit->toPlainText()));
You can still keep in the
MainWindow::on_pushButton_clicked()
Also if you add new rows, you might be able to use ( if its a list)
http://doc.qt.io/qt-5/qstandarditemmodel.html#appendRow-1
That way you dont need to keep a row counter.
Else setItem is fine. -