1.定时器 QTimer
⭐创建定时器对象QTimer *timer = new QTimer(this);
⭐ 启动定时器timer->start(毫秒);
⭐ 监听信号 connect(timer,&QTimer::timeout,[=](){ });
———————————————————–例子———————————————————–
QTimer *timer = new QTimer(this); timer->start(500); connect(timer,&QTimer::timeout,[=](){ static int num = 1; ui->label->setText(QString::number(num++)); });
⭐ 点击暂停,实现停止,点击开始,继续计时
connect(ui->pushButton_stop,&QPushButton::clicked,[=](){ timer->stop(); }); connect(ui->pushButton_start,&QPushButton::clicked,[=](){ timer->start(); });
2.绘图 QPainter
⭐创建绘图事件 void paintEvent(QPaintEvent *);
⭐ 实例化画家对象QPainter painter(this);
⭐ 画线—drawLine,画圆—drawEllipse,画矩形—drawRect,画文字—drawText
⭐ 设置画笔—QPen pen, 设置画刷—QBrush brush,让画家使用画笔、画刷
———————————————————–例子———————————————————–
void MainWindow::paintEvent(QPaintEvent *){ QPainter painter(this); // 设置画笔 QPen pen(QColor(255,0,0)); pen.setWidth(3); pen.setStyle(Qt::DotLine); painter.setPen(pen); // 设置画刷 QBrush brush(Qt::cyan); brush.setStyle(Qt::Dense7Pattern); painter.setBrush(brush); // 画线 painter.drawLine(QPoint(0,0), QPoint(100,100)); // 画圆 painter.drawEllipse(QPoint(100,100), 50 ,50); // 画矩形 painter.drawRect(QRect(20,20,50,50)); // 画文字 painter.drawText(QRect(20,200,120,50),"好好学习,天天向上");
}
⭐ 抗锯齿,效率低 painter.setRenderHint(QPainter::Antialiasing);
⭐ 对画家进行移动 painter.translate(100,0);
⭐ 保存状态—save,还原状态—restore
———————————————————–例子———————————————————–
painter.drawRect(QRect(20,300,50,50)); painter.translate(100,0); painter.save(); // 保存画家状态 painter.drawRect(QRect(20,300,50,50)); painter.restore(); // 还原画家保存状态 painter.drawRect(QRect(20,300,50,50));
⭐ 手动调用绘图事件,点击按钮,进行图片移动
———————————————————–例子———————————————————–
connect(ui->pushButton_move,&QPushButton::clicked,[=](){ posX+=20; update(); // 手动调用,用update更新 });void MainWindow::paintEvent(QPaintEvent *){ QPainter painter(this); // 如果超出屏幕,从0开始 if(posX > this->width()) { posX = 0; } painter.drawPixmap(posX,200,QPixmap(":/img/lufei.jpg"));}