QT传输函数控件设计8 设计小圆点
首先看一下小圆点:
如图,左图上有很多小圆点,这些小圆点是由蓝色的中心和红边构成。点击小圆点的时候,小圆点的红边会消失,松开鼠标红边又会出现。
我们首先要把这些小圆点能够显示在QGraphicsView上面,还记得之前讲过的图形项嘛?每个小圆点就是一个图形项。现在我们就开始设计图形项类。因为这是圆的,所以我们就继承一个QGraphicsEllipse椭圆类。
#ifndef __NodeGraphicsItem_H__
#define __NodeGraphicsItem_H__
#include <QGraphicsEllipseItem>
#include <QPainter>
class NodeGraphicsItem : public QGraphicsEllipseItem {
public:
NodeGraphicsItem& operator = (const NodeGraphicsItem& Other) {
brushColor = Other.brushColor;
pen = Other.pen;
return *this;
}
NodeGraphicsItem(const NodeGraphicsItem& Other)
{
*this = Other;
};
public:
NodeGraphicsItem(QGraphicsEllipseItem * parent = Q_NULLPTR);
~NodeGraphicsItem();
private:
QBrush brushColor;
QPen pen;
private:
void mousePressEvent(QGraphicsSceneMouseEvent *event);
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);
void hoverEnterEvent(QGraphicsSceneHoverEvent *event);
void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget = 0);
QVariant itemChange(GraphicsItemChange change, const QVariant &value) override;
};
#endif
我们先把之前学的那些函数都搞进去,然后把这些函数体填充一下:
NodeGraphicsItem::NodeGraphicsItem(QGraphicsEllipseItem * parent) : QGraphicsEllipseItem(parent),
brushColor(QColor(0, 190, 27))
{
setZValue(1000000);
pen.setWidth(2);
pen.setColor(Qt::red);
setPen(pen);
setBrush(brushColor);
setRect(-5,-5,10,10);
setFlags(QGraphicsItem::ItemIsFocusable | QGraphicsItem::ItemIsSelectable
| QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemSendsGeometryChanges);
setAcceptHoverEvents(true);
}
NodeGraphicsItem::~NodeGraphicsItem() {
}
注意在这个函数里面,我们把Z值设置非常大,因为它一定要在所有东西的最上面。然后设置笔和刷子。然后设置椭圆的边界:setRect,因为这个椭圆是相当于设置的方形的内切圆。然后设置它可以移动可以选择可以设置焦点可以设置边界可以悬停等一大堆属性。
// 鼠标按下事件处理函数,设置被点击的图形项获得焦点,并改变光标外观
void NodeGraphicsItem::mousePressEvent(QGraphicsSceneMouseEvent * pEvent)
{
QGraphicsItem::mousePressEvent(pEvent);
setFocus();
}
void NodeGraphicsItem::mouseReleaseEvent(QGraphicsSceneMouseEvent * pEvent)
{
QGraphicsItem::mouseReleaseEvent(pEvent);
clearFocus();
}
在事件处理中,有鼠标事件以后就设置或者清除焦点。
void NodeGraphicsItem::paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget)
{
if (hasFocus()) {
painter->setPen(QPen(QColor(255, 255, 0)));
}
else {
painter->setPen(pen);
}
painter->setBrush(QColor(0, 190, 27));
painter->drawEllipse(-5,-5,10,10);
}
设置重绘,当有焦点的时候说明你鼠标点在了这上面,所以就设置一个特殊的被选中的颜色。如果没有焦点就画回原来的样子。
QVariant NodeGraphicsItem::itemChange(GraphicsItemChange change, const QVariant &value)
{
if (change == ItemPositionChange && scene())
{
QPointF newPos = value.toPointF();
QRectF rect(0,0,100,100 );//先随便设置一下
if (!rect.contains(newPos))
{
newPos.setX(qMin(rect.right(), qMax(newPos.x(), rect.left())));
newPos.setY(qMin(rect.bottom(), qMax(newPos.y(), rect.top())));
return newPos;
}
}
return QGraphicsItem::itemChange(change, value);
}
这个函数因为边界什么的都没有,这里先随便设置一下,以后再回来重新设置。
现在已经有了一个初步的NodeGraphicsItem小圆点,下一步我们就设置一个QGraphicsView类来安置这些小圆点。