Reindexing items in Tablewidgets
-
In my Qt c++ application I have 2 Qtablewidgets one which has a set of UserIds and the other table whcih has the respective user names! I should be able to change the ids and when the button is clicked the names should rearrange based on the ids I changed.
following is my codeMainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>
namespace Ui {
class MainWindow;
}class MainWindow : public QMainWindow
{
Q_OBJECTpublic:
QStringList Headers1;
QStringList Headers2;QStringList List1; QStringList List2; explicit MainWindow(QWidget *parent = 0); ~MainWindow();
private slots:
void on_pushButtonclicked();private:
Ui::MainWindow *ui;
};#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);ui->tableWidget->setRowCount(10); ui->tableWidget->setColumnCount(1); ui->tableWidget_2->setRowCount(10); ui->tableWidget_2->setColumnCount(1); ui->tableWidget->setColumnWidth(0,100); ui->tableWidget_2->setColumnWidth(0,150); Headers1<<"UserId"; Headers2<<"UserNames"; ui->tableWidget->setHorizontalHeaderLabels(Headers1); ui->tableWidget_2->setHorizontalHeaderLabels(Headers2);
}
MainWindow::~MainWindow()
{
delete ui;
}void MainWindow::on_pushButtonclicked()
{
List1<<"0"<<"1"<<"2"<<"3"<<"4"<<"5"<<"6"<<"7"<<"8"<<"9";
List2<<"John"<<"Smith"<<"Mary"<<"Anne"<<"Kamal"<<"Victor"<<"Peter"<<"Sunil"<<"Juanna"<<"Jennifer";for(int i=0;i<List1.size();i++){ ui->tableWidget->setItem(i,0,new QTableWidgetItem(List1[i])); } for(int i=0;i<List2.size();i++){ ui->tableWidget_2->setItem(i,0,new QTableWidgetItem(List2[i])); }
}
As it can be seen from the code username John corresponds to userID 0 and smith corresponds to userID 1 and so on.I want to change the order of userIDs by editing Qtablewidget.(currently userIDs are displayed from 0 to 9). and when a button is clicked(not defined in my code) I want to rearrange the usernames based on how the userIDs were edited.
i.e if I put number 7 to position of 1 and put number 1 to position of 7 and the button is clicked the 2nd tablewidget should show Sunil as the 2nd element (previous position of Smith) and Smith in the 8th position(previous position of Sunil)
How can I achieve this?
-
Hi,
You should rather consider using a custom QAbstractItemModel which wraps your custom data. That would avoid such syncing mechanism.
-
Sure you can, loop through the content of the left QTableWidget and update the content of the right table to match. But again, you seem to overcomplicate things.