我想在 QPushButton
上设置一张图片,同时 QPushButton
的大小应该根据图片的大小自适应。使用 QLabel
时可以实现这一点,但是使用 QPushButton
时不能。
如果有人有解决方案,请帮忙提供。
我想在 QPushButton
上设置一张图片,同时 QPushButton
的大小应该根据图片的大小自适应。使用 QLabel
时可以实现这一点,但是使用 QPushButton
时不能。
如果有人有解决方案,请帮忙提供。
您可以使用 pixmap 作为图标,然后将此图标放置在按钮上。
为确保按钮的尺寸正确,您需要根据 pixmap 的大小调整图标的大小。
类似这样的代码应该可以实现:
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));
您也可以使用:
button.setStyleSheet("qproperty-icon: url(:/path/to/images.png);");
注意:这有点hacky。你应该只在万不得已时使用它。图标应该从 C++
代码或 Qt Designer
中设置。
您可能也希望设置按钮的尺寸。
QPixmap pixmap("image_path");
QIcon ButtonIcon(pixmap);
button->setIcon(ButtonIcon);
button->setIconSize(pixmap.rect().size());
button->setFixedSize(pixmap.rect().size());
我认为你不能在任何现有的按钮类上设置任意大小的图片。如果你想要一个简单的像按钮一样的图片,你可以编写自己的QAbstractButton子类,例如:
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 );
}
};
这是一个老的但仍然有用的技术,已经在QT5.3中进行了全面测试。
注意,关于资源路径的例子:
我的情况下,我在源代码项目中创建了一个名为“Ressources”的资源目录。
文件夹“ressources”包含图片和图标。然后我在Qt中添加了一个前缀“Images”,所以像素图路径变为:
QPixmap pixmap(":/images/Ressources/icone_pdf.png");
JF
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)
只需使用此代码
QPixmap pixmap("path_to_icon");
QIcon iconBack(pixmap);
"path_to_icon"
是您项目中 .qrc
文件中图像图标的路径。 您可以在此处找到如何添加.qrc
文件here。