質問

I'm writing a PyQt application that shall feature multiple windows. Right now, I am interested in having one of two windows open at a time (so a click of a button in one window causes a switch to the other window). What is a reasonable way of keeping track of multiple windows in a PyQt application? My initial attempt, as shown below, essentially stores instances of the QtGui.QWidget in data members of a global instance of a simple class.

I'm new to PyQt. Is there a better way to approach this?

#!/usr/bin/env python

import sys
from PyQt4 import QtGui

class Program(object):
    def __init__(
        self,
        parent = None
        ):
        self.interface = Interface1()

class Interface1(QtGui.QWidget):
    def __init__(
        self,
        parent = None
        ):
        super(Interface1, self).__init__(parent)

        self.button1 = QtGui.QPushButton(self)
        self.button1.setText("button")
        self.button1.clicked.connect(self.clickedButton1)

        self.layout = QtGui.QHBoxLayout(self)
        self.layout.addWidget(self.button1)

        self.setGeometry(0, 0, 350, 100)
        self.setWindowTitle('interface 1')
        self.show()

    def clickedButton1(self):
        self.close()
        program.interface = Interface2()

class Interface2(QtGui.QWidget):
    def __init__(
        self,
        parent = None
        ):
        super(Interface2, self).__init__(parent)

        self.button1 = QtGui.QPushButton(self)
        self.button1.setText("button")
        self.button1.clicked.connect(self.clickedButton1)

        self.layout = QtGui.QHBoxLayout(self)
        self.layout.addWidget(self.button1)

        self.setGeometry(0, 0, 350, 100)
        self.setWindowTitle('interface 2')
        self.show()

    def clickedButton1(self):
        self.close()
        program.interface = Interface1()

def main():
    application = QtGui.QApplication(sys.argv)
    application.setApplicationName('application')
    global program
    program = Program()
    sys.exit(application.exec_())

if __name__ == "__main__":
    main()
役に立ちましたか?

解決

Have a single main window with a QStackedWidget to hold the different interfaces. Then use QStackedWidget.setCurrentIndex to switch between the interfaces.

Also, try to avoid using global references. If you want GUI components to communicate with each other, use signals and slots. You can easily define your own custom signals if there are no suitable built-in ones.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top