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

鼠标箭头处显示坐标

相关推荐
游离状态的猫11 小时前
JavaScript性能优化实战:从瓶颈定位到极致提速
开发语言·javascript·性能优化
GeekABC1 小时前
FastAPI系列06:FastAPI响应(Response)
开发语言·python·fastapi·web
小彭努力中1 小时前
7.Three.js 中 CubeCamera详解与实战示例
开发语言·前端·javascript·vue.js·ecmascript
why1512 小时前
腾讯(QQ浏览器)后端开发
开发语言·后端·golang
charade3122 小时前
【C语言】内存分配的理解
c语言·开发语言·c++
LinDaiuuj2 小时前
判断符号??,?. ,! ,!! ,|| ,&&,?: 意思以及举例
开发语言·前端·javascript
小臭希2 小时前
Java——琐碎知识点一
java·开发语言
淋一遍下雨天3 小时前
Spark Streaming核心编程总结(四)
java·开发语言·数据库
小白学大数据3 小时前
如何避免爬虫因Cookie过期导致登录失效
开发语言·爬虫·python·scrapy
爱吃烤鸡翅的酸菜鱼4 小时前
【SpringMVC】概念引入与连接
java·开发语言·mysql