lundi 18 mars 2019

How to sequentially send content in QLineEdit to QTableView

Sorry if this is a trivial question but I am stuck on this problem.

I have 1 QLineEdit (the path of an image, which is a text), a QPushButton (Send button) and a QTableView. When I have entered text into the QLineEdit, if I click the Send button, the text (or path) of the QLineEdit should be added in the first row of the QTableView. And so on incrementally every time I change /path/to/tableView.png1.

However, the content of the QLineEdit is not being passed to the QTableView and nothinig is being passed.

MCVE

Below the small MCVE that show my problem. You can copy and paste this small minimal and verifiable example and it will compile.

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QStandardItemModel>

namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();
    void addData();
private slots:
    void on_sendBtn_clicked();
private:
    Ui::MainWindow *ui;
    QStandardItemModel *model;
};
#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QStandardItemModel *model = new QStandardItemModel();
    model->setRowCount(5);
    ui->tableView->setModel(model);
    QObject::connect(ui->sendBtn, SIGNAL(clicked()), this, SLOT(on_sendBtn_clicked()));
}

MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::addData()
{
    QStandardItem *pathAItem = new QStandardItem(ui->lineEdit->text());
    QList<QStandardItem*> row;
    row << pathAItem;
    model->appendRow(row); // <-- ERROR HERE
}

void MainWindow::on_sendBtn_clicked()
{
    addData();
}

main.cpp

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

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

How can I do this?

Aucun commentaire:

Enregistrer un commentaire