C++ 如何在 QTreeWidget 中找到所选项目?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/334952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:44:27  来源:igfitidea点击:

How can I find the selected item in a QTreeWidget?

c++qteventskdetreewidget

提问by Giancarlo

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

我有一个继承 QTreeWidget 的类。如何找到当前选定的行?通常我以这种方式将信号连接到插槽:

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:

但是,我找不到任何类似的QTreeWidget->QTreeWidgetItem. 我发现的唯一方法是像这样重新定义 QTreeWidget 类的 mousePressEvent:

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?

我还没试过。是唯一的解决方案还是有更简单的方法?

采纳答案by Parker Coates

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

使用 itemClicked() 信号将错过使用键盘所做的任何选择更改。我假设这对你来说是件坏事。

回答by Thomas Watnedal

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

Dusty 几乎是正确的。但是 itemSelectionChanged 信号不会告诉您选择了哪个项目。

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

因此,将插槽连接到 itemSelectionChanged 信号,然后在树小部件上调用 selectedItems() 以获取所选项目。

回答by Sofiane

you can simply use this :

你可以简单地使用这个:

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

to get your text in the variable word.

将您的文本放入变量 word 中。

回答by Dusty Campbell

According to the documentation hereit appears that you should connect the QTreeWidgetitemSelectionChanged()signal to a slot in your class. That will tell you which QTreeWidgetItemwas selected which is what I believe you want.

根据此处的文档,您似乎应该将QTreeWidget itemSelectionChanged()信号连接到类中的插槽。这将告诉您选择了哪个QTreeWidgetItem,这是我相信您想要的。

回答by Giancarlo

ooops, I've solved simply using this:

哎呀,我已经解决了简单地使用这个:

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

however thanks for replies :D

不过感谢您的回复:D