
用到的類:QTimer,QPaintEvent,QPainter,QRectF

首先,重寫繪制事件,需要在頭檔案加入QPaintEvent頭檔案,并定義幾個變數,
bool ison=false;
float currentValue;
float widthSize,heightSize;
然后加入如下代碼:
思路就是滑鼠點擊,觸發paintEvent函式
void MainWindow::mousePressEvent(QMouseEvent *event){
Q_UNUSED(event)
ison=!ison; //在頭檔案種定義:bool ison=false;
//當滑鼠點擊,ison為true;
timer->start(1);//定時器開始(ms級)
this->update();//觸發paintEvent函式
}
paintEvent函式的重寫
void MainWindow::paintEvent(QPaintEvent *event){
Q_UNUSED(event)
QPainter painter(this);
painter.setRenderHint(QPainter::SmoothPixmapTransform);
//QPainter::SmoothPixmapTransform 使用平滑的pixmap變換演算法(雙線性插值演算法),而不是近鄰插值算,
painter.setRenderHint(QPainter::Antialiasing); //使繪制時邊緣平滑,qt反走樣默認關閉
painter.setPen(Qt::NoPen);//畫筆樣式,這里無
if(ison){
painter.save();//保存當前畫筆的狀態,與下面的restore();成對出現
painter.setBrush(Qt::green);
QRectF greenRect=QRectF(0,0,widthSize,heightSize);
painter.drawRoundedRect(greenRect,0.5*heightSize,0.5*heightSize);
painter.restore();
painter.save();
painter.setBrush(Qt::white);
painter.drawEllipse(currentValue,0.05*heightSize,0.9*heightSize,0.9*heightSize);
painter.restore();//恢復畫筆
//save() 用于保存 QPainter 的狀態,restore() 用于恢復 QPainter 的狀態,save() 和 restore() 一般都是成對使用的,
//如果只呼叫了 save() 而不呼叫 restore(),那么保存就沒有意義了,保存是為了能恢復被保存的狀態而使用的,
}else{
//邊框
painter.save();
QColor grayColor(199,199,199);//灰色
painter.setBrush(grayColor);//畫筆顏色
QRectF roundRect=QRectF(0,0,widthSize,heightSize);
painter.drawRoundedRect(roundRect,0.5*heightSize,0.5*heightSize);
//繪制橢圓邊框
painter.restore();
//背景
painter.save();
painter.setBrush(Qt::red);
QRectF redRect=QRectF(heightSize*0.05,heightSize*0.05,widthSize-heightSize*0.1,heightSize*0.9);
painter.drawRoundedRect(redRect,0.45*heightSize,0.45*heightSize);
//第1、2個引數制定矩形的左上角起點,第3個引數制定矩形的長度,第4個引數指定矩形的寬度
//最后兩個引數決定角的圓度,它可以為0到99之間的任意值(99代表最圓),
//繪制圓形矩形
painter.restore();
//按鈕
painter.save();
painter.setBrush(Qt::white);
painter.drawEllipse(currentValue,0.05*heightSize,0.9*heightSize,0.9*heightSize);
//第1,2個引數表示圓/橢圓距螢屏左上角的像素數,第3,4個引數表示圓/橢圓的寬度和高度,兩者相同時為圓,
//繪制圓按鈕
painter.restore();
}
}
滑鼠點擊進行繪制,按鈕從左邊滑到右邊應該有一個運動狀態,這就是定時器,
在表單建構式中進行信號系結:
timer=new QTimer(this);
timer->setInterval(50);
connect(timer,SIGNAL(timeout()),this,SLOT(begainAnimation()));
//下面是繪制引數相關
if(ison){
currentValue=widthSize-0.95*heightSize;
}else{
currentValue=0.05*heightSize;
}
然后撰寫begainAnimation函式:
void MainWindow::begainAnimation(){
int i=0.05*heightSize;
int n=widthSize-0.95*heightSize;
if(ison){
currentValue+=1;
if(currentValue>n-i){
timer->stop();
}
}else{
currentValue-=1;
if(currentValue<i){
timer->stop();
}
}
update();
//每1ms呼叫一次updata,
}
繪制矩形:paint->drawRect(20,20,160,160);
第1、2個引數制定矩形的左上角起點,第3個引數制定矩形的長度,第4個引數指定矩形的寬度
繪制圓和橢圓:paint->drawEllipse(20,20,210,160);
第1,2個引數表示圓/橢圓距螢屏左上角的像素數,第3,4個引數表示圓/橢圓的寬度和高度,兩者相同時為圓,
繪制圓角矩形:paint->drawRoundRect(20,20,210,160,50,50);
前面四個引數和繪制矩形的引數一致,最后兩個引數決定角的圓度,它可以為0到99之間的任意值(99代表最圓),
CSDN認證博客專家
Qt
C
C++
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/190703.html
標籤:java
