在 PySide 中创建相同 class 的另一个 window

Create another window of same class in PySide

我正在使用 PySide 创建一个小型 GUI 程序。我在创建另一个相同 class 的对象时遇到困难。我真正想做的是,当单击 MainWindow 上的按钮时,它应该创建另一个独立的 window 相同 class.

import sys 
from PySide import QtCore, QtGui 

class Sticky(QtGui.QMainWindow):
    def __init__(self,parent = None):
        QtGui.QMainWindow.__init__(self,parent)
        self.initUI()

    def initUI(self):
        ....
        self.addToolBarElements()
        ....
        self.show()

    def addToolBarElements(self):
        ....
        self.newwindow = QtGui.QAction(QtGui.QIcon(os.path.join(os.path.dirname(__file__),'icons/new.png')),"New Note",self)
        self.newwindow.setStatusTip("New")
        self.newwindow.triggered.connect(newwindow)

        self.toolBar.addAction(self.newwindow)

    def newwindow(self):
        #how to create new object of same class

def run():
    app = QtGui.QApplication(sys.argv)
    notes = Sticky()
    sys.exit(app.exec_()) 

这是我尝试过的:

我试过multiprocessing,但不是很懂。我尝试再次调用 运行() 方法,但它给出了错误。

不要调用同名的 2 个不同的元素,在你的例子中 self.newwindow 指的是 QAction 作为 class 的方法,避免它,那是一个类型错误容易犯但很难发现。

进入正题,你只需要创建一个 class 的新对象,但问题是垃圾收集器会清除它,要避免它有 2 个可能的选项,第一个是使新的 window 成为 class 的成员,或者将其存储在一个列表中,这是我选择的,因为我认为你想要多个 windows.

import sys 
import os

from PySide import QtCore, QtGui 

class Sticky(QtGui.QMainWindow):
    def __init__(self,parent = None):
        QtGui.QMainWindow.__init__(self,parent)
        self.others_windows = []
        self.initUI()

    def initUI(self):
        self.addToolBarElements()
        self.show()

    def addToolBarElements(self):
        self.toolBar = self.addToolBar("toolBar")
        self.newwindow = QtGui.QAction(QtGui.QIcon(os.path.join(os.path.dirname(__file__),'icons/new.png')), "New Note",self)
        self.newwindow.setStatusTip("New")
        self.newwindow.triggered.connect(self.on_newwindow)

        self.toolBar.addAction(self.newwindow)

    def on_newwindow(self):
        w = Sticky()
        w.show()
        self.others_windows.append(w)

def run():
    app = QtGui.QApplication(sys.argv)
    notes = Sticky()
    sys.exit(app.exec_()) 

run()