程序运行截图如下:
原理:使用QPainter一个部分,一个部分的画
源码:
mygraphicsitem.h
1 ifndef MYGRAPHICSITEM_H
2 #define MYGRAPHICSITEM_H
3
4 #include <QGraphicsItem>
5
6 class MyGraphicsItem:public QGraphicsItem
7 {
8 public:
9 MyGraphicsItem(QGraphicsItem *parent=0);
10 ~MyGraphicsItem();
11
12 protected:
13 QRectF boundingRect()const;
14 void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
15 };
16
17 #endif // MYGRAPHICSITEM_H
widget.h
1 #ifndef WIDGET_H
2 #define WIDGET_H
3
4 #include <QWidget>
5 class QGraphicsScene;
6
7 namespace Ui {
8 class Widget;
9 }
10
11 class Widget : public QWidget
12 {
13 Q_OBJECT
14
15 public:
16 explicit Widget(QWidget *parent = 0);
17 ~Widget();
18
19 private:
20 Ui::Widget *ui;
21 QGraphicsScene *m_scene;
22 };
23
24 #endif // WIDGET_H
main.cpp
1 #include "widget.h"
2 #include <QApplication>
3
4 int main(int argc, char *argv[])
5 {
6 QApplication a(argc, argv);
7 Widget w;
8 w.show();
9
10 return a.exec();
11 }
mygraphicsitem.cpp
1 #include "mygraphicsitem.h"
2 #include <QPainter>
3 #include <QPen>
4 #include <QRectF>
5
6 MyGraphicsItem::MyGraphicsItem(QGraphicsItem *parent):
7 QGraphicsItem(parent)
8 {
9 setFlags(QGraphicsItem::ItemIsSelectable|QGraphicsItem::ItemIsMovable);
10 }
11
12 MyGraphicsItem::~MyGraphicsItem()
13 {
14
15 }
16
17 QRectF MyGraphicsItem::boundingRect() const
18 {
19 return QRectF(-14,-50,55,70);
20 }
21
22 void MyGraphicsItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
23 {
24 Q_UNUSED(option)
25 Q_UNUSED(widget)
26 painter->setPen(QPen(Qt::white,1));
27 painter->drawRect(-14,-50,55,70);
28 painter->setPen(QPen(Qt::red,2));
29 painter->drawLine(0,0,0,10);
30 painter->drawLine(0,10,30,10);
31 painter->drawLine(30,10,30,0);
32 painter->drawLine(15,10,15,-20);
33 painter->drawLine(15,-20,0,-20);
34 QRectF rectangle(0,-33,30,30);
35 int startAngle=-180*16;
36 int spanAngle=270*16;
37 painter->drawArc(rectangle, startAngle, spanAngle);
38 painter->drawLine(15,-35,15,-40);
39 }
widget.cpp
1 #include "widget.h"
2 #include "ui_widget.h"
3 #include "mygraphicsitem.h"
4 #include <QGraphicsScene>
5
6 Widget::Widget(QWidget *parent) :
7 QWidget(parent),
8 ui(new Ui::Widget)
9 {
10 ui->setupUi(this);
11 m_scene=new QGraphicsScene;
12 ui->graphicsView->setScene(m_scene);
13 ui->graphicsView->setRenderHint(QPainter::Antialiasing);
14 m_scene->setBackgroundBrush(QBrush(Qt::black));
15 MyGraphicsItem *item=new MyGraphicsItem;
16 item->setPos(0,0);
17 m_scene->addItem(item);
18 }
19
20 Widget::~Widget()
21 {
22 delete ui;
23 }