如何正确运行pyqt5应用程序?

时间:2018-09-10 14:48:51

标签: python pyqt pyqt5 qt-designer

我无法以我需要的方式来运行应用程序的GUI。我的问题是,考虑到以下条件,我该如何正确设置和运行GUI。我发现缺少好的文档会令人发疯(可能是我在错误的地方找东西?)。

我在一个名为MainCustomerWindow.py的文件中有一个主窗口,其中包含一个具有相同名称的类。这是qt设计器中所有代码的所在。我有另一个名为GUIController的类文件。 GUIController类正是这样做的,它控制着多个GUI窗口。我试图在此GUIController类中实例化并运行MainCustomerWindow。这是我一直在尝试的代码。

def setup_window(self):
    APP = QtWidgets.QApplication(sys.argv)
    Window = MainCustomerWindow()
    Window.setupUi(QtWidgets.QMainWindow)
    Window.show()
    sys.exit(APP.exec_())

作为一个补充说明,我来自JavaFX和Swing,但并不完全了解pyqt5的工作流程。因此,如果有人也可以对此添加解释,将不胜感激。

2 个答案:

答案 0 :(得分:0)

由Qt Designer生成的类不是窗口小部件,它是用于填充现有窗口小部件的类,因此您必须在窗口中创建一个对象,假设您已使用“主窗口”模板,则该窗口小部件必须为import React from 'react'; import { mount } from 'enzyme'; import { Provider } from 'react-redux'; import configureStore from 'redux-mock-store'; import TodoList from '../../../../react/components/todo/TodoList'; describe('TodoList component', () => { //global arrange const storeState = { todos: [ { id: 'testId1', title: 'testTitle1', description: 'testDescription1' }, { id: 'testId2', title: 'testTitle2', description: 'testDescription2' }, ] }; const mockStore = configureStore(); let store; beforeEach(() => { store = mockStore(storeState) }); it('Removes a todo from the list if the remove button the todo was pressed', () => { //arrange //let mockFn = jest.fn(); //TodoList.prototype.onRemoveClick = mockFn; => tried, doesn't work... const component = mount( <Provider store={store}> <TodoList /> </Provider> ); //component.instance() => tried working with this, but couldn't find it //component.instance().children() => is not the TodoList const items = component.find('.todoItem'); //act const button = items.first().find('button'); button.simulate('click'); //assert //Todo: check function spy here }); }); (如果是另一个QMainWindowQDialog),则必须创建属于设计的另一个类,并使用方法QWidget您必须传递小部件来填充它:

setupUi()

尽管更好的选择是创建一个新类并使其从这两个类继承:

def setup_window(self):
    app = QtWidgets.QApplication(sys.argv)
    # create window
    window = QtWidgets.QMainWindow()

    ui = MainCustomerWindow()
    # fill window
    ui.setupUi(window)

    window.show()

    sys.exit(app.exec_())

如果您想获取详细信息,我建议您阅读以下内容:

答案 1 :(得分:0)

您可以尝试获取那里的代码,并将其添加到应用程序脚本末尾的main语句中。您还可以让该语句实例化您的类,其中init方法包含setupui()调用。例如:

if __name__ == '__main__':
    app = QWidgets.QApplication(sys.argv)
    window = QMainWindow()
    main_window = MainCustomerWindow()

    window.show()
    sys.exit(app.exec())

此代码首先将PyQt应用设置为QApplication的实例。接下来,它实例化QMainWindow的实例,以便PyQt知道在主应用程序启动时显示的内容。根据我的经验,我将setupui()放在了应用类的init方法中。对于您的情况,在MainCustomerWindow的init方法中,最后,window.show()告诉PyQt开始渲染主窗口。