Search code examples
qtqgraphicsitemqpainter

How to draw selectable text with QPainter?


I need to implement a class like QGraphcisTextItem, however I need it to be selectable text.

However if my class descends from QGraphicsTextItem or QGraphicsItem, and I reimplement the paint event the ability for the text to be selectable is lost (I'm using drawText).

So my question is how can I create selectable text using QPainter's drawText?


Solution

  • I can't reproduce the issue you have with custom fonts. That's a very important bit of information that belongs in the question and changes the question substantially.

    The addApplicationFont is a static function that adds the font to the application-wide font database. Use the applicationFontFamilies(int id) to obtain the name of the family to use in html:

    ...
    auto id = QFontDatabase::addApplicationFont(":/fonts/myfont.ttf");
    if (if == -1)
      return;
    auto families = QFontDatabase::applicationFontFamilies(id);
    if (families.isEmpty())
      return;
    auto face = families.first().toHtmlEscaped();
    auto html = QStringLiteral("<font face=\"%1\">Hello</font>").arg(face);
    ...