qt中怎么在鼠标停留的位置上显示该点的坐标位置

需要重写控件的mouseMoveEvent方法。
1、自定义一个QLabel控件,然后重写QLabel的mouseMoveEvent
cpp 复制代码
customlabel.h


#include <QWidget>
#include <QHBoxLayout>
#include <QLabel>

class CustomLabel : public QLabel
{
    Q_OBJECT
public:
    explicit CustomLabel(QWidget *parent = nullptr);
    void setPiture(QString path);
    void paintLine(QPoint startPoint, QPoint endPoint);

protected:
    void mouseMoveEvent(QMouseEvent* event) override;
signals:

private:
    QHBoxLayout* m_layout;
    QList<QPoint> m_pointList;
};
cpp 复制代码
customlabel.cpp


#include "customlabel.h"
#include <QMouseEvent>
#include <QToolTip>

CustomLabel::CustomLabel(QWidget *parent)
    : QLabel{parent}
{
    setMouseTracking(true);
    show();
}

void CustomLabel::mouseMoveEvent(QMouseEvent *event)
{
    QPoint pos = event->pos();
    QString positionString = QString("X: %1, Y: %2").arg(pos.x()).arg(pos.y());
    // 设置工具提示文本
    QToolTip::showText(event->globalPos(), positionString, this);
    QColor color(Qt::red);
    QPalette palette;
    palette.setColor(QPalette::Text,color);
    QToolTip::setPalette(palette);
}
2、在主界面widget中使用CustomLabel。
cpp 复制代码
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    CustomLabel* label = new CustomLabel(this);
    ui->verticalLayout_2->addWidget(label);
}
3、看效果

鼠标箭头处显示坐标

相关推荐
再见晴天*_*2 小时前
SpringBoot 中单独一个类中运行main方法报错:找不到或无法加载主类
java·开发语言·intellij idea
lqjun08273 小时前
Qt程序单独运行报错问题
开发语言·qt
hdsoft_huge5 小时前
Java & Spring Boot常见异常全解析:原因、危害、处理与防范
java·开发语言·spring boot
风中的微尘5 小时前
39.网络流入门
开发语言·网络·c++·算法
未来之窗软件服务6 小时前
幽冥大陆(二)RDIFSDK 接口文档:布草洗涤厂高效运营的技术桥梁C#—东方仙盟
开发语言·c#·rdif·仙盟创梦ide·东方仙盟
小冯记录编程6 小时前
C++指针陷阱:高效背后的致命危险
开发语言·c++·visual studio
1uther6 小时前
Unity核心概念⑨:Screen
开发语言·游戏·unity·c#·游戏引擎
C_Liu_7 小时前
C++:类和对象(下)
开发语言·c++
coderxiaohan7 小时前
【C++】类和对象1
java·开发语言·c++
阿幸软件杂货间7 小时前
Office转PDF转换器v1.0.py
开发语言·pdf·c#