一、新建一個Qt Gui應用,項目名稱爲myPalette,基類選擇爲QMainWindow,類名設置爲MainWindow。函數
二、在mainwindow.h頭文件中添加如下代碼,同時添加#include<QPushButton>ui
1 private: 2 Ui::MainWindow *ui; 3 QPixmap pix; 4 QPoint lastPoint; 5 QPoint endPoint; 6 qreal scale; 7 QPushButton *zoomInButton, *zoomOutButton; 8 9 protected: 10 void paintEvent(QPaintEvent *); 11 void mousePressEvent(QMouseEvent *); 12 void mouseMoveEvent(QMouseEvent *); 13 void mouseReleaseEvent(QMouseEvent *); 14 15 public slots: 16 void zoomIn(); 17 void zoomOut();
三、在mainwindow.cpp文件中添加#include<QPainter>,同時在構造函數中添加如下代碼段this
1 resize(600, 500);//窗口大小 2 pix = QPixmap(400, 400);//畫布大小 3 pix.fill(Qt::white); 4 5 scale = 1;//不放大 6 zoomInButton = new QPushButton(this);//放大按鈕 7 zoomInButton->setText(tr("zoomIn")); 8 zoomInButton->move(400,450); 9 zoomOutButton = new QPushButton(this);//縮小按鈕 10 zoomOutButton->setText(tr("zoomOut")); 11 zoomOutButton->move(500,450); 12 13 connect(zoomInButton, SIGNAL(clicked()), this, SLOT(zoomIn())); 14 connect(zoomOutButton, SIGNAL(clicked()), this, SLOT(zoomOut()));
四、在mainwindow.cpp文件中配置相關的事件函數,代碼以下spa
1 void MainWindow::paintEvent(QPaintEvent *) 2 { 3 QPainter pp(&pix); 4 pp.drawLine(lastPoint/scale, endPoint/scale);//保證畫布座標和窗口座標相同,避免窗口座標變化,而畫布座標未發生改變 5 lastPoint = endPoint; 6 QPainter painter(this); 7 painter.scale(scale, scale);//進行放大操做,放大的是窗口座標。若是想放大畫布座標,則執行pp.scale(scale, scale); 8 painter.drawPixmap(0, 0, pix);//從窗口的原點(0, 0)添加該QPixmap對象,在窗口中放置畫布pix。 9 //若drawPixmap(0, 0, 100, 100, pix),則指定了添加對象的尺寸大小 10 } 11 12 void MainWindow::mousePressEvent(QMouseEvent *event) 13 { 14 if(event->button() == Qt::LeftButton)//button()函數返回的是按下的鍵,直接判斷是否爲某個鍵。適用於鼠標鍵一次按下 15 { 16 lastPoint = event->pos(); 17 } 18 } 19 20 void MainWindow::mouseMoveEvent(QMouseEvent *event) 21 { 22 if(event->buttons()&Qt::LeftButton)//buttons()函數返回的是按下的鍵的狀態,須要經過OR運算進行判斷。適用於鼠標鍵持續按下 23 { 24 endPoint = event->pos(); 25 update();//調用update()函數會進行paintEvent()函數的從新繪製 26 } 27 } 28 29 void MainWindow::mouseReleaseEvent(QMouseEvent *event) 30 { 31 if(event->button() == Qt::LeftButton) 32 { 33 endPoint = event->pos(); 34 update(); 35 } 36 } 37 38 void MainWindow::zoomIn() 39 { 40 scale *= 2;//放大兩倍 41 update(); 42 } 43 44 void MainWindow::zoomOut() 45 { 46 scale /= 2;//縮小兩倍 47 update(); 48 }
五、運行結果以下code