圆月山庄资源网 Design By www.vgjia.com

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

标签:
PySide,PyQt加载ui文件,PySide,PyQt导入ui文件,PySide加载ui文件

圆月山庄资源网 Design By www.vgjia.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
圆月山庄资源网 Design By www.vgjia.com