How to properly set parent of a widget in Pyqt?

旧巷老猫 提交于 2020-07-21 04:22:06

问题


I have the following code

from PyQt5 import QtCore, QtGui, QtWidgets
from mw import Ui_MainWindow as mwin
from wd import Ui_Form as wdg

class widget(QtWidgets.QWidget):
    def __init__(self,parent = None):
            super(widget,self).__init__(parent)
            self.ui = wdg()
            self.ui.setupUi(self)
            self.show()

class Main(QtWidgets.QMainWindow):
    def __init__(self,parent = None):
        super(Main,self).__init__(parent)
        self.ui = mwin()
        self.ui.setupUi(self)
        self.show()
        w = widget(self)
import sys
if __name__ == '__main__':
        app = QtWidgets.QApplication(sys.argv)
        mn = Main()
        sys.exit(app.exec_())

The Ui is generated by qt designer and is imported from another file.

When I run the code, both the Main window and widget are merged together and a segmentation fault occurs when I close the Main window.

When I set the parent in the widget as None the problem goes but the widget has no parent.

I am unable to understand what is wrong and how to correctly set the Main window as the parent of the widget ?


回答1:


This is probably not the correct way but works.

Workaround:

class widget(QtWidgets.QWidget):
    def __init__(self,parent = None):
        super(widget,self).__init__()
        self.ui = wdg()
        self.ui.setupUi(self)

        self.parent = parent

        self.show()


class Main(QtWidgets.QMainWindow):
    def __init__(self,parent = None):
    super(Main,self).__init__(parent)
    self.ui = mwin()
    self.ui.setupUi(self)
    self.show()
    w = widget(self)

then use self.parent



来源:https://stackoverflow.com/questions/41831787/how-to-properly-set-parent-of-a-widget-in-pyqt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!