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

鼠标箭头处显示坐标

相关推荐
Tttian6224 分钟前
Python办公自动化(2)对word&pdf的操作
开发语言·python
美美打不死15 分钟前
webpack js 逆向 --- 个人记录
开发语言·javascript·webpack
等雨季15 分钟前
scala编程语言
开发语言·scala
不断前进的皮卡丘41 分钟前
06-公寓租赁项目-后台管理-公寓管理篇
java·开发语言·数据库·spring boot
努力学习的小廉1 小时前
【C++11(下)】—— 我与C++的不解之缘(三十二)
开发语言·c++
唐静蕴1 小时前
Kotlin语言的安全开发
开发语言·后端·golang
LabVIEW开发1 小时前
LabVIEW 调用 Python 函数
开发语言·python·labview
老哥不老1 小时前
从零掌握 Playwright:用 Python 玩转现代浏览器自动化
开发语言·python·自动化
yngsqq1 小时前
批量改CAD图层颜色——CAD c#二次开发
开发语言·数据库·c#
Hello.Reader1 小时前
迭代器介绍与使用(四十一)
开发语言·c++