首页 > 代码库 > 利用QT中Qpainter画点,直线,弧线等简单图形

利用QT中Qpainter画点,直线,弧线等简单图形

  1. MyImgTest.h:
  2. #ifndef MYIMGTEST_H
  3. #define MYIMGTEST_H
  4. #include <QWidget>
  5. class MyImgTest : public QWidget
  6. {
  7. //Q_OBJECT
  8. public:
  9. MyImgTest(QWidget* parent = 0);
  10. ~MyImgTest();
  11. void paintEvent(QPaintEvent *);
  12. };
  13. #endif




  1. MyImgTest.cpp:
  2. #include "MyImgTest.h"
  3. #include <QPainter>
  4. //#include <QRect>
  5. //#include <QPointF>
  6. //#include <QLineF>
  7. MyImgTest::MyImgTest(QWidget* parent) : QWidget(parent)
  8. {
  9. setFixedSize(360,360); //固定大小
  10. setWindowTitle("Hello DevDiv!");
  11. }
  12. MyImgTest::~MyImgTest()
  13. {
  14. }
  15. void MyImgTest::paintEvent(QPaintEvent *)
  16. {
  17. // 画一条直线
  18. QPainter painter(this); // 创建QPainter一个对象
  19. QPen pen;
  20. //pen.setStyle(Qt::DashLine);
  21. pen.setColor(Qt::red); // 设置画笔为黄色
  22. painter.setPen(pen); // 设置画笔
  23. painter.drawLine(rect().topLeft(), rect().bottomRight());
  24. // 画一个空心矩形
  25. pen.setColor(Qt::darkRed);
  26. painter.setPen(pen);
  27. painter.drawRect(1, 1, 100, 100); //painter.drawRect(QRect(1, 1, 100, 100));
  28. // 画一个实心矩形
  29. QBrush bruch(Qt::FDiagPattern); // 画刷
  30. painter.setBrush(bruch); // 设置画刷
  31. painter.drawRect(QRect(105, 1, 100, 100));
  32. // 画一个多点线
  33. pen.setColor(Qt::black);
  34. painter.setPen(pen);
  35. bruch.setStyle(Qt::NoBrush); // 将画刷设置成null//fow what
  36. painter.setBrush(bruch);
  37. static const QPointF points[4] = {QPointF(210.0, 1), QPointF(220.0, 50.3), QPointF(300, 100.4), QPointF(260.4, 120.0)};
  38. painter.drawPolyline(points, 4);
  39. // 画多个点
  40. QPointF pointf[10];
  41. for (int i=0; i<10; ++i)
  42. {
  43. pointf[i].setX(2.0+i*10.0);
  44. pointf[i].setY(130.0);
  45. }
  46. painter.drawPoints(pointf, 10);
  47. // 画多条线
  48. QLineF linef[5];
  49. for (int j=0; j<5; ++j)
  50. {
  51. linef[j].setP1(QPointF(110.9+j*10, 120.0));
  52. linef[j].setP2(QPointF(120.8+j*12, 200.0));
  53. }
  54. painter.drawLines(linef, 5);
  55. // 画一个多边形
  56. QPolygonF polygon;
  57. polygon << QPointF(200.0, 120.0) << QPointF(230.0, 130.0) << QPointF(260.0, 180.0) << QPointF(200.0, 200.0);
  58. bruch.setStyle(Qt::CrossPattern);
  59. painter.setBrush(bruch);
  60. painter.drawPolygon(polygon, Qt::WindingFill);
  61. // 画一个圆角矩形
  62. QRectF rectangle(290.0, 110.0, 50, 50);
  63. bruch.setStyle(Qt::SolidPattern);
  64. painter.setBrush(bruch);
  65. painter.drawRoundedRect(rectangle, 20.0, 15.0);
  66. // 画一个QString
  67. painter.drawText(50, 300, "Hello DevDiv!");
  68. }


  1. main.cpp
  2. #include <QApplication>
  3. #include "MyImgTest.h"
  4. int main(int argc,char *argv[])
  5. {
  6. QApplication app(argc,argv);
  7. MyImgTest* widget = new MyImgTest();
  8. widget->show();
  9. return app.exec();
  10. }
  11. 操作步骤:
  12. 1.qmake-qt4 -project
  13. 2.qmake-qt4
  14. 3.make



来自为知笔记(Wiz)