I have 3 QLineEdit
s (say Name, Address & Phone No.), 2 QPushButton
(Add & Modify) and a QTableView
.
When I enter text in all the QLineEdit
s, and if I click the Add button, all 3 texts of the QLineEdit
s should be added in the 1st row of the QTableView
.
Again if I enter 3 text's in the QLineEdit
and the Add Button is Clicked, the Text's should be placed in the 2nd row of the QTableView
. Like this it should go on. I did this all and it works fine.
Now if I select any row from the QTableView
and once I click the Modify Button the selected Row has to be removed from the QTableView
and the Items should be again placed in their respective QLineEdit
s.
How can I do this ?
Example.h
#ifndef EXAMPLE_H
#define EXAMPLE_H
#include <QWidget>
#include <QStandardItemModel>
namespace Ui {
class Example;
}
class Example : public QWidget
{
Q_OBJECT
public:
explicit Example (QWidget *parent = 0);
~Example();
private slots:
void on_addButton_released();
void on_modifyButton_released();
private:
Ui::Example*ui;
QStandardItemModel *model;
};
#endif // EXAMPLE_H
EXAMPLE.CPP
#include "Example.h"
Example::Example(QWidget *parent) :
QWidget(parent),
ui(new Ui::Example)
{
ui->setupUi(this);
model = new QStandardItemModel();
ui->tableView->setModel(model);
}
Example::~Example()
{
delete ui;
}
void Example::on_addButton_released()
{
model->setHorizontalHeaderItem(0, new QStandardItem(QString(" NAME ")));
model->setHorizontalHeaderItem(1, new QStandardItem(QString(" ADDRESS ")));
model->setHorizontalHeaderItem(2, new QStandardItem(QString(" PHONE NO ")));
QStandardItem *nameItem = new QStandardItem(ui->nameLineEdit->text());
QStandardItem *addressItem = new QStandardItem(ui->addressLineEdit->text());
QStandardItem *phoneItem = new QStandardItem(ui->phoneLineEdit->text());
QList<QStandardItem*> row;
row << nameItem << addressItem << phoneItem;
model->appendRow(row);
ui->nameLineEdit->clear();
ui->addressLineEdit->clear();
ui->mobileLineEdit->clear();
ui->emailLineEdit->clear();
}
void Example::on_modifyButton_released()
{
}
What you want to do is when the Modify button is clicked, access the selection from the QItemSelectionModel
of your QTableView
. Once you have the selection, if any, process it.
For example:
void Example::on_modifyButton_released()
{
if( ui->myTableView )
{
QModelIndex currentIndex = ui->myTableView->selectionModel();
// Make sure to check the index is valid, as the user
// may not have selected a row.
if( currentRow.isValid() )
{
// Add your code here to copy the data to
// your QLineEdit and remove the row from your
// QStandardModel.
...
}
}
}
For reference:
QTableView
http://qt-project.org/doc/qt-4.8/QTableView.html
QItemSelectionModel
http://qt-project.org/doc/qt-4.8/QItemSelectionModel.html