Accessing TableView from second QML file with PySide2

Heads up! You've already completed this tutorial.

Max92 | 2021-05-30 22:40:05 UTC | #1

I am having two different QML files. In the main.qml I am using a Loader to call another QML file (other.qml). The second file contains a TableView which I want to access with Python (main.py) by creating a class implementing QtCore.QAbstractTableModel. Unfortunately, I am not able to access activityTable with Python when loading the main.qml in main.py. Already, the assignment of the model in main.qml fails. How do I make this TableView accessable in Python?

main.qml

python
TableView {
    id: activityTable
    anchors.fill: parent
    columnSpacing: 1
    rowSpacing: 1
    clip: true

    model: ActivityTableModel {}

    delegate: Rectangle {
        implicitWidth: 100
        implicitHeight: 50
        Text {
            text: display
        }
    }
}

other.qml

python
Loader {
    id: pagesOther
    anchors.fill: parent
    source: Qt.resolvedUrl("pages/other.qml")
}

main.py

python
if __name__ == "__main__":
    app = QGuiApplication(sys.argv)
    engine = QQmlApplicationEngine()

    main = MainWindow()
    engine.rootContext().setContextProperty("backend", main)
    engine.load(os.path.join(os.path.dirname(__file__), "qml/main.qml"))

I am using QtCreator, QtQuick 2.15, PySide2 and Python 3.9.


Over 15,000 developers have bought Create GUI Applications with Python & Qt!
Create GUI Applications with Python & Qt6
Take a look

Downloadable ebook (PDF, ePub) & Complete Source code

Also available from Leanpub and Amazon Paperback

[[ discount.discount_pc ]]% OFF for the next [[ discount.duration ]] [[discount.description ]] with the code [[ discount.coupon_code ]]

Purchasing Power Parity

Developers in [[ country ]] get [[ discount.discount_pc ]]% OFF on all books & courses with code [[ discount.coupon_code ]]
Well done, you've finished this tutorial! Mark As Complete
[[ user.completed.length ]] completed [[ user.streak+1 ]] day streak
Martin Fitzpatrick

Accessing TableView from second QML file with PySide2 was written by Martin Fitzpatrick .

Martin Fitzpatrick has been developing Python/Qt apps for 8 years. Building desktop applications to make data-analysis tools more user-friendly, Python was the obvious choice. Starting with Tk, later moving to wxWidgets and finally adopting PyQt. Martin founded PythonGUIs to provide easy to follow GUI programming tutorials to the Python community. He has written a number of popular Python books on the subject.