如何在Qt Designer中为带占位符的QPushButton设置图标?

1 投票
3 回答
12324 浏览
提问于 2025-04-18 14:05

解决方案:
这是我的错误:我在用QtDesigner添加按钮图标时,使用了“placeholder”功能。主程序在一个不同的文件夹里,它只在自己的文件夹中寻找图标,而不是在“导入”的文件所在的文件夹里。所以你只需要把图标的路径加上就可以了:

dirpath = os.path.dirname(os.path.abspath(__file__))
icon1_path = os.path.join(dirpath,"arrow_down.ico")
icon = QtGui.QPixmap(icon1_path)

我想创建一个带图标的Qpushbutton,而不是文字:

icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap("arrow_down.png"))
self.ui.pb_down.setIcon(icon)

但是这并不奏效。这个也不行:

self.ui.pb_down.setIcon(QtGui.QIcon("arrow_down.png"))

没有错误提示,图标就是不显示。

如果我通过Qt Designer添加图标,图标在Qt Designer里是能显示的,但运行程序时,图标又消失了。有人知道这是怎么回事吗?

我使用的是Python 2.7和Windows 7

编辑: 使用@Chris Aung的代码,我得到了一个带图标的按钮。

    button = QtGui.QPushButton()
    self.setCentralWidget(button)
    icon = QtGui.QIcon()
    icon.addPixmap(QtGui.QPixmap("arrow_down.ico"))
    print button.icon().isNull()  #Returns true if the icon is empty; otherwise returns false.
    #output = False

但是如果我在我的GUI中完全使用这段代码,它就是不添加图标。

    icon = QtGui.QIcon()
    icon.addPixmap(QtGui.QPixmap("arrow_down.ico"))
    self.ui.pb_down.setIcon(icon)
    print self.ui.pb_down.icon().isNull()
    # output = True

我不知道问题出在哪里。

3 个回答

0

你那个按钮上有文字吗?
可以试着调整一下图标的大小,使用setIconSize()这个方法。刚开始可以把它设置成和图片的大小一样。

2

这个对我来说有效,而且是通过pyqt自动生成的,当你用pyuic4工具把一个.ui文件转换成.py文件时。

    Icon = QtGui.QIcon()
    Icon.addPixmap(QtGui.QPixmap(_fromUtf8("SOME FILE")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
    button.setIcon(Icon)
    button.setIconSize(QtCore.QSize(width, height))

如果你使用这个,你还需要在模块的顶部定义"_fromUtf8",像这样:

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s
2

我用你提供的代码成功创建了带图标的 QPushButton,没有遇到任何问题。以下是我使用的代码。

from PyQt4 import QtGui,QtCore
import sys

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        button = QtGui.QPushButton("TEST")
        self.setCentralWidget(button)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("add.png"))
        button.setIcon(icon)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    main = MainWindow()
    main.show()
    app.exec_()

我建议你再检查一下你的 png 图片(或者试试其他的 png 图片)。我不能完全保证这样就能解决问题,但我之前遇到过类似的问题,换一张不同的 .png 图片似乎能解决这个问题。

撰写回答