当初在学MFC时,最经典的入门实例就是绘图程序,其作用相当于Console Application 下的Hello World了吧。
如今入手QT,不免怀旧,于是也写了一个绘图程序,虽然简单,却也是入门必备啊。
环境
OS : Ubuntu 11.04
IDE :Qt Creator 2.2.1
Qt : 4.7.4 (32bit)
Complier: gcc
1. 新建一个空白Qt工程
文件--> 新建工程或项目-->其它项目-->空的Qt项目
比如命名为Qt_Instance_Example
2. 添加一个C++源文件
比如命名为main.cpp
添加如下代码
#include <QApplication> #include <mypainterwidget.h> int main(int argc,char** argv) { QApplication a(argc,argv); MyPainterWidget w(0); w.show(); return a.exec(); }
这里的MyPainterWidget类是我们自己编写的QWidget类的子类,用来实现绘制的窗口部件。
下面我们添加这个类并编写其代码。
3. 添加C++类,命名为MyPainterWidget
.h 文件如下
#ifndef MYPAINTERWIDGET_H #define MYPAINTERWIDGET_H #include <QWidget> #include <QPoint> #include<vector> using namespace std; //线段 typedef struct myLine{ QPoint startPnt; QPoint endPnt; }myLine; class MyPainterWidget: public QWidget { public: MyPainterWidget(QWidget* parent); ~MyPainterWidget(); //继承 void paintEvent(QPaintEvent* p); void mousePressEvent(QMouseEvent *e); void mouseMoveEvent(QMouseEvent *e); void mouseReleaseEvent(QMouseEvent *e); QPoint startPnt; //起点 QPoint endPnt; //终点 bool isPressed; //鼠标是否按下 vector<myLine*> lines; //存放所有的线段 }; #endif // MYPAINTERWIDGET_H
.cpp 文件如下
#include "mypainterwidget.h" #include <QString> #include <QMessageBox> #include <QPainter> #include <QPen> #include <QMouseEvent> MyPainterWidget::MyPainterWidget(QWidget* parent) :QWidget(parent){ setMinimumSize(240,120); setMaximumSize(480,240); this->setMouseTracking(true); this->isPressed = false; } MyPainterWidget::~MyPainterWidget(){ } void MyPainterWidget::paintEvent(QPaintEvent*p){ QPainter painter(this); QPen pen; //创建一个画笔 pen.setColor(Qt::darkCyan); pen.setWidth(5); painter.setPen(pen); for(int i = 0;i<lines.size();i++){ myLine* pLine = lines[i]; painter.drawLine(pLine->startPnt,pLine->endPnt); } } void MyPainterWidget::mousePressEvent(QMouseEvent *e){ setCursor(Qt::PointingHandCursor); startPnt = e->pos(); endPnt = e->pos(); this->isPressed = true; //QString msg ="("+QString::number(e->x())+","+QString::number(e->y())+")"; //QMessageBox::warning(this,tr("Warning"),msg,QMessageBox::Ok); } void MyPainterWidget::mouseMoveEvent(QMouseEvent *e){ if(this->isPressed){ endPnt = e->pos(); myLine* line = new myLine; //put the new line into vector line->startPnt = startPnt; line->endPnt = endPnt; this->lines.push_back(line); update(); //repainter,call paintEvent startPnt = endPnt; } } void MyPainterWidget::mouseReleaseEvent(QMouseEvent *e){ setCursor(Qt::ArrowCursor); this->isPressed = false; }
3. 运行结果如下