Python QPushButton setIcon:将图标放在按钮上

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1905402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:18:24  来源:igfitidea点击:

Python QPushButton setIcon: put icon on button

pythonuser-interfaceqtbuttonicons

提问by ThreaderSlash

I want to put an in ICON into a push button.. the code should work like that:

我想将一个 in ICON 放入一个按钮中..代码应该像这样工作:

    self.printButton = QtGui.QPushButton(self.tab_name)
    self.printButton.setIcon(QtGui.QPixmap('printer.tif'))
    self.printButton.setGeometry(QtCore.QRect(1030, 500, 161, 61))

But instead, it gives the error message:

但相反,它给出了错误消息:

    TypeError: argument 1 of QAbstractButton.setIcon() has an invalid type

What is missing here?

这里缺少什么?

All comments and suggestions are highly appreciated.

非常感谢所有的意见和建议。

回答by Andy M

This is strange, I quickly tested the code on my C++ application and it seems to be working...

这很奇怪,我很快在我的 C++ 应用程序上测试了代码,它似乎工作......

Maybe by using this you could correct your problem :

也许通过使用这个你可以纠正你的问题:

rMyIcon = QtGui.QPixmap("printer.tif");
self.printButton.setIcon(QtGui.QIcon(rMyIcon))

Hope this helps a bit...

希望这个对你有帮助...

回答by baysmith

Create a QIcon rather than a QPixmap for passing to setIcon(). Try changing the second line to

创建一个 QIcon 而不是 QPixmap 来传递给 setIcon()。尝试将第二行更改为

self.printButton.setIcon(QtGui.QIcon('printer.tif'))

回答by ThreaderSlash

Hi Baysmith and Andy... thanks for the input. I tested your suggestions, it worked. I also have to add setIconSize, otherwise the icon is displayed very small. Here is code:

嗨,贝史密斯和安迪...感谢您的投入。我测试了你的建议,它奏效了。我还必须添加setIconSize,否则图标显示的很小。这是代码:

def printerButton(self,tab_name):
    self.printButton = QtGui.QPushButton(tab_name)
    self.printButton.setIcon(QtGui.QIcon('icons/printer.tif'))
    self.printButton.setIconSize(QtCore.QSize(130,130))
    self.printButton.setGeometry(QtCore.QRect(1030, 500, 161, 61))

Hope this help others too....|:0),

希望这对其他人也有帮助....|:0),