绘图事件QPainter
绘图事件(需要重写的函数):paintEvent
声明一个画家对象 QPainter painter(this) 指定绘图设备
画线,画圆,画矩形,画文字
可设置画笔,画刷
# include <QPainter>
. . . . . .
void paintEvent ( QPaintEvent * ) ;
void MainWindow:: paintEvent ( QPaintEvent * )
{
QPainter painter ( this) ;
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 ( 10 , 200 , 100 , 50 ) , "举例举例举例举例举例举例" ) ;
QPen pen ( QColor ( 255 , 0 , 0 ) ) ;
painter. setPen ( pen) ;
painter. drawRect ( QRect ( 150 , 150 , 30 , 30 ) ) ;
QBrush brush ( QColor ( 0 , 255 , 0 ) ) ;
painter. setBrush ( brush) ;
painter. drawRect ( QRect ( 300 , 300 , 30 , 30 ) ) ;
}
QPainter高级设置
1.抗锯齿,效率低,清晰度提高:
painter.setRenderHint(QPainter::Antialiasing);
2.对画家移动:painter.translate(100,0);
3.保存状态,还原状态
void MainWindow:: paintEvent ( QPaintEvent * )
{
QPainter painter ( this) ;
painter. drawEllipse ( QPoint ( 100 , 50 ) , 50 , 50 ) ;
painter. setRenderHint ( QPainter:: Antialiasing) ;
painter. drawEllipse ( QPoint ( 200 , 50 ) , 50 , 50 ) ;
painter. drawRect ( QRect ( 200 , 200 , 30 , 30 ) ) ;
painter. translate ( 100 , 0 ) ;
painter. drawRect ( QRect ( 200 , 200 , 30 , 30 ) ) ;
painter. translate ( 100 , 0 ) ;
painter. restore ( ) ;
painter. drawRect ( QRect ( 200 , 200 , 30 , 30 ) ) ;
}
手动调用绘图事件
先导入资源图片;
如果需要手动调用绘图事件,利用update
利用画家画图片 painter.drawPixmap()
void paintEvent ( QPaintEvent * ) ;
int PosX= 0 ;
MainWindow:: MainWindow ( QWidget * parent)
: QMainWindow ( parent)
, ui ( new Ui:: MainWindow)
{
ui-> setupUi ( this) ;
connect ( ui-> pushButton, & QPushButton:: clicked, [ = ] ( ) {
PosX += 20 ;
update ( ) ;
} ) ;
}
void MainWindow:: paintEvent ( QPaintEvent * )
{
QPainter painter ( this) ;
if ( PosX> this-> width ( ) )
{
PosX = 0 ;
}
painter. drawPixmap ( PosX, 100 , QPixmap ( ":/1.jpg" ) ) ;
}