views:

2800

answers:

4

I have a class that inherits by QTreeWidget, how can I know the actually selected row? I explain, usually we connect signals to slots by this way:

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

I can't find nothing to similar for QTreeWidget->QTreeWidgetItem. The only way I found is this: redefining the mousePressEvent of 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. Can anybody tell me if this is the unique solution or if there is a simplest way? Thanks

A: 

According to the documentation here it appears that you should connect the QTreeWidget itemSelectionChanged() signal to a slot in your class. That will tell you which QTreeWidgetItem was selected which is what I believe you want.

Dusty Campbell
+3  A: 

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).

Thomas Watnedal
Yes, you are correct. It even says so in the documentation that I linked to. Nice catch.
Dusty Campbell
A: 

ooops, I've solved simply using this:

connect(this,SIGNAL(itemClicked(QTreeWidgetItem*, int)), SLOT(mySlot()));

however thanks for replies :D

Giancarlo
A: 

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

Parker
it's perfect, I only need to click on the QTreeWidget :)
Giancarlo