Qt实现海康OSD拖动Demo

在 Qt 中可以通过组合 QLabel 和鼠标事件来实现这个需求。以下是一个简单的实现步骤:

  1. 使用 QLabel 显示文本。
  2. QLabel 启用鼠标事件,通过重写其 mousePressEvent, mouseMoveEventmouseReleaseEvent 实现拖动功能。
  3. QLabel 设置为窗口的子控件,限制它的移动范围在窗口内。
cpp 复制代码
#include <QApplication>
#include <QWidget>
#include <QLabel>
#include <QMouseEvent>

class DraggableLabel : public QLabel {
    Q_OBJECT

public:
    explicit DraggableLabel(QWidget *parent = nullptr) : QLabel(parent), m_isDragging(false) {
        setText("拖动我!");
        setStyleSheet("background-color: lightblue; padding: 5px; border: 1px solid black;");
        setAlignment(Qt::AlignCenter);
        setFixedSize(100, 50);
    }

protected:
    void mousePressEvent(QMouseEvent *event) override {
        if (event->button() == Qt::LeftButton) {
            m_isDragging = true;
            m_dragStartPosition = event->pos();
        }
    }

    void mouseMoveEvent(QMouseEvent *event) override {
        if (m_isDragging) {
            QPoint newPos = mapToParent(event->pos() - m_dragStartPosition);
            QRect parentRect = parentWidget()->rect();

            // 限制 QLabel 不超出父窗口范围
            newPos.setX(qMax(parentRect.left(), qMin(newPos.x(), parentRect.right() - width())));
            newPos.setY(qMax(parentRect.top(), qMin(newPos.y(), parentRect.bottom() - height())));

            move(newPos);
        }
    }

    void mouseReleaseEvent(QMouseEvent *event) override {
        if (event->button() == Qt::LeftButton) {
            m_isDragging = false;
        }
    }

private:
    bool m_isDragging;
    QPoint m_dragStartPosition;
};

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    QWidget window;
    window.setWindowTitle("可拖动文本");
    window.resize(400, 300);

    DraggableLabel *label = new DraggableLabel(&window);
    label->move(150, 125); // 初始位置

    window.show();
    return app.exec();
}

#include "main.moc"
相关推荐
真的想上岸啊12 分钟前
学习C++、QT---18(C++ 记事本项目的stylesheet)
开发语言·c++·学习
明天好,会的18 分钟前
跨平台ZeroMQ:在Rust中使用zmq库的完整指南
开发语言·后端·rust
丁劲犇1 小时前
用 Turbo Vision 2 为 Qt 6 控制台应用创建 TUI 字符 MainFrame
开发语言·c++·qt·tui·字符界面·curse
旷世奇才李先生1 小时前
Next.js 安装使用教程
开发语言·javascript·ecmascript
charlie1145141912 小时前
深入理解Qt的SetWindowsFlags函数
开发语言·c++·qt·原理分析
likeGhee2 小时前
python缓存装饰器实现方案
开发语言·python·缓存
whoarethenext3 小时前
使用 C++/Faiss 加速海量 MFCC 特征的相似性搜索
开发语言·c++·faiss
项目題供诗3 小时前
黑马python(二十五)
开发语言·python
慌糖3 小时前
RabbitMQ:消息队列的轻量级王者
开发语言·javascript·ecmascript
醇醛酸醚酮酯3 小时前
Qt项目锻炼——TODO清单(二)
开发语言·数据库·qt