简体   繁体   中英

Why is this QLabel showing?

When I run the following code, the label widget (?) shows even though it hasn't been added to any layout. The textbook I'm following also implies I shouldn't be seeing it (until I add it to a layout), but it's appearing anyway. I was expecting to see an empty window. Any thoughts?

import sys
from PyQt5 import QtWidgets as qtw
from PyQt5 import QtGui as qtg
from PyQt5 import QtCore as qtc

class MainWindow(qtw.QWidget):

    def __init__(self):
        """MainWindow constructor"""
        super().__init__(windowTitle='Hello world')

        # QWidget
        subwidget = qtw.QWidget(self, toolTip='This is my widget')
        subwidget.setToolTip('This is YOUR widget')
        print(subwidget.toolTip())

        # QLabel
        label = qtw.QLabel('<b>Hello Widgets!</b>', self, margin=10)

        self.show()

if __name__ == '__main__':
    app = qtw.QApplication(sys.argv)
    mw = MainWindow()
    sys.exit(app.exec())

What you expect is incorrect, I will not point out anything about the book since you do not indicate what book it is or indicate the quotation where it indicates that you are probably misinterpreting what the author points out.


A widget is shown as part of another widget if the first is the child of the second or the child of a widget that is already displayed in the widget.

In your example when passing "self" you are pointing out that the QLabel are children of the window:

print(subwidget.parentWidget())
print(label.parentWidget())

Output:

<__main__.MainWindow object at 0x7f10757a4dc0>
<__main__.MainWindow object at 0x7f10757a4dc0>

So if it is valid they are shown.

So why are widgets that are set in a layout displayed if they are not set to a parent? Well, when a layout is established internally it establishes that the parent of the widget is the widget where the layout was established

class MainWindow(qtw.QWidget):
    def __init__(self):
        super().__init__(windowTitle="Hello world")

        btn1 = qtw.QPushButton("btn1")
        btn2 = qtw.QPushButton("btn2")

        lay = qtw.QVBoxLayout(self)
        lay.addWidget(btn1)
        lay.addWidget(btn2)

        print(btn1.parentWidget())
        print(btn2.parentWidget())

Output:

<__main__.MainWindow object at 0x7faf9ced2e50>
<__main__.MainWindow object at 0x7faf9ced2e50>

In conclusion:

A widget will be displayed as part of another widget if the former is the child of the latter. There are exceptional cases such as hiding the widget, it is established that the child widget is a popup.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM