利用QT中Qpainter畫點,直線,弧線等簡單圖形
轉自:
http://blog.sina.com.cn/s/blog_67cf08270100wv59.html
MyImgTest.h:
#ifndef MYIMGTEST_H
#define MYIMGTEST_H
#include <QWidget>
class MyImgTest : public QWidget
{
//Q_OBJECT
public:
MyImgTest(QWidget* parent = 0);
~MyImgTest();
void paintEvent(QPaintEvent *);
};
#endif
MyImgTest.cpp:
#include "MyImgTest.h"
#include <QPainter>
//#include <QRect>
//#include <QPointF>
//#include <QLineF>
MyImgTest::MyImgTest(QWidget* parent) : QWidget(parent)
{
setFixedSize(360,360); //固定大小
setWindowTitle("Hello DevDiv!");
}
MyImgTest::~MyImgTest()
{
}
void MyImgTest::paintEvent(QPaintEvent *)
{
// 畫一條直線
QPainter painter(this); // 建立QPainter一個物件
QPen pen;
//pen.setStyle(Qt::DashLine);
pen.setColor(Qt::red); // 設定畫筆為黃色
painter.setPen(pen); // 設定畫筆
painter.drawLine(rect().topLeft(), rect().bottomRight());
// 畫一個空心矩形
pen.setColor(Qt::darkRed);
painter.setPen(pen);
painter.drawRect(1, 1, 100, 100); //painter.drawRect(QRect(1, 1, 100, 100));
// 畫一個實心矩形
QBrush bruch(Qt::FDiagPattern); // 畫刷
painter.setBrush(bruch); // 設定畫刷
painter.drawRect(QRect(105, 1, 100, 100));
// 畫一個多點線
pen.setColor(Qt::black);
painter.setPen(pen);
bruch.setStyle(Qt::NoBrush); // 將畫刷設定成null//fow what
painter.setBrush(bruch);
static const QPointF points[4] = {QPointF(210.0, 1), QPointF(220.0, 50.3), QPointF(300, 100.4), QPointF(260.4, 120.0)};
painter.drawPolyline(points, 4);
// 畫多個點
QPointF pointf[10];
for (int i=0; i<10; ++i)
{
pointf[i].setX(2.0+i*10.0);
pointf[i].setY(130.0);
}
painter.drawPoints(pointf, 10);
// 畫多條線
QLineF linef[5];
for (int j=0; j<5; ++j)
{
linef[j].setP1(QPointF(110.9+j*10, 120.0));
linef[j].setP2(QPointF(120.8+j*12, 200.0));
}
painter.drawLines(linef, 5);
// 畫一個多邊形
QPolygonF polygon;
polygon << QPointF(200.0, 120.0) << QPointF(230.0, 130.0) << QPointF(260.0, 180.0) << QPointF(200.0, 200.0);
bruch.setStyle(Qt::CrossPattern);
painter.setBrush(bruch);
painter.drawPolygon(polygon, Qt::WindingFill);
// 畫一個圓角矩形
QRectF rectangle(290.0, 110.0, 50, 50);
bruch.setStyle(Qt::SolidPattern);
painter.setBrush(bruch);
painter.drawRoundedRect(rectangle, 20.0, 15.0);
// 畫一個QString
painter.drawText(50, 300, "Hello DevDiv!");
}
main.cpp:
#include <QApplication>
#include "MyImgTest.h"
int main(int argc,char *argv[])
{
QApplication app(argc,argv);
MyImgTest* widget = new MyImgTest();
widget->show();
return app.exec();
}
操作步驟:
1.qmake-qt4 -project
2.qmake-qt4
3.make