开发者

How to set image on QPushButton?

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 u开发者_开发技巧sing QLabel, but not with QPushButton.

So, if anyone has a solution, then please help me out.


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());


QPushButton *button = new QPushButton;
button->setIcon(QIcon(":/icons/..."));
button->setIconSize(QSize(65, 65));


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.


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());


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 );
    }
};


You can do this in QtDesigner. Just click on your button then go to icon property and then choose your image file.


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


Just use this code

QPixmap pixmap("path_to_icon");
QIcon iconBack(pixmap);

Note that:"path_to_icon" is the path of image icon in file .qrc of your project You can find how to add .qrc file here


In case anybody needs a PyQt version of the first answer:

class PictureButton(QAbstractButton):

  def __init__(self, picture, parent):
    super().__init__(parent)
    self.setPicture(QPixmap(picture))

  def setPicture(self, picture):
    self.picture = picture
    self.update()

  def sizeHint(self):
    return self.picture.size()

  def paintEvent(self, e):
    painter = QPainter(self)
    painter.drawPixmap(0, 0, self.picture)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜