Qt QTreeView鼠标悬停显示信息
时间: 2023-07-10 20:04:37 浏览: 230
在Qt中,可以通过使用QTreeView的setMouseTracking()方法来开启鼠标跟踪功能,然后在重载QTreeView的mouseMoveEvent()方法中实现鼠标悬停显示信息的功能。
以下是一个简单的示例代码:
```cpp
class MyTreeView : public QTreeView
{
public:
MyTreeView(QWidget *parent = nullptr) : QTreeView(parent)
{
setMouseTracking(true); // 开启鼠标跟踪功能
}
protected:
void mouseMoveEvent(QMouseEvent *event) override
{
QModelIndex index = indexAt(event->pos());
if (index.isValid())
{
QString data = "Some information about " + index.data(Qt::DisplayRole).toString(); // 获取鼠标所在行的数据
QToolTip::showText(mapToGlobal(event->pos()), data, this); // 显示信息
}
QTreeView::mouseMoveEvent(event);
}
};
```
在上述代码中,我们继承了QTreeView类,并在构造函数中开启了鼠标跟踪功能。然后,我们重载了mouseMoveEvent()方法,在方法中获取鼠标所在行的数据,并使用QToolTip::showText()方法显示信息。最后,我们调用了QTreeView::mouseMoveEvent()方法,以确保QTreeView的默认操作也会执行。
请注意,QToolTip::showText()方法可以在任何QWidget的子类中使用,以显示鼠标悬停时的信息。
相关推荐
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)