How do i open a class from within another class by selecting an item on ToolBar?? Python/PyQt

StackOverflow https://stackoverflow.com/questions/23160290

  •  05-07-2023
  •  | 
  •  

質問

I am trying to run class AddTQuestions from a def in class AddTest but it wont work!! It opens the window AddTQuestions for a split-second then closes it straight away?!

The code is shown here:

import sys
from PyQt4 import QtCore, QtGui

class Example(QtGui.QMainWindow):
    def __init__(self):
        super(Example, self).__init__()
        self.initUI()
    def initUI(self):               
        RunClassAction = QtGui.QAction(QtGui.QIcon('exit24.png'), 'Exit', self)
        RunClassAction.triggered.connect(self.run)
        self.toolbar = self.addToolBar('Exit')
        self.toolbar.addAction(RunClassAction)
        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('Why Wont this Woooorkkkkk')    
        self.show()

    def run(self):
        AddQuestion = AddTQuestions()
        AddQuestion.show()

class AddTQuestions(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(AddTQuestions, self).__init__(parent)
        self.welldone = QtGui.QLabel('WellDone')
        self.button = QtGui.QPushButton('Press Me')
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.welldone)
        layout.addWidget(self.button)
        self.setLayout(layout)
        print("hello")


if __name__ == '__main__':
    app = QtGui.QApplication([])
    window = Example()
    window.show()
    app.exec_()
役に立ちましたか?

解決

The object get's garbage collected, since you don't hold any reference to it when the function ends.

add them as class variables like this and the window stays open.

self.AddQuestion = AddTQuestions()
self.AddQuestion.show()
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top