QPainterStateGuard: also check for nullptr painter in save(), restore()

The ctor refuses to be called with a nullptr painter, but a moved-from
QPainterStateGuard object _will_ have a nullptr painter. An assert
gives a slightly nicer error message than "nullptr deref".

Extract Method verifyPainter() to not litter the executable with
string literals for every one of the these functions (some compilers
don't use the leeway extended to them by the standard to fold duplicate
string literals).

Found in API-review.

Amends ec3a5f4994a2bafc65fa8e01fb0861219580f622.

Change-Id: I562e6a0ff5a4c8ce86418b998ed78c501441b61a
Reviewed-by: Giuseppe D'Angelo <giuseppe.dangelo@kdab.com>
Reviewed-by: Axel Spoerl <axel.spoerl@qt.io>
Reviewed-by: Juha Vuolle <juha.vuolle@qt.io>
(cherry picked from commit 5c20f9aa5c31d30a2dccfc617e93c6d6ac0fc96c)
Reviewed-by: Qt Cherry-pick Bot <cherrypick_bot@qt-project.org>
This commit is contained in:
Marc Mutz 2025-01-30 12:09:01 +01:00 committed by Qt Cherry-pick Bot
parent a546662cd8
commit 6067b27071

View File

@ -33,7 +33,7 @@ public:
explicit QPainterStateGuard(QPainter *painter, InitialState state = InitialState::Save)
: m_painter(painter)
{
Q_ASSERT(painter);
verifyPainter();
if (state == InitialState::Save)
save();
}
@ -46,18 +46,25 @@ public:
void save()
{
verifyPainter();
m_painter->save();
++m_level;
}
void restore()
{
verifyPainter();
Q_ASSERT(m_level > 0);
--m_level;
m_painter->restore();
}
private:
void verifyPainter()
{
Q_ASSERT(m_painter);
}
QPainter *m_painter;
int m_level = 0;
};