noo*_*guo 3 c++ qt qtableview qt5
用手机写,所以格式可能不好。
我有一个表QTableView
,表中有两列。第二列包含一个很长的字符串,如果不调整大小就无法完全显示。当鼠标悬停在一个项目上时,我想在一个矩形中显示字符串,并且该矩形靠近鼠标(Eclipse和VS等许多软件都有这样的功能)。
我在互联网上搜索了一段时间,但仍然不知道如何编程此视图功能。
该死。每个人都必须尝试以艰难的方式去做,并开始对不需要的东西进行子类化和重新发明。答案已经在在 PyQT 中为 QTreeView 项目显示工具提示
答案是,在你模型的 data() 函数中,当调用 'Qt::ToolTipRole;' 时只返回一些有用的东西。在首先检查“index.column()”以确保它是正确的列之后。
这里有一些类似的愚蠢:
我会给他们一个怀疑的好处,并假设 Qt 曾经以这种方式工作;但现在没有。他们有人制作这个自定义事件过滤器;而我为我的模型中的给定列返回了 ToolTipRole 的工具提示,而工具提示仅显示为返回值的列中的单元格。这只是不必要的工作;现在不需要了;而且很浪费时间。这个维基条目很有可能,只是过时了。
首先要实现弹窗你需要知道鼠标什么时候进入表格中某个项目的区域,为此我们将使用eventFilter()
方法并查找何时使用QEvent::MouseMove
事件,我们将通过函数indexAt()
和位置获取索引的鼠标,并比较这是否与之前的索引不同。如果发生这种情况,它将根据需要显示或隐藏弹出窗口。
为了创建弹出窗口,我们使用一个对话框并插入一个 QLabel,并使用 setWordWrap 属性来正确地适应文本
#ifndef TABLEVIEW_H
#define TABLEVIEW_H
#include <QDialog>
#include <QEvent>
#include <QLabel>
#include <QMouseEvent>
#include <QTableView>
#include <QVBoxLayout>
#include <QHeaderView>
class TableView: public QTableView{
Q_OBJECT
QDialog *popup;
QLabel *popupLabel;
public:
TableView(QWidget *parent = Q_NULLPTR):QTableView(parent){
viewport()->installEventFilter(this);
setMouseTracking(true);
popup = new QDialog(this, Qt::Popup | Qt::ToolTip);
QVBoxLayout *layout = new QVBoxLayout;
popupLabel = new QLabel(popup);
popupLabel->setWordWrap(true);
layout->addWidget(popupLabel);
popupLabel->setTextFormat(Qt::RichText);
//popupLabel->setOpenExternalLinks(true);
popup->setLayout(layout);
popup->installEventFilter(this);
}
bool eventFilter(QObject *watched, QEvent *event){
if(viewport() == watched){
if(event->type() == QEvent::MouseMove){
QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
QModelIndex index = indexAt(mouseEvent->pos());
if(index.isValid()){
showPopup(index);
}
else{
popup->hide();
}
}
else if(event->type() == QEvent::Leave){
popup->hide();
}
}
else if(popup == watched){
if(event->type() == QEvent::Leave){
popup->hide();
}
}
return QTableView::eventFilter(watched, event);
}
private:
void showPopup (const QModelIndex &index) const {
if(index.column() == 1){
QRect r = visualRect(index);
popup->move(viewport()->mapToGlobal(r.bottomLeft()));
popup->setFixedSize(100, popup->heightForWidth(100));
popupLabel->setText(index.data(Qt::DisplayRole).toString());
popup->adjustSize();
popup->show();
}
else {
popup->hide();
}
}
};
#endif // TABLEVIEW_H
Run Code Online (Sandbox Code Playgroud)
截屏:
在以下链接中,您将找到一个示例。
归档时间: |
|
查看次数: |
3509 次 |
最近记录: |