QGraphicsItem 边框样式
Posted
技术标签:
【中文标题】QGraphicsItem 边框样式【英文标题】:QGraphicsItem Border Styles 【发布时间】:2017-12-04 22:23:38 【问题描述】:我怎样才能画出像这张图片一样的矩形和椭圆形。在这段代码中,它创建了带有单线边框的矩形和椭圆形。但是我需要像这个给定的图片那样改变边框样式。
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);
【问题讨论】:
【参考方案1】:这些属性没有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);
输出:
完整的例子可以在下面的link找到。
【讨论】:
先生你能给我一个解决这个问题的方法吗***.com/questions/47728237/…以上是关于QGraphicsItem 边框样式的主要内容,如果未能解决你的问题,请参考以下文章