send Qtable widget selected items to list widget upon button click
-
In my qt c++ application I have a Qtablewidget which contains 5 items( numbers from 1 to 5), a push button(named transfer) and a list widget.
following is my code
MainWindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private slots: void on_Transfer_clicked(); 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(5); ui->tableWidget->setColumnCount(1); for(int i=0;i<5;i++){ ui->tableWidget->setItem(i, 0, new QTableWidgetItem((QString::number(i)))); } } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_Transfer_clicked() { }
when I select an item from tablewidget and click the button I want to add it to the list widget! How can I do this?
-
@Kushan You can use http://doc.qt.io/qt-5/qtablewidget.html#selectedItems to get selected items from the table and then use http://doc.qt.io/qt-5/qlistwidget.html#insertItem-1 to add to the list widget...
-
@jsulm Thanx !
I did
void MainWindow::on_Transfer_clicked()
{
ui->listWidget->addItem(ui->tableWidget->selectedItems());}
and I get the following error!
'QListWidget::addItem(QList<QTableWidgetItem*>)'
ui->listWidget->addItem(ui->tableWidget->selectedItems());
^ -
@Kushan Why do you need examples? Call selectedItems and check whether the list it returns is empty - if it is empty you don't have anything to do. If it is not empty then iterate over the list and call http://doc.qt.io/qt-5/qtablewidgetitem.html#text on each element and put the result in a QString list then simply call insertItem and pass this list (untested):
void MainWindow::on_Transfer_clicked() { QList<QTableWidgetItem *> selectedItems = ui->tableWidget->selectedItems(); if (selectedItems.isEmpty()) return; QStringList itemsToAdd; for (auto item : selectedItems) itemsToAdd.append(item->text()); ui->listWidget->addItem(0, itemsToAdd); }
-
@jsulm Thanx but your one is erronous! I got it corrrected
void MainWindow::on_Transfer_clicked()
{
QList<QTableWidgetItem *> selectedItems = ui->tableWidget->selectedItems();
if (selectedItems.isEmpty()){
return;
}for (int i=0;i<selectedItems.size();i++){ ui->listWidget->addItem(selectedItems[i]->text());
}
} -
For future reference, this approach only works if you know in advance all the roles you will use.
You can use KSelectionProxyModel instead if you need a proper general implementation