How to set image on QPushButton?

前端 未结 8 424
时光说笑
时光说笑 2020-11-30 21:34

I want to set an image on QPushButton, and the size of QPushButton should depend on the size of the image. I am able to do this when using QL

相关标签:
8条回答
  • 2020-11-30 22:08

    You can also use:

    button.setStyleSheet("qproperty-icon: url(:/path/to/images.png);");
    

    Note: This is a little hacky. You should use this only as last resort. Icons should be set from C++ code or Qt Designer.

    0 讨论(0)
  • 2020-11-30 22:10

    You may also want to set the button size.

    QPixmap pixmap("image_path");
    QIcon ButtonIcon(pixmap);
    button->setIcon(ButtonIcon);
    button->setIconSize(pixmap.rect().size());
    button->setFixedSize(pixmap.rect().size());
    
    0 讨论(0)
  • 2020-11-30 22:10

    I don't think you can set arbitrarily sized images on any of the existing button classes. If you want a simple image behaving like a button, you can write your own QAbstractButton-subclass, something like:

    class ImageButton : public QAbstractButton {
    Q_OBJECT
    public:
    ...
        void setPixmap( const QPixmap& pm ) { m_pixmap = pm; update(); }
        QSize sizeHint() const { return m_pixmap.size(); }
    protected:
        void paintEvent( QPaintEvent* e ) {
            QPainter p( this );
            p.drawPixmap( 0, 0, m_pixmap );
        }
    };
    
    0 讨论(0)
  • 2020-11-30 22:11
    QPushButton *button = new QPushButton;
    button->setIcon(QIcon(":/icons/..."));
    button->setIconSize(QSize(65, 65));
    
    0 讨论(0)
  • 2020-11-30 22:13

    This is old but it is still useful, Fully tested with QT5.3.

    Be carreful, example concerning the ressources path :

    In my case I created a ressources directory named "Ressources" in the source directory project.

    The folder "ressources" contain pictures and icons.Then I added a prefix "Images" in Qt So the pixmap path become:

    QPixmap pixmap(":/images/Ressources/icone_pdf.png");

    JF

    0 讨论(0)
  • 2020-11-30 22:14

    What you can do is use a pixmap as an icon and then put this icon onto the button.

    To make sure the size of the button will be correct, you have to reisze the icon according to the pixmap size.

    Something like this should work :

    QPixmap pixmap("image_path");
    QIcon ButtonIcon(pixmap);
    button->setIcon(ButtonIcon);
    button->setIconSize(pixmap.rect().size());
    
    0 讨论(0)
提交回复
热议问题