PySide6 QWidget Doesn't Automatically Create Window?
-
I've been slowly working through the PySide6 tutorials at https://www.pythonguis.com/tutorials/pyside6-creating-multiple-windows/. The following code example should, when the button in MainWindow is clicked, open up a second window with a simple label: "Another Window " and a random integer. The main window and button show up, and the second window does when the button is clicked -- but the label doesn't. Why not?
(I tried deleting the space between the percent symbol (%) and d in the string passed to QLabel, but that didn't seem to fix things. Any insight you can lend would be appreciated. Thank you for your time.)
from PySide6.QtWidgets import (QApplication, QMainWindow, QPushButton, QLabel, QVBoxLayout, QWidget) from random import randint import sys class AnotherWindow(QWidget): """ This "window" is a QWidget. If it has no parent, it will appear as a free-floating window as we want. """ def __init___(self): super().__init__() layout = QVBoxLayout() self.label = QLabel("Another Window % d" % randint(0, 100)) layout.addWidget(self.label) self.setLayout(layout) class MainWindow(QMainWindow): def __init__(self): super().__init__() self.w = None # No external window yet. self.button = QPushButton("Push for Window") self.button.clicked.connect(self.show_new_window) self.setCentralWidget(self.button) def show_new_window(self, checked): if self.w is None: self.w = AnotherWindow() self.w.show() else: self.w.close() # Close window. self.w = None # Discard reference, close window. app = QApplication(sys.argv) w = MainWindow() w.show() app.exec()
-
@go4tli
Indeed, it was very well spotted by @SGaist, I don't think I would have noticed it!Python could do with an
override
keyword to catch this, which it lacks. If you are interested for the future In Python, how do I indicate I'm overriding a method? or https://pypi.org/project/overrides/ suggest some code snippets which would catch such a mistake.... -