|
- #include "item.h"
- #include "connection.h"
- #include <QPainter>
- #include <QStyleOptionGraphicsItem>
-
- Item::Item(const QString &type, QGraphicsItem *parent)
- : QGraphicsObject(parent), type_(type)
- {
- if (type == "常开") color_ = Qt::blue;
- else if (type == "常闭") color_ = Qt::red;
- else if (type == "比较指令") color_ = Qt::green;
- else color_ = Qt::darkYellow;
-
- setFlags(QGraphicsItem::ItemIsMovable |
- QGraphicsItem::ItemIsSelectable |
- QGraphicsItem::ItemSendsGeometryChanges);
- }
-
- QRectF Item::boundingRect() const
- {
- return QRectF(-5, -5, 90, 50);
- }
-
- void Item::paint(QPainter *painter,
- const QStyleOptionGraphicsItem *,
- QWidget *)
- {
- QRectF r = boundingRect().adjusted(5, 5, -5, -5); // 图元主体
- painter->setBrush(color_.lighter(150));
- painter->setPen(QPen(color_, 2));
- painter->drawRoundedRect(r, 5, 5);
-
- // 画锚点
- painter->setBrush(Qt::darkGray);
- painter->setPen(Qt::NoPen);
- painter->drawEllipse(QPointF(r.left(), r.center().y()), 5, 5); // 左锚点
- painter->drawEllipse(QPointF(r.right(), r.center().y()), 5, 5); // 右锚点
-
- painter->setPen(Qt::black);
- painter->drawText(r, Qt::AlignCenter, type_);
- }
-
- QPointF Item::anchorPos(AnchorType anc) const
- {
- QRectF r = boundingRect();
- switch (anc) {
- case Left: return mapToScene(QPointF(r.left(), r.center().y()));
- case Right: return mapToScene(QPointF(r.right(), r.center().y()));
- }
- return QPointF();
- }
-
- void Item::addConnection(Connection* conn)
- {
- if (!connections_.contains(conn))
- connections_.append(conn);
- }
-
- void Item::removeConnection(Connection* conn)
- {
- connections_.removeAll(conn);
- }
-
- QList<Connection *> Item::connections()
- {
- return connections_;
- }
-
- QVariant Item::itemChange(GraphicsItemChange change, const QVariant &value)
- {
- if (change == QGraphicsItem::ItemPositionChange) {
- for (Connection* conn : connections_)
- conn->updatePosition();
- }
- return QGraphicsObject::itemChange(change, value);
- }
|