用手机书写,因此格式可能不正确。

我有一个带有QTableView的表,该表中有两列。第二列包含一个非常长的字符串,如果不调整大小,则无法完全显示该字符串。当我将鼠标悬停在一个项目上时,我想在矩形中显示字符串,而该矩形在鼠标附近(许多软件(例如Eclipse和VS都具有这种功能))。

我已经在互联网上搜索了一段时间,但仍然不知道如何对该 View 功能进行编程。

c++ - QTableView在鼠标悬停时显示表项的内容-LMLPHP
c++ - QTableView在鼠标悬停时显示表项的内容-LMLPHP

最佳答案

首先要实现弹出窗口,您需要知道何时鼠标进入表中某个项目的区域,为此,我们将使用eventFilter()方法,并在使用QEvent::MouseMove事件时进行查找,并通过indexAt()函数获取索引和鼠标的位置,并比较是否与先前的索引不同。如果发生这种情况,它将根据需要显示或隐藏弹出窗口。

要创建PopUp,我们使用对话框并插入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

屏幕截图:

c&#43;&#43; - QTableView在鼠标悬停时显示表项的内容-LMLPHP

在以下链接中,您将找到example

09-10 01:31
查看更多