gpt4 book ai didi

c++ - QGraphicsItem 边框样式

转载 作者:行者123 更新时间:2023-11-30 02:22:10 24 4
gpt4 key购买 nike

我怎样才能像这张图片一样绘制矩形和椭圆形。在这段代码中,它创建了带有单线边框的矩形和椭圆形。但是我需要像这张给定的图片那样更改边框样式。

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

最佳答案

这些属性没有 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中找到.

关于c++ - QGraphicsItem 边框样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47642978/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com