QPainterStateGuard Class

QPainterStateGuard 是一个 RAII 方便类,用于平衡QPainter::save() 和QPainter::restore() 调用。更多

头文件: #include <QPainterStateGuard>
CMake: find_package(Qt6 REQUIRED COMPONENTS Gui)
target_link_libraries(mytarget PRIVATE Qt6::Gui)
qmake: QT += gui
Qt 6.9

注意:该类中的所有函数都是可重入的

公共函数

QPainterStateGuard(QPainter *painter, QPainterStateGuard::InitialState state = InitialState::Save)
QPainterStateGuard(QPainterStateGuard &&other)
~QPainterStateGuard()
void restore()
void save()
void swap(QPainterStateGuard &other)
QPainterStateGuard &operator=(QPainterStateGuard &&other)

详细说明

QPainterStateGuard 在任何地方都应作为QPainter::save() 的替代函数使用,以确保在完成绘制例程后调用相应的QPainter::restore() 以避免这两个函数之间的不平衡调用。

使用QPainter::save()/QPainter::restore() 的示例:

void MyWidget::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.setPen(Qt::red);
    if (drawText) {
        painter.save();
        painter.setPen(Qt::blue);
        painter.setFont(QFont("Arial", 30));
        painter.drawText(rect(), Qt::AlignCenter, "Qt");
        painter.restore();  // don't forget to restore previous painter state
    }
    painter.drawLine(line);
}

使用 QPainterStateGuard 的示例:

void MyGuardWidget::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.setPen(Qt::red);
    if (drawText) {
        QPainterStateGuard guard(&painter)
        painter.setPen(Qt::blue);
        painter.setFont(QFont("Arial", 30));
        painter.drawText(rect(), Qt::AlignCenter, "Qt");
    }
    painter.drawLine(line);
}

另请参阅 QPainter

成员函数文档

[explicit] QPainterStateGuard::QPainterStateGuard(QPainter *painter, QPainterStateGuard::InitialState state = InitialState::Save)

构造一个 QPainterStateGuard,如果stateInitialState::Save (默认情况),则在painter 上调用save() 。当 QPainterStateGuard 被销毁时,调用restore() 的次数与调用save() 的次数相同,以恢复QPainter 的状态。

[noexcept] QPainterStateGuard::QPainterStateGuard(QPainterStateGuard &&other)

移动-从other 中构建一个画家国家卫队。

[noexcept] QPainterStateGuard::~QPainterStateGuard()

销毁QPainterStateGuard 实例,并像调用save() 那样频繁调用restore() 以恢复QPainter 的状态。

void QPainterStateGuard::restore()

如果内部保存/恢复计数器大于零,则调用QPainter::restore() 。

注意: 如果计数器已经归零,该函数会在调试构建时断言。

void QPainterStateGuard::save()

调用QPainter::save() 并将内部保存/恢复计数器增加一个。

[noexcept] void QPainterStateGuard::swap(QPainterStateGuard &other)

other 与该画家的国家卫队对调。这一操作非常快速,而且从未出现过故障。

[noexcept] QPainterStateGuard &QPainterStateGuard::operator=(QPainterStateGuard &&other)

移动-将other 指派给该画家的国家卫队。

© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.