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、看效果

鼠标箭头处显示坐标

相关推荐
雨季6664 分钟前
Flutter 三端应用实战:OpenHarmony “极简手势轨迹球”——指尖与屏幕的诗意对话
开发语言·javascript·flutter
m0_736919108 分钟前
编译器命令选项优化
开发语言·c++·算法
Stream_Silver10 分钟前
【Agent学习笔记1:Python调用Function Calling,阿里云API函数调用与DeepSeek API对比分析】
开发语言·python·阿里云
froginwe1111 分钟前
CSS3 多媒体查询实例
开发语言
naruto_lnq16 分钟前
C++中的工厂方法模式
开发语言·c++·算法
独自破碎E16 分钟前
LCR_019_验证回文串II
java·开发语言
一切尽在,你来17 分钟前
C++多线程教程-1.2.3 C++并发编程的平台无关性
开发语言·c++
坚持就完事了19 分钟前
Java中的一些关键字
java·开发语言
雨季66629 分钟前
Flutter 三端应用实战:OpenHarmony “专注时光盒”——在碎片洪流中守护心流的数字容器
开发语言·前端·安全·flutter·交互
新缸中之脑36 分钟前
Moltbook 帖子精选
开发语言·php