问题
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