|
## 一、前言
在很多项目应用中,需要根据数据动态生成对象显示在地图上,比如地图标注,同时还需要可拖动对象到指定位置显示,能有多种状态指示,安防领域一般用来表示防区或者设备,可以直接显示防区号,有多种状态颜色指示,例如布防、撤防、旁路、报警、离线、在线等状态,可以作为一个通用的设备按钮对象使用。
**主要功能:**
1. 可设置防区样式 圆形、JC、气泡、气泡2、消息、消息2
2. 可设置防区状态 布防、撤防、报警、旁路、故障
3. 可设置报警切换
4. 可设置显示的防区号
5. 可设置是否可鼠标拖动
## 二、代码思路
```c++
void ButtonDefence::paintEvent(QPaintEvent *)
{
double width = this->width();
double height = this->height();
QPainter painter(this);
painter.setRenderHint(QPainter::Antialiasing);
//绘制背景图
QImage img(imgName);
if (!img.isNull()) {
img = img.scaled(width, height, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
painter.drawImage(0, 0, img);
}
//计算字体
QFont font;
font.setPixelSize(height * 0.37);
font.setBold(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);
font.setPixelSize(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);
}
//绘制文字标识
painter.setFont(font);
painter.setPen(Qt::white);
painter.drawText(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:eftButton)) {
lastPoint = e->pos();
isPressed = true;
}
} else if (event->type() == QEvent::MouseMove && isPressed) {
QMouseEvent *e = static_cast<QMouseEvent *>(event);
int dx = e->pos().x() - lastPoint.x();
int dy = e->pos().y() - lastPoint.y();
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. 国内站点:[https://gitee.com/feiyangqingyun/QWidgetDemo](https://gitee.com/feiyangqingyun/QWidgetDemo)
2. 国际站点:[https://github.com/feiyangqingyun/QWidgetDemo](https://github.com/feiyangqingyun/QWidgetDemo)
3. 个人主页:[https://blog.csdn.net/feiyangqingyun](https://blog.csdn.net/feiyangqingyun)
4. 知乎主页:[https://www.zhihu.com/people/feiyangqingyun/](https://www.zhihu.com/people/feiyangqingyun/)
|
|