欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 培训 > Qt实现海康OSD拖动Demo

Qt实现海康OSD拖动Demo

2025/2/24 6:07:48 来源:https://blog.csdn.net/Lemon_D1999/article/details/145000172  浏览:    关键词:Qt实现海康OSD拖动Demo

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

  1. 使用 QLabel 显示文本。
  2. QLabel 启用鼠标事件,通过重写其 mousePressEvent, mouseMoveEventmouseReleaseEvent 实现拖动功能。
  3. QLabel 设置为窗口的子控件,限制它的移动范围在窗口内。
#include <QApplication>
#include <QWidget>
#include <QLabel>
#include <QMouseEvent>class DraggableLabel : public QLabel {Q_OBJECTpublic: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"

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词