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"
相关推荐
用户805533698031 天前
不止三件套:QObject 属性系统全关键字与运行时反射!
c++·qt
xcyxiner1 天前
DicomViewer (vcpkg Windows和ubuntu编译)7
qt
Quz6 天前
QML Hello World 入门示例
qt
xcyxiner9 天前
DicomViewer (dcmtk读取dcm文件)5
qt
xcyxiner10 天前
DicomViewer (后台线程处理文件)4
qt
xcyxiner10 天前
DicomViewer (添加模型类)3
qt
xcyxiner11 天前
DicomViewer (目录调整) 2
qt
xcyxiner11 天前
dcmtk vtk vtk-dicom(gdcm) 编译(debug) v2
qt
LDR00613 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
雪碧聊技术13 天前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript