Create QIcon from a string



  • I have a piece of code to create an QIcon from given string:

    QIcon* CreateIcon(const QString& content, int iw, int ih)
    {
        auto pixmap = new QPixmap(iw, ih);
        auto painter = new QPainter(pixmap);
        painter->setPen(QColor(255, 0, 0, 128));
        painter->drawText(QRect(0, 0, iw, ih), content);
        return new QIcon(*pixmap);
    }
    

    Unfortunately the icon will be drawn and I can see the text, but somehow impure.
    What I do wrong?
    Probable the code is incomplete...

    Thanks for help!



  • Maybe system using bitmap font. Set a scalable font using by void QPainter::setFont(const QFont &font)


  • Moderators

    @peter-70 said in Create QIcon from a string:

    Unfortunately the icon will be drawn and I can see the text, but somehow impure.

    What size(s) do you use to display your icon?

    QIcon* CreateIcon(const QString& content, int iw, int ih)
    {
        auto pixmap = new QPixmap(iw, ih);
        auto painter = new QPainter(pixmap);
        painter->setPen(QColor(255, 0, 0, 128));
        painter->drawText(QRect(0, 0, iw, ih), content);
        return new QIcon(*pixmap);
    }
    

    Don't use new to create QIcon, QPixmap, and QPainter. (This won't make your icon look better, but this helps keep your code clean)

    QPixmap pixmap(iw, ih);
    QPainter painter(&pixmap);
    painter.setPen(QColor(255, 0, 0, 128));
    painter.drawText(QRect(0, 0, iw, ih), content);
    return QIcon(pixmap);


  • See if renderHint QPainter::TextAntialiasing for your painter makes a difference


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.