Qt philosophy to using or not using 'const'
-
I stumbled upon a specific example of "why didn't they make that const?":
I create a QTextLayout for a custom paint engine (in my case, a printer)
QTextLayout layout(text, font, m_Printer);
m_Printer is a class member. However, I'd like to use a text layout in some pre-calculation method, and didn't see why I shouldn't make that method const:
qreal MyClass::calculateTextBlockHeight(const QString& text, const QFont& font) const { QTextLayout layout(text, font, m_Printer); // Some layout code return calculatedHeight; }
What stops me from making the method const: QTextLayout expects a non-const QPaintDevice as 3rd parameter. I wonder: What would QTextLayout want to change on my paint device?
Turns out it doesn't want to change anything: The paint device is just used in a QFont-constructor internally (which also takes it non-const), and then all the code does is read the logical DPI. So both constructors of QFont and QTextLayout would be perfectly happy with a const QPaintDevice*, and so would I.
Would you consider this an oversight, or is there some coding standard or interface philosophy behind?
-
It's a good suggestion for a change in Qt 6, add it in https://bugreports.qt.io
In the meantime, given, as you noted correctly, the paint device is used only as it was
const
it's still safe to const-cast it and pass it:QTextLayout layout(text, font, const_cast<MyClass*>(this)->m_Printer);
Edit:
Related bug: https://bugreports.qt.io/browse/QTBUG-65967