Как я могу сгенерировать код python из файла QtDesigner? Я нашел pyside-uic, но я не могу найти пример для синтаксиса. Я запускаю win7 и pythonxy со spyder.
Генерация кода Python с помощью pyside-uic
Ответ 1
pyside-uic более или менее идентичен pyuic4, так как таковая страница указывает:
Usage:
pyside-uic [options] <ui-file>
Options:
--version
show program version number and exit
-h,--help
show this help message and exit
-oFILE,--output=FILE
write generated code to FILE instead of stdout
-x,--execute
generate extra code to test and display the class
-d,--debug
show debug output
-iN,--ident=N
set indent width to N spaces, tab if N is 0 (default: 4)
Я обычно использую его так:
pyside-uic -o output.py input.ui
Ответ 2
Просто попробовал Pyside QUILoader, отлично работает:
from PySide import QtGui
from PySide import QtCore
from PySide import QtUiTools
class MyWidget(QtGui.QMainWindow):
def __init__(self, *args):
apply(QtGui.QMainWindow.__init__, (self,) + args)
loader = QtUiTools.QUiLoader()
file = QtCore.QFile("pyside_ui_qtdesigner_form_test.ui")
file.open(QtCore.QFile.ReadOnly)
self.myWidget = loader.load(file, self)
file.close()
self.setCentralWidget(self.myWidget)
if __name__ == '__main__':
import sys
import os
print("Running in " + os.getcwd() + " .\n")
app = QtGui.QApplication(sys.argv)
win = MyWidget()
win.show()
app.connect(app, QtCore.SIGNAL("lastWindowClosed()"),
app, QtCore.SLOT("quit()"))
app.exec_()
Я использовал Eclipse и QTDesigner для создания файла .ui(щелкните правой кнопкой мыши по модулю, "Создать → Другое..", выберите "Qt Designer → Qt Designer Form" ). Нет явного вызова uic.
Ответ 3
import pysideuic
import xml.etree.ElementTree as xml
from cStringIO import StringIO
def loadUiType(uiFile):
"""
Pyside "loadUiType" command like PyQt4 has one, so we have to convert the
ui file to py code in-memory first and then execute it in a special frame
to retrieve the form_class.
"""
parsed = xml.parse(uiFile)
widget_class = parsed.find('widget').get('class')
form_class = parsed.find('class').text
with open(uiFile, 'r') as f:
o = StringIO()
frame = {}
pysideuic.compileUi(f, o, indent=0)
pyc = compile(o.getvalue(), '<string>', 'exec')
exec pyc in frame
# Fetch the base_class and form class based on their type
# in the xml from designer
form_class = frame['Ui_%s'%form_class]
base_class = eval('QtGui.%s'%widget_class)
return form_class, base_class
Вы можете использовать этот способ для загрузки пользовательского интерфейса и также можете получить form_class, а также базовый класс в качестве типа возврата... но если вы не хотите конвертировать, в противном случае Да, это правильный путь.
pyside-uic.exe MyWindow.ui -o MyWindow.py
Ответ 4
pyside-uic.exe MyWindow.ui -o MyWindow.py
- это то, что я делал, и он отлично работает (насколько я знаю)
Ответ 5
Класс QUiLoader выполнит задание без промежуточного файла.
http://www.pyside.org/docs/pyside/PySide/QtUiTools/QUiLoader.html
Ответ 6
Прочитайте документацию. В этом конкретном случае http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/pyqt4ref.html#pyuic4:
The pyuic4 utility is a command line interface to the uic module. The command has the following syntax:
pyuic4 [options] .ui-file
The full set of command line options is:
-h, --help A help message is written to stdout.
--version The version number is written to stdout.
-i N, --indent=N
The Python code is generated using an indentation of N spaces. If N is 0 then a tab is used. The default is 4.
-o FILE, --output=FILE
The Python code generated is written to the file FILE.
-p, --preview The GUI is created dynamically and displayed. No Python code is generated.
-w, --pyqt3-wrapper
The generated Python code includes a small wrapper that allows the GUI to be used in the same way as it is used in PyQt v3.
-x, --execute The generated Python code includes a small amount of additional code that creates and displays the GUI when it is executes as a standalone application.
--from-imports Resource modules are imported using from . import rather than a simple import.
Ответ 7
Использование QtUiTools (как предлагается в другом ответе) в настоящее время не рекомендуется команде PySide.
Прочтите полную информацию здесь: https://groups.google.com/forum/?fromgroups=#!topic/pyside/_s1HPe6XTZs
Ответ 8
Посмотрите на C:\Python27\Lib\site-packages\PySide\scripts\uic.py(или там, где вы установили python). Если вы посмотрите на script, вы можете увидеть параметры, помеченные и описанные как на странице руководства (что я не знаю, как правильно смотреть на окна. Советы оценены.) Здесь http://manpages.ubuntu.com/manpages/precise/man1/pyside-uic.1.html
Я немного смутился, пытаясь взглянуть на C:\Python27\Lib\site-packages\pysideuic\pyside-uic.1, поскольку я думал, что это должен быть файл, который вызывается. Даже попытка взглянуть на это как на страницу руководства невозможна для меня из-за всех лишних символов. Вы не можете изучить синтаксис, пытаясь угадать, какие символы являются дополнительными, а какие нет!
В Windows вы можете автоматизировать это с помощью командного файла, конечно, сохраняя текстовый файл с указанной выше строкой (ниже для справки) с расширением .bat, например uic_generator.bat.
pyside-uic MyWindow.ui -o MyWindow.py