Offer arrives, dig friends to pick up! I am participating in the 2022 Spring Recruitment Check-In Event, click to view the event details .
Foreword:
The paintEvent() function provided by QWidget is a pure virtual function, which must be reimplemented when subclasses inheriting from it want to repaint.
Situations where a repaint event is raised:
- When the window control is displayed for the first time, the system automatically generates a drawing event.
- When the repaint() and update() functions are called.
- When the window control is obscured by other widgets and then displayed again, a repaint event is generated for the hidden area.
- When resizing the window.
The paintEvent() function is a highly optimized function that has been automatically turned on and implemented a double buffering mechanism, so repainting in Qt will not cause any flickering on the screen.
repaint() function:
- repaint() is the fastest to cause a repaint operation. In an emergency , you can call repaint() when you need to repaint immediately .
- But repaint() cannot be called in the paintEvent() function, or cause an infinite loop.
update() function:
- After the update() is called , it will not be redrawn immediately , but the redraw event will be put into the main loop and dispatched uniformly by the Event Loop of the main() main function.
- update() is optimized before calling paintEvent(), if update() is called many times, finally these update() will be merged into a big repaint event and added to the message queue, and finally only this big update () is executed once .
Compared with update(), repaint() is generally enough to call update(). When update() cannot meet the requirements, try to use repaint().
Implement drawing operations in paintEvent():
Commonly used tools for drawing include the brush class QPen, the brush class QBrush, and the font class QFont, etc., which all inherit from the QPainter class.
- QPainter can draw various basic graphics.
- The QPen class is used to draw the edges of geometric figures, consisting of parameters such as color, width, and line style.
- The QBrush class is a palette for filling geometry, consisting of a color and a fill style.
- The QFont class is used for text drawing and consists of font properties.
example:
void Widget::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
painter.drawLine(10, 100, 30, 300);//画线
painter.setPen(Qt::red);
painter.drawRect(10, 10, 100, 100);//红色矩形框
painter.setPen(QPen(Qt::green, 5));
painter.setBrush(Qt::blue);
painter.drawEllipse(100, 10, 200, 200);//绿边蓝色填充椭圆
}
复制代码
For other specific usage, please refer to the help manual.