Python setParent显示QWidget而不显示布局的PyQt5行为

Python setParent显示QWidget而不显示布局的PyQt5行为,python,pyqt5,Python,Pyqt5,使用PyQt5的矿山小项目出现了一个小问题。我尝试将随机QWidget(在本例中为QPushbutton)添加到自定义QWidget。但是,我不理解“setParent”函数的行为。当我在自定义QWidget之外使用它时,会显示QPushButton。当我在自定义小部件的声明函数中使用它时,QPushButton被阻塞,除了添加布局(我不希望)之外,我没有机会显示它。下面是源代码的示例: from PyQt5.QtWidgets import * from PyQt5.QtGui import

使用PyQt5的矿山小项目出现了一个小问题。我尝试将随机QWidget(在本例中为QPushbutton)添加到自定义QWidget。但是,我不理解“setParent”函数的行为。当我在自定义QWidget之外使用它时,会显示QPushButton。当我在自定义小部件的声明函数中使用它时,QPushButton被阻塞,除了添加布局(我不希望)之外,我没有机会显示它。下面是源代码的示例:

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

class customWidget(QWidget):

    def __init__(self):
        super().__init__()
        self.addButton()

    def addButton(self):

        button = QPushButton('not_showing')
        button.setParent(self)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = QWidget()

    button = QPushButton('showing')
    button.setParent(w)

    button.move(50,50)
    w.resize(600,600)
    w.move(1000,300)
    w.setWindowTitle('Simple')
    w.show()

    sys.exit(app.exec_())

在QPushButton初始化期间添加父级时,没有任何更改。

当函数addButton退出时,按钮被删除

如果要查看按钮,请尝试以下操作:

class customWidget(QWidget):

def __init__(self):
    super().__init__()
    self.addButton()
    self.button = None

def addButton(self):
    if self.button is None:
       self.button = QPushButton('not_showing')
       self.button.setParent(self)
主函数中没有此问题,因为此函数在应用程序停止之前不会返回

编辑:评论是对的,但你也遗漏了一些论点。这会奏效的

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
import sys

class customWidget(QWidget):

    def __init__(self, parent=None):
        super(customWidget, self).__init__(parent)
        self.addButton()

    def addButton(self):
        button = QPushButton('not_showing')
        button.setParent(self)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = customWidget()

    button = QPushButton('showing')
    button.setParent(w)

    button.move(50,50)
    w.resize(600,600)
    w.move(1000,300)
    w.setWindowTitle('Simple')
    w.show()

    sys.exit(app.exec_())

您的示例很有效,因为我在main中创建了一个customWidget对象,您可以在使用customWidget的地方发布您尝试的代码。不创建对象的类永远不会被调用这是错误的。该按钮将不会被删除,因为它具有父级。无需为其创建属性。OPs代码可以与
w=customWidget()
而不是
w=QWidget()
配合使用。谢谢,您的编辑成功了!在将来实现init时,我必须更加小心。