I'm creating a programm using Python and PyQt5. This is the first time I used PyQt.
Actually, when you launch the programm, the main window appears. The user can then choose between two option, showed by two button.
When the user choose an option by clicking a button, a new child window opens and user have to complete some fields in it.
My problem is that my child window closes every time right after opening.
Here is my code :
main.py
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QGridLayout, QFormLayout, QGroupBox, QLabel, QLineEdit, \
QComboBox, QTextEdit, QPushButton, QTreeView, QMenuBar, QMainWindow
from PyQt5.QtGui import QStandardItemModel
from scelle_window import ScelleWindow
from oe_window import OeWindow
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('''Main Window''')
self.resize(800, 500)
main_widget = QWidget()
self.setCentralWidget(main_widget)
grid = QGridLayout()
bt_add_scelle = QPushButton('''Add objetc''')
bt_add_scelle.clicked.connect(self.add_scelle_dial)
bt_add_oe = QPushButton('''Add desc''')
bt_add_oe.clicked.connect(self.add_oe_dial)
grpbox_tree = QGroupBox('''List''')
layout_tree = QGridLayout()
layout_tree.addWidget(case_tree, 0, 0)
layout_tree.addWidget(bt_add_scelle, 1, 0)
layout_tree.addWidget(bt_add_oe, 2, 0)
grpbox_tree.setLayout(layout_tree)
grid.addWidget(grpbox_tree, 3, 0, 1, 2)
main_widget.setLayout(grid)
def add_scelle_dial(self):
desc_scelle = ScelleWindow()
desc_scelle.show()
def add_oe_dial(self):
desc_oe = OeWindow()
desc_oe.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
win = MainWindow()
win.show()
sys.exit(app.exec_())
scelle_window
from PyQt5.QtWidgets import QWidget, QFormLayout, QLabel, QLineEdit, QComboBox
class ScelleWindow(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle('''Object informations''')
self.resize(500, 300)
# ... following code...
oe_window
from PyQt5.QtWidgets import QWidget, QFormLayout, QLabel, QLineEdit, QComboBox
class OeWindow(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle('''Object description''')
self.resize(500, 300)
# ... following code...
Is this because of carbage collection or something else ?
Thanks
Yes, you need to keep a reference to your widgets. Making the widgets member variables will do the trick:
def add_scelle_dial(self):
self.desc_scelle = ScelleWindow()
self.desc_scelle.show()
def add_oe_dial(self):
self.desc_oe = OeWindow()
self.desc_oe.show()