在 PYQT 中处理多个 windows

Handling multiple windows in PYQT

我的 PYQT4 GUI 变得非常冗长,所以我将页面拆分为每个页面的 .py 文件。

我正在尝试使用按钮遍历页面,但现在无法正常工作:)

这是我目前的情况:

mainwindow.py

import windowConvertor


        self.button2 = QtGui.QPushButton('Convertor Page', self)
        self.button2.clicked.connect(self.pageTwo)

    def pageTwo(self):

        self.hide()
        pagetwo = windowConvertor.convertorPage
        pagetwo.show(self)

windowconvertor.py

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

        self.initUI()

    def initUI(self):

        print "YOU MADE IT!!"

看来您不了解classes、对象、实例化以及self是什么。

这些行是完全错误的:

pagetwo = windowConvertor.convertorPage
pagetwo.show(self)

此代码获取对 convertorPage class 的引用,并将对它的引用存储在 pagetwo 中。然后调用 pagetwo.show,它调用 convertorPage class 中的函数 show 并将第一页对象的引用传递给它(selfpageTwo 方法,大概驻留在第一页的 class 中)。

相反,您应该使用 convertorPage class 实例化:

pagetwo = windowConvertor.convertorPage()

这将创建一个 convertorPage 类型的对象并将其存储在 pagetwo 中。 然后您可以在此对象上调用 show:

pagetwo.show()

注意:调用对象的方法时,对象的引用作为第一个参数隐式传递。无需明确指定。

最后的笔记:

  • 请阅读面向对象编程(和面向对象的 GUI)。您的代码表明您还没有完全掌握这一点,您需要全神贯注才能有效地使用 PyQt 进行编程。

  • 您的代码还有一个问题。您没有存储对新 window (pagetwo) 的引用,当 pageTwo 方法完成 运行 时,它将被垃圾回收。您需要通过将其存储为实例属性 (self.pagetwo = ...) 或在实例化 convertorPage.

  • 时传入一个总体父小部件来解决此问题