天天看點

QT繪制不規則多邊形

第一種:直接在界面上繪制

在widget中對paintEvent進行重寫,然後就可以得到多邊形。

void Widget::paintEvent(QPaintEvent *event)
{
    //建立畫筆
    QPainter painter(this);

    //建立畫刷
    QBrush brush(QColor(0, 0, 255), Qt::SolidPattern);
    //使用畫刷
    painter.setBrush(brush);

    //定義四個點
    static const QPointF points[4] = {
        QPointF(270.0, 80.0),
        QPointF(290.0, 10.0),
        QPointF(350.0, 30.0),
        QPointF(390.0, 70.0)
    };
    //使用四個點繪制多邊形
    painter.drawPolygon(points, 4);
}      

第二種:利用QT圖形視圖架構繪制

QT圖形視圖架構(Graphics View)

QT繪制不規則多邊形
首先對Item進行繼承

myitem.h

#include <QGraphicsItem>

class MyItem : public QGraphicsItem
{
public:
    MyItem();
    QRectF boundingRect() const;
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option,
               QWidget *widget);

    void setColor(const QColor &color) { brushColor = color; }

private:
    QColor brushColor;

};      

myitem.cpp

#include "myitem.h"
#include <QPainter>
#include <QCursor>
#include <QKeyEvent>
#include <QGraphicsSceneHoverEvent>
#include <QGraphicsSceneContextMenuEvent>
#include <QMenu>
#include <qdebug.h>

MyItem::MyItem()
{
    brushColor = Qt::red;

    setFlag(QGraphicsItem::ItemIsFocusable);
    setFlag(QGraphicsItem::ItemIsMovable);
    setAcceptHoverEvents(true);

}
void MyItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *,
                   QWidget *)
{
    if (hasFocus()) {
        painter->setPen(QPen(QColor(255, 255, 255, 200)));
    } else {
        painter->setPen(QPen(QColor(100, 100, 100, 100)));
    }
    painter->setBrush(brushColor);
    //painter->drawRect(-10, -10, 20, 20);

    // 定義四個點
    static const QPointF points[4] = {
    QPointF(200.0, 80.0),
    QPointF(220.0, 10.0),
    QPointF(270.0, 30.0),
    QPointF(310.0, 70.0)
    };
    // 使用四個點繪制多邊形
    painter->drawPolygon(points, 4);

}

QRectF MyItem::boundingRect() const
{
    qreal adjust = 0.5;
    return QRectF(-10 - adjust, -10 - adjust,
                  20 + adjust, 20 + adjust);
}      
#include "widget.h"
#include "ui_widget.h"
#include <QGraphicsRectItem>
#include <qdebug.h>
#include "myitem.h"
#include <qpainter.h>
Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
        ui->setupUi(this);
        m_scene=new QGraphicsScene;
        MyItem *item=new MyItem;
        item->setPos(0,0);
        item->setColor(QColor(Qt::red));
    
        m_scene->addItem(item);
        ui->graphicsView->setSceneRect(-100,-100,100,100);
        ui->graphicsView->setScene(m_scene);


}

Widget::~Widget()
{
    delete m_scene;
    delete ui;
}      

運作結果: