PySide:无法在__init__之外使用方法show()来正确显示窗口

时间:2017-02-20 18:38:20

标签: python qt pyqt pyside

我最近一直在研究PySide的Qt开发,但是我无法完成一件事。我想不是直接在init中加载ui而是在自己的init_ui方法中加载ui(仅用于科学目的)。但无论我做什么,我都无法在show()函数中调用__main__时使其工作。 Like in example here.

应该有效,但不是:

 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()

1 个答案:

答案 0 :(得分:0)

因为您必须在main()中调用show方法,而不是在__init__()方法中调用show方法。对不起我的英文