赞
踩
1、进入Pycharm的设置界面
2、进入外部工具设置
3、配置designer.exe,注意program路径和working directory路径
4、配置pyUIC,注意找到pyside-uic.exe文件所在的路径和参数
我们打开.ui文件时会发现ui文件实际上是一个xml文件,我们可以写一个方法解析ui文件,并且返回该界面类及其基类,例如我们写的是一个主窗口界面继承自QMainWindow,类名为MyWindow,那么我们就可以返回QMainWindow和MyWindow,这里的代码来自PySide和PyQt加载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)
还有一种使用QUiloade可以直接动态加载ui文件的方法QUiloader,示例代码为:
class MyWidget(QWidget):
def __init__(self, parent):
super(QWidget, self).__init__(parent)
loader = QUiLoader()
file = QFile(":/forms/myform.ui")
file.open(QFile.ReadOnly)
myWidget = loader.load(file, self)
file.close()
layout = QVBoxLayout()
layout.addWidget(myWidget)
self.setLayout(layout)
利用with语句可以简化文件操作:
from PySide.QtGui import *
from PySide.QtUiTools import *
from PySide.QtCore import *
import sys
class UiFile:
def __init__(self,file_name):
self.file_name = file_name
self.file = QFile(file_name)
def __enter__(self):
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
self.file.close()
def Open_UiFile(filename):
return UiFile(filename)
if __name__ == '__main__':
app = QApplication(sys.argv)
loader = QUiLoader()
with Open_UiFile('tt.ui') as file:
file.open(QFile.ReadOnly)
myDialog = loader.load(file)
myDialog.button = QPushButton("test",myDialog)
myDialog.verticalLayout.addWidget(myDialog.button)
myDialog.show()
sys.exit(app.exec_())
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。