|
- #include "light.h"
- #include <QPainter>
- #include <QStyleOptionGraphicsItem>
- #include <QMenu>
- #include <QFileDialog>
-
- Light::Light(const QString &type) : Item(type)
- {
-
- }
-
- QRectF Light::boundingRect() const
- {
- return QRectF(0, 0, 50, 50);
- }
-
- void Light::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *)
- {
- painter->setRenderHint(QPainter::Antialiasing);
-
- if (type_ == "指示灯") {
- if (state() && !onPixmap_.isNull()) {
- painter->drawPixmap(0, 0, 50, 50, onPixmap_);
- } else if (!state() && !offPixmap_.isNull()) {
- painter->drawPixmap(0, 0, 50, 50, offPixmap_);
- } else {
- if (state()) {
- painter->setBrush(Qt::green); // 激活状态
- } else {
- painter->setBrush(Qt::white); // 未激活状态
- }
- painter->drawEllipse(0,0,50,50);
- }
- }
- if (!registerId_.isEmpty()) {
- painter->save();
- painter->setFont(QFont("Arial", 8));
- painter->setPen(Qt::black);
- QString text = QString("%1").arg(registerId());
- painter->drawText(QRectF(13, 13, 26, 26), Qt::AlignCenter, text);
- painter->restore();
- }
- if (option->state & QStyle::State_Selected) {
- QPen pen(Qt::DashLine);
- pen.setColor(Qt::blue);
- pen.setWidth(2);
- painter->setPen(pen);
- painter->setBrush(Qt::NoBrush);
- painter->drawRect(boundingRect());
- }
- }
-
- bool Light::state() const
- {
- return registerValue_ > 0;
- }
-
- void Light::addMenuActions(QMenu *menu)
- {
- menu->addAction("ON外观设置");
- menu->addAction("OFF外观设置");
- }
-
- void Light::handleMenuAction(QAction *action)
- {
- if (action->text() == "复制") {
- emit requestCopy(this);
- }
- if (action->text() == "删除") {
- emit requestDelete(this);
- }
- if (action->text() == "对象"){
- emit requestBindRegister(this);
- }
- if (action->text() == "重置"){
- emit requestReset(this);
- }
- if (action->text() == "ON外观设置"){
- QString fileName = QFileDialog::getOpenFileName(nullptr,
- "选择图片",
- "",
- "图片文件(*.png *.jpg *.bmp)");
- if (!fileName.isEmpty())
- {
- setOnImage(fileName);
- }
- }
- if (action->text() == "OFF外观设置"){
- QString fileName = QFileDialog::getOpenFileName(nullptr,
- "选择图片",
- "",
- "图片文件(*.png *.jpg *.bmp)");
- if (!fileName.isEmpty())
- {
- setOffImage(fileName);
- }
- }
- }
-
- void Light::setOnImage(const QString& imagePath)
- {
- onImagePath_ = imagePath;
- loadImage();
- update();
- }
-
- void Light::setOffImage(const QString &imagePath)
- {
- offImagePath_ = imagePath;
- loadImage();
- update();
- }
-
- void Light::loadImage()
- {
- if (!onImagePath_.isEmpty()) {
- onPixmap_ = QPixmap(onImagePath_);
- if (!onPixmap_.isNull()) {
- onPixmap_ = onPixmap_.scaled(50, 50, Qt::KeepAspectRatio, Qt::SmoothTransformation);
- }
- }
- if (!offImagePath_.isEmpty()) {
- offPixmap_ = QPixmap(offImagePath_);
- if (!offPixmap_.isNull()) {
- offPixmap_ = offPixmap_.scaled(50, 50, Qt::KeepAspectRatio, Qt::SmoothTransformation);
- }
- }
- }
|