i learning pyqt5 and trying to open a new window by click a button from another window. if there are not input() function it will close the open window immediately, so i put input() to keep the window open. the window will open for long, but then it has stopped working. Can some one help me ? Thank you
import sys
from PyQt5.QtWidgets import QApplication, QPushButton,QMainWindow,QWidget
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
class App1(QWidget):
def __init__(self):
super().__init__()
self.title = 'open window'
self.left = 60
self.top = 60
self.width = 320
self.height = 200
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.show()
m.getch()
input() '''here is the problem'''
class App(QMainWindow):
def __init__(self):
super().__init__()
self.title = 'PyQt5 button - pythonspot.com'
self.left = 200
self.top = 200
self.width = 320
self.height = 200
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
button = QPushButton('PyQt5 button', self)
button.setToolTip('This is an example button')
button.move(100, 70)
button.clicked.connect(self.on_click)
self.show()
@pyqtSlot()
def on_click(self):
app1 = QApplication(sys.argv)
ex1 = App1()
sys.exit(app1.exec_())
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
You need to save a reference to the window or it will be garbage collected when on_click()
finishes executing. The easiest way is to store it in App
through the use of self
@pyqtSlot()
def on_click(self):
self.ex1 = App1()
import sys
from PyQt5.QtWidgets import QApplication, QPushButton,QMainWindow,QWidget
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
class App1(QWidget):
def __init__(self):
super().__init__()
self.title = 'open window'
self.left = 60
self.top = 60
self.width = 320
self.height = 200
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.show()
input()
class App(QMainWindow):
def __init__(self):
super().__init__()
self.title = 'PyQt5 button - pythonspot.com'
self.left = 200
self.top = 200
self.width = 320
self.height = 200
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
button = QPushButton('PyQt5 button', self)
button.setToolTip('This is an example button')
button.move(100, 70)
button.clicked.connect(self.on_click)
self.show()
@pyqtSlot()
def on_click(self):
self.ex1 = App1()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.