Nanobody
Nanobody

Reputation: 19

calling parent() from QWidget in PyQT results in NoneType

I have a custom widget class (in PyQT 5.9) as a child in a QMainWindow that needs to access variables and functions from the MainWindow. I'm settings it up with a test variable imaginatively called self.test. However when I use self.parent().test in the child class, I get and error:

File "D:/test.py", line 390, in mainWin = MainWindow()

File "D:/test.py", line 158, in init self.leftPane = FastaAnalysisWidget('left')

File "D:/test.py", line 26, in init print(self.parent().test)

AttributeError: 'NoneType' object has no attribute 'test'

This is the simplified child class:

class FastaAnalysisWidget(QWidget):
    def __init__(self, name, parent=None):
        super(FastaAnalysisWidget, self).__init__(parent)
        print(self.parent().test)

And this is the simplified parent MainWindow:

class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.test = 'blabla'
        self.leftPane = FastaAnalysisWidget('left')

The main looks like this:

app = QApplication(sys.argv)
mainWin = MainWindow()
mainWin.show()
sys.exit(app.exec_())

I'm quite new to PyQT and I didn't play around with parent-child relations in Python before starting PyQT. The code I use here for the init I have used successfully before with a QTabWidget where the tabs were separate classes. Am I missing something obvious?

Upvotes: 1

Views: 1934

Answers (1)

RunOrVeith
RunOrVeith

Reputation: 4805

When you create the FastaAnalysisWidget, you are omitting the parent argument, which defaults to None, so the code does exactly what you tell it to.

You need to initialize it like this in the MainWindowclass:

self.leftPane = FastaAnalysisWidget('left', parent=self)

Then, the parent correctly points to the MainWindow.

Upvotes: 2

Related Questions