Я изучал недавно разработку Qt с PySide, однако я не могу пройти через одну вещь. Я хочу загрузить ui не непосредственно в init, а в собственный метод init_ui (только для научных целей). Но независимо от того, что я буду делать, я не могу заставить его работать при вызове show()
из функции __main__
. Like in example here.PySide: Невозможно использовать метод show() за пределами __init__ для правильного отображения окна
Должно работать, но это не так: отображается
mw = MainWindow()
# this displays empty window
mw.show()
Однако правильное окно при вызове непосредственно из __init__
:
def __init__(self):
super(MainWindow, self).__init__()
# this shows proper
self.show()
self.init_ui()
self.load_widgets()
Вот весь код:
from PySide import QtCore,QtGui
from PySide import QtUiTools
import os, sys
def load_ui(file_name, where=None):
"""
Loads a .UI file into the corresponding Qt Python object
:param file_name: UI file path
:param where: Use this parameter to load the UI into an existing class (i.e. to override methods)
:return: loaded UI
"""
# Create a QtLoader
loader = QtUiTools.QUiLoader()
# Open the UI file
ui_file = QtCore.QFile(file_name)
ui_file.open(QtCore.QFile.ReadOnly)
# Load the contents of the file
ui = loader.load(ui_file, where)
# Close the file
ui_file.close()
return ui
class MainWindow(QtGui.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
# this shows proper
self.show()
self.init_ui()
self.load_widgets()
def init_ui(self):
"""
init ui
:return:
"""
ui_file_path = os.path.join(os.path.realpath(os.path.dirname(__file__)), 'window.ui')
print ui_file_path
# it returns ui but I have no idea what to do with it
# main_widget = load_ui(ui_file_path, self)
load_ui(ui_file_path, self)
# return main_widget
def load_widgets(self):
"""
here configuring rest of widgets
:return:
"""
export_path_button = self.findChild(QtGui.QPushButton, 'export_path_button')
export_path_button.clicked.connect(self.on_export_path_button_clicked)
def on_export_path_button_clicked(self):
"""
test if works
:return:
"""
print "clicked!"
filename = QtGui.QFileDialog.getSaveFileName(parent=self, caption='Select output file', dir='.')
if filename:
print filename
def main():
app = QtGui.QApplication(sys.argv)
mw = MainWindow()
# this displays empty window
mw.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Думаю, что я понял. Мне также необходимо переопределить метод createWidget из QUiLoader. – pokyfudywise