[SOLVED] Button with Icons via code



  • I try to create a bool-indcator button. So I have some question about images.
    I have a recoure file with windows ico files. Every iconfile has 3 incons integrated with different size. This is very practicable, because I can change in dialog designer the icon-size and it seem as it puts the best matching icon of the 3 for this size.

    But how can I do this via code?

            QPixmap pix(":/images/Games.ico");
            QIcon icon(pix);
            c->setIcon(icon);
            c->setIconSize(QSize(16,16));
    

    This picks always the 48x48 icon and scales it to 16x16, what looks bad.
    How can it pick a subicon with a special size from a resource file ???

    I want 2 different icon for the On and Off state for this button. Via Designer I can configure different icons for the 2 states (Normal on/Normal Off property).
    How can I make this via code? I found only the function setIcon() which set on/off state to the same icon.


  • Moderators



  • Hi,

    instead of assigning the pixmap on QIcon constructor you shoud use addPixmap

    QIcon icon;
    icon.addPixmap(onPixmap, QIcon::Normal, QIcon::On);
    icon.addPixmap(offPixmap, QIcon::Normal, QIcon::Off);
    

    if you also need to set different pixmap depending on the size you can use QIcon::addFile()


  • Moderators

    @mcosta Yes, seems like the QIcon from pixmap constructor needs some improvement.



  • @Wieland said:

    @mcosta Yes, seems like the QIcon from pixmap constructor needs some improvement.

    The standard constructor is enough for standard usage.
    Qt usually makes default things simple and provides API to use advanced feature (QMessageBox is another example)



  • I found out the "read all subicons" is integreated in the constructor yet.
    The problem was the indirect loading in a pixmap before.
    Now, it takes really the best matching iconsize, automatically.

            QPushButton *c = new QPushButton(OnText, parent);
            QIcon icon(":/images/Games.ico");
            c->setIcon(icon);
            c->setIconSize(QSize(16,16));

  • Moderators

    Cool! :-) Could you please post one of your icon files? I would like to check if this works with QtQuick, too.



  • @Wieland
    how can I upload files here ?


Log in to reply
 

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