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

鼠标箭头处显示坐标

相关推荐
笨笨马甲5 分钟前
Qt Quick模块功能及架构
开发语言·qt
夜晚回家19 分钟前
「Java基本语法」代码格式与注释规范
java·开发语言
YYDS31424 分钟前
C++动态规划-01背包
开发语言·c++·动态规划
前端页面仔33 分钟前
易语言是什么?易语言能做什么?
开发语言·安全
树叶@1 小时前
Python数据分析7
开发语言·python
wydaicls1 小时前
十一.C++ 类 -- 面向对象思想
开发语言·c++
Biomamba生信基地1 小时前
R语言基础| 下载、安装
开发语言·r语言·生信·医药
姜君竹1 小时前
QT的工程文件.pro文件
开发语言·c++·qt·系统架构
奇树谦2 小时前
使用VTK还是OpenGL集成到qt程序里哪个好?
开发语言·qt
VBA63372 小时前
VBA之Word应用第三章第十节:文档Document对象的方法(三)
开发语言