7

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?

Jason Plank
  • 2,336
  • 5
  • 31
  • 40
JuanDeLosMuertos
  • 4,532
  • 15
  • 55
  • 87

5 Answers5

17

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
  • 4,903
  • 4
  • 24
  • 23
4

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 Coates
  • 8,520
  • 3
  • 31
  • 37
3

you can simply use this :

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

to get your text in the variable word.

Andy
  • 49,085
  • 60
  • 166
  • 233
Sofiane
  • 473
  • 1
  • 6
  • 13
1

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,146
  • 31
  • 34
0

ooops, I've solved simply using this:

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

however thanks for replies :D

JuanDeLosMuertos
  • 4,532
  • 15
  • 55
  • 87