更新
uic 包中似乎存在一个错误,该错误会阻止在使用 uic.loadUi 时加载主题图标。
违规代码在 PyQt4/uic/icon_cache.py 中(第 60 行左右):
# Handle a themed icon.
theme = iconset.attrib.get('theme')
if theme is not None:
return self._object_factory.createQObject("QIcon.fromTheme",
'icon', (as_string(theme), ), is_attribute=False)
问题是使用as_string 函数,它试图通过,例如'_fromUtf8("face-smile")' 到 QIcon.fromTheme 而不是简单的图标名称。
如果您想解决这个问题,我建议您在 PyQt4 mailing list 上报告它。
请注意,等效功能在 PySide 中有效:
from PySide.QtUiTools import QUiLoader
class Window(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
QUiLoader().load('/tmp/test.ui', self)
以下是如何将pyuic4 与在 Qt Designer 中创建的 ui 一起使用的简单细分。
首先,创建您的用户界面。下面是一个最小的ui 文件,它创建了一个带有主题图标的按钮:
/tmp/test.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>Form</class>
<widget class="QWidget" name="Form">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>400</width>
<height>300</height>
</rect>
</property>
<property name="windowTitle">
<string>Form</string>
</property>
<widget class="QPushButton" name="pushButton">
<property name="geometry">
<rect>
<x>110</x>
<y>100</y>
<width>92</width>
<height>25</height>
</rect>
</property>
<property name="text">
<string>PushButton</string>
</property>
<property name="icon">
<iconset theme="face-smile"/>
</property>
</widget>
</widget>
<resources/>
<connections/>
</ui>
接下来,使用pyuic4 从ui 文件中编译一个python 模块:
pyuic4 -o /tmp/test_ui.py /tmp/test.ui
/tmp/test_ui.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file '/tmp/test.ui'
#
# Created: Fri Sep 21 16:45:39 2012
# by: PyQt4 UI code generator 4.9.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName(_fromUtf8("Form"))
Form.resize(400, 300)
self.pushButton = QtGui.QPushButton(Form)
self.pushButton.setGeometry(QtCore.QRect(110, 100, 92, 25))
icon = QtGui.QIcon.fromTheme(_fromUtf8("face-smile"))
self.pushButton.setIcon(icon)
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.retranslateUi(Form)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(QtGui.QApplication.translate("Form", "Form", None, QtGui.QApplication.UnicodeUTF8))
self.pushButton.setText(QtGui.QApplication.translate("Form", "PushButton", None, QtGui.QApplication.UnicodeUTF8))
现在将编译好的 ui 类导入你的应用程序:
/tmp/test.py
from PyQt4 import QtGui, QtCore
from test_ui import Ui_Form
class Window(QtGui.QWidget, Ui_Form):
def __init__(self):
QtGui.QWidget.__init__(self)
self.setupUi(self)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
最后,运行应用程序:
python2.7 /tmp/test.py