Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find the selected item in a QTreeWidget?

I have a class that inherits QTreeWidget. How can I find the currently selected row? Usually I connect signals to slots this way:

connect(myButton, SIGNAL(triggered(bool)), this, SLOT(myClick()));

However, I can't find anything similar for QTreeWidget->QTreeWidgetItem. The only way I found is to redefine the mousePressEvent of the QTreeWidget class like this:

void MyQTreeWidget::mousePressEvent(QMouseEvent *e){
    QTreeView::mousePressEvent(e);
    const QModelIndex index = indexAt(e->pos());
    if (!index.isValid())
    {
    const Qt::KeyboardModifiers modifiers = QApplication::keyboardModifiers();
    if (!(modifiers & Qt::ShiftModifier) && !(modifiers & Qt::ControlModifier))
    clearSelection();
    }
 }

I didn't try it yet. Is the only solution or is there any easier way?

like image 637
Giancarlo Avatar asked Dec 02 '08 18:12

Giancarlo


3 Answers

Dusty is almost correct. But the itemSelectionChanged signal will not tell you which item is selected.

QList<QTreeWidgetItem *> QTreeWidget::selectedItems() const

will give you the selected item(s).

So, connect a slot to the itemSelectionChanged signal, then call selectedItems() on the tree widget to get the selected item(s).

like image 60
Thomas Watnedal Avatar answered Sep 20 '22 18:09

Thomas Watnedal


Using the itemClicked() signal will miss any selection changes made using the keyboard. I'm assuming that's a bad thing in your case.

like image 38
Parker Coates Avatar answered Sep 22 '22 18:09

Parker Coates


you can simply use this :

QString word = treeWidget->currentItem()->text(treeWidget->currentColumn());

to get your text in the variable word.

like image 42
Sofiane Avatar answered Sep 20 '22 18:09

Sofiane