QGraphicsItem边框样式

时间:2017-12-04 22:23:39

标签: c++ qt border qgraphicsview qgraphicsitem

如何绘制像这个图像的矩形形状和椭圆形状。在这个代码中创建矩形形状和椭圆形状,带有单个线条边框。但是我需要更改边框样式,就像给定图像一样。

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    scene = new QGraphicsScene(this);
    ui->graphicsView->setScene(scene);

    QBrush redBrush(Qt::red);
    QBrush blueBrush(Qt::blue);
    QPen blackPen(Qt::black);
    blackPen.setWidth(6);

    //rect = scene->addRect(25,25,Qt::RelativeSize);
    elipse = scene->addEllipse(20,20,100,100,blackPen,redBrush);
    elipse->setFlag(QGraphicsItem::ItemIsMovable, true);
    rect = scene->addRect(-20,-10,200,100,blackPen,blueBrush);
    rect->setFlag(QGraphicsItem::ItemIsMovable, true);
    rect->setFlag(QGraphicsItem::ItemIsSelectable,true);
}

Expected Result image

1 个答案:

答案 0 :(得分:3)

这些属性没有Qt提供的QGraphicsItem,我们必须做的是创建我们的自定义QGraphicsItem。一个选项是从标准类继承:

<强> dgraphicsitem.h

#ifndef DGRAPHICSITEM_H
#define DGRAPHICSITEM_H

#include <QGraphicsRectItem>
#include <QPainter>

class DGraphicsEllipseItem : public QGraphicsEllipseItem
{
public:
    DGraphicsEllipseItem(const QRectF &rect, qreal radius, QGraphicsItem *parent = nullptr):
        QGraphicsEllipseItem(rect, parent){
        mRadius = radius;
    }
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){
        QGraphicsEllipseItem::paint(painter, option, widget);
        painter->setBrush(brush());
        QRectF r = rect();
        r.setSize(r.size()-mRadius*QSizeF(1, 1));
        r.translate(mRadius*QPointF(1, 1)/2);
        painter->drawEllipse(r);
    }
private:
    qreal mRadius;
};

class DGraphicsRectItem : public QGraphicsRectItem
{
public:
    DGraphicsRectItem(const QRectF &rect, qreal radius, QGraphicsItem *parent = nullptr):
        QGraphicsRectItem(rect, parent){
        mRadius = radius;
    }
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){
        QGraphicsRectItem::paint(painter, option, widget);
        painter->setBrush(brush());
        QRectF r = rect();
        r.setSize(r.size()-mRadius*QSizeF(1, 1));
        r.translate(mRadius*QPointF(1, 1)/2);
        painter->drawRect(r);
    }
private:
    qreal mRadius;
};
#endif // DGRAPHICSITEM_H

然后它被添加到场景中:

scene = new QGraphicsScene(this);
ui->graphicsView->setScene(scene);

QBrush brush(Qt::white);
QPen pen(Qt::green);
pen.setWidth(1);

DGraphicsEllipseItem* ellipse = new DGraphicsEllipseItem(QRectF(20,20, 200,100), 10);
scene->addItem(ellipse);
ellipse->setPen(pen);
ellipse->setBrush(brush);
ellipse->setFlag(QGraphicsItem::ItemIsMovable, true);

DGraphicsRectItem* rect = new DGraphicsRectItem(QRectF(-20,-10,200,100), 10);
scene->addItem(rect);
rect->setPen(pen);
rect->setBrush(brush);
rect->setFlag(QGraphicsItem::ItemIsMovable, true);

输出:

enter image description here

完整示例可在以下link中找到。