本文实例为大家分享了PySide和PyQt加载ui文件的具体实现代码,供大家参考,具体内容如下
在用PySide或PyQt的时候,经常用到要将画好的ui文件导入到代码里使用,下面是两种调入的方法:
import PyQt4.uic
from PyQt4 import QtCore, QtGui
MainWindowForm, MainWindowBase = PyQt4.uic.loadUiType('ui/mainwindow.ui')
class MainWindow(MainWindowBase, MainWindowForm):
def __init__(self, parent = None):
super(MainWindow, self).__init__(parent)
# setup the ui
self.setupUi(self)
if ( __name__ == '__main__' ):
app = None
if ( not app ):
app = QtGui.QApplication([])
window = MainWindow()
window.show()
if ( app ):
app.exec_()
第二种:
import PyQt4.uic
from PyQt4 import QtCore, QtGui
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent = None):
super(MainWindow, self).__init__(parent)
# load the ui
PyQt4.uic.loadUi('ui/mainwindow.ui', self)
if ( __name__ == '__main__' ):
app = None
if ( not app ):
app = QtGui.QApplication([])
window = MainWindow()
window.show()
if ( app ):
app.exec_()
当然如果是用PySide的话,我们可以写个专门读取ui文件的方法,将baseclass和formclass返回出去,供后面UI的类继承。
# -*- coding: utf-8 -*-
from PySide import QtGui
import xml.etree.ElementTree as xml
from cStringIO import StringIO
def load_ui_file(ui_file, type='PySide'):
if type == 'PySide':
import pysideuic
print pysideuic
parsed = xml.parse(ui_file)
widget_class = parsed.find('widget').get('class')
form_class = parsed.find('class').text
with open(ui_file, 'r') as f:
o = StringIO()
frame = {}
pysideuic.compileUi(f, o, indent=0)
pyc = compile(o.getvalue(), '<string>', 'exec')
exec pyc in frame
form_class = frame['Ui_%s' % form_class]
base_class = getattr(QtGui, widget_class)
return form_class, base_class
elif type == 'PyQt4':
import PyQt4.uic
return PyQt4.uic.loadUiType(ui_file)
if __name__ == "__main__":
ui_file = 'test.ui'
load_ui_file(ui_file)
这样Pyside和PyQt就可以调用.ui文件了,而且这两种调用方法的性能和占用的内存都有人专门测试过,但作者也比较推荐第一种方法。
您可能感兴趣的文章:PyQt5的安装配置过程,将ui文件转为py文件后显示窗口的实例详解python做UI界面的方法利用pyuic5将ui文件转换为py文件的方法解决pyqt中ui编译成窗体.py中文乱码的问题pyqt实现.ui文件批量转换为对应.py文件脚本解决.ui文件生成的.py文件运行不出现界面的方法