本页内容

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)

若state 为InitialState::Save (这是默认值),则构建一个QPainterStateGuard,并在painter 上调用save()。当QPainterStateGuard被销毁时,restore()的调用次数将与save()的调用次数相同,以恢复QPainter 的状态。

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

从other 动态构造一个画家状态守护者。

[noexcept] QPainterStateGuard::~QPainterStateGuard()

销毁QPainterStateGuard 实例,并调用restore()的次数与调用save()的次数相同,以恢复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 赋值给此绘图状态守护变量。

© 2026 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.