In a QTreewidget, how could I retrieve selected items...?
-
@MSDQuick
Hi
The treeWidget->selectionModel()->selectedIndexes() returns a list.
http://doc.qt.io/qt-5/qitemselectionmodel.html#selectedIndexesQModelIndexList selection = yourTableView->selectionModel()->selectedRows(); // Multiple rows can be selected for(int i=0; i< selection.count(); i++) { QModelIndex index = selection.at(i); qDebug() << index.row(); }
You can then use a for loop to process the selected.
To use the signal, you need a slot function that matches the signal
void QItemSelectionModel::selectionChanged(const QItemSelection &selected, const QItemSelection &deselected)So you need a function like
void xxxxx::TreeSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected) {
}
And connect signal to slot
connect(selectionModel, SIGNAL(selectionChanged(const QItemSelection&,const QItemSelection&)), this, SLOT(TreeSelectionChanged(const QItemSelection&,const QItemSelection&))); -
@mrjj
You mean I have to put this in my mainwindow.h file :public slots: void TreeSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected);
and this in mainwindow.cpp :
void MainWindow::TreeSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected) { QModelIndexList selection = ui->myTreeView->selectionModel()->selectedRows(); for(int i=0; i< selection.count(); i++) { QModelIndex index = selection.at(i); qDebug() << index.row(); } }
Right?
-
@MSDQuick
Hi , you are mixing a little.
The TreeSelectionChanged is fired each time you select one
so processing the list there might not be what you want.Depending on your design. Do you press a button after you have selected some?
You can use the
QModelIndexList selection = ui->myTreeView->selectionModel()->selectedRows(); for(int i=0; i< selection.count(); i++) {
without using the signal. Like in a button when pressing ok. etc.
-
@MSDQuick
Not at all.
In constructor of mainwindow, connect the signal and slot
connect(treeWidget->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&,const QItemSelection&)), this, SLOT(TreeSelectionChanged(const QItemSelection&,const QItemSelection&)));Then the treeWidget call your slot.
You should read over this
http://doc.qt.io/qt-5/signalsandslots.html