## 一、前言
在很多项目应用中,需要根据数据动态生成对象显示在地图上,比如地图标注,同时还需要可拖动对象到指定位置显示,能有多种状态指示,安防领域一般用来表示防区或者设备,可以直接显示防区号,有多种状态颜色指示,例如布防、撤防、旁路、报警、离线、在线等状态,可以作为一个通用的设备按钮对象使用。
**主要功能:**
1. 可设置防区样式 圆形、警察、气泡、气泡2、消息、消息2
2. 可设置防区状态 布防、撤防、报警、旁路、故障
3. 可设置报警切换
4. 可设置显示的防区号
5. 可设置是否可鼠标拖动
## 二、代码思路
void ButtonDefence::paintEvent(QPaintEvent *) { double width = this->width(); double height = this->height(); QPainter painter(this); (QPainter::Antialiasing); //绘制背景图 QImage img(imgName); if (!img.isNull()) { img = img.scaled(width, height, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); (0, 0, img); } //计算字体 QFont font; (height * 0.37); (true); //自动计算文字绘制区域,绘制防区号 QrectF rect = this->rect(); if (buttonStyle == ButtonStyle_Police) { double y = (30 * height / 60); rect = QRectF(0, y, width, height - y); } else if (buttonStyle == ButtonStyle_Bubble) { double y = (8 * height / 60); rect = QRectF(0, 0, width, height - y); } else if (buttonStyle == ButtonStyle_Bubble2) { double y = (13 * height / 60); rect = QRectF(0, 0, width, height - y); (width * 0.33); } else if (buttonStyle == ButtonStyle_Msg) { double y = (17 * height / 60); rect = QRectF(0, 0, width, height - y); } else if (buttonStyle == ButtonStyle_Msg2) { double y = (17 * height / 60); rect = QRectF(0, 0, width, height - y); } //绘制文字标识 (font); (Qt::white); (rect, Qt::AlignCenter, text); } bool ButtonDefence::eventFilter(QObject *watched, QEvent *event) { if (canMove) { static QPoint lastPoint; static bool isPressed = false; if (event->type() == QEvent::MouseButtonPress) { QMouseEvent *e = static_cast<QMouseEvent *>(event); if (this->rect().contains(e->pos()) && (e->button() == Qt::LeftButton)) { lastPoint = e->pos(); isPressed = true; } } else if (event->type() == QEvent::MouseMove && isPressed) { QMouseEvent *e = static_cast<QMouseEvent *>(event); int dx = e->pos().x() - la(); int dy = e->pos().y() - la(); this->move(this->x() + dx, this->y() + dy); return true; } else if (event->type() == QEvent::MouseButtonRelease && isPressed) { isPressed = false; } } if (event->type() == QEvent::MouseButtonPress) { emit clicked(); } else if (event->type() == QEvent::MouseButtonDblClick) { emit doubleClicked(); } return QWidget::eventFilter(watched, event); }
## 三、效果图
## 四、开源主页
**以上作品完整源码下载都在开源主页,会持续不断更新作品数量和质量,欢迎各位关注。**
1. 国内站点:[]()
2. 国际站点:[]()
3. 个人主页:[]()
4. 知乎主页:[]()