PySide和PyQt加载ui文件的两种方法

本文实例为大家分享了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文件了,而且这两种调用方法的性能和占用的内存都有人专门测试过,但作者也比较推荐第一种方法。