Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Qt philosophy to using or not using 'const'
QtWS25 Last Chance

Qt philosophy to using or not using 'const'

Scheduled Pinned Locked Moved Solved General and Desktop
2 Posts 2 Posters 547 Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A Offline
    A Offline
    Asperamanca
    wrote on last edited by Asperamanca
    #1

    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?

    1 Reply Last reply
    0
    • VRoninV Offline
      VRoninV Offline
      VRonin
      wrote on last edited by VRonin
      #2

      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

      "La mort n'est rien, mais vivre vaincu et sans gloire, c'est mourir tous les jours"
      ~Napoleon Bonaparte

      On a crusade to banish setIndexWidget() from the holy land of Qt

      1 Reply Last reply
      3

      • Login

      • Login or register to search.
      • First post
        Last post
      0
      • Categories
      • Recent
      • Tags
      • Popular
      • Users
      • Groups
      • Search
      • Get Qt Extensions
      • Unsolved