如何在单击另一个小部件的按钮时显示一个小部件

How to show a widget on button click of another widget

我的问题很简单,我想在主window中打开一个childwindow。我得到了所有答案的帮助,所以这个问题不是重复的。我的childwindow来了一段时间就自动消失了

import random
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5 import QtWidgets, uic


class SubWindow(QWidget):
    def __init__(self, parent = None):
        super(SubWindow, self).__init__(parent)
        label = QLabel("Sub Window",  self)
        label.setGeometry(0, 0, 20, 10)
        self.show()


class pro(QWidget):
    def __init__(self, parent=None):
        super(pro, self).__init__(parent)


        self.acceptDrops()

        self.x = 200
        self.y = 200
        self.width = 800
        self.length = 800

        self.setGeometry(self.x, self.y, self.width, self.length)
        self.setWindowTitle("PA")

        label = QLabel(self)
        pixmap = QPixmap('p_bg.png')
        label.setPixmap(pixmap)
        label.setGeometry(0, 0, 1100, 1000)

        self.initgui()

    def register_system(self):
        opener = SubWindow()
        opener.show()

    def initgui(self):

        self.btn_log = QPushButton(self)
        self.btn_log.setGeometry(440, 250, 150, 30)
        self.btn_log.setText("         Login         ")
        self.btn_log.adjustSize()

        self.btn_sign = QPushButton(self)
        self.btn_sign.setGeometry(440, 300, 150, 30)
        self.btn_sign.setText("       Register       ")
        self.btn_sign.adjustSize()
        self.btn_sign.clicked.connect(self.register_system)

        self.welcome = QLabel("Arial font", self)
        self.welcome.setText("Welcome")
        self.welcome.setGeometry(410, 100, 200, 30)
        self.welcome.setStyleSheet("background-color:transparent;")
        self.welcome.setFont(QFont("Arial", 30))

        self.show()

def window():

    apk = QApplication(sys.argv)
    win = pro()

    win.show()
    sys.exit(apk.exec_())
window()

我从这里帮助制作了一个 child window:https://www.codersarts.com/post/multiple-windows-in-pyqt5-codersarts ,我在我的案例中使用了类型 2 资源。

原因可能是变量 opener 仅在 register_system 方法内有效;它在方法退出后被删除,您可以修改代码以使用 self 创建变量作为 class 对象的属性,然后像这样显示小部件:

    def register_system(self):
        self.opener = SubWindow()
        self.opener.show()

或者,您可以只在全局范围内创建一个变量 opener,然后使用全局变量来分配和显示小部件:

# imports
opener = None
class SubWindow(QWidget):
    def __init__(self, parent = None):
    
    #Rest of the code

class pro(QWidget):
    def __init__(self, parent=None):
    # Rest of the code

    def register_system(self):
        global opener
        opener = SubWindow()
        opener.show()

    # Rest of the code

附带说明一下,您应该始终在 PyQt 应用程序中为小部件使用布局,您可以查看 Layout Management