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.


Create GUI Applications with Python & Qt5 by Martin Fitzpatrick — (PySide2 Edition) The hands-on guide to making apps with Python — Over 10,000 copies sold!

More info Get the book

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 https://www.martinfitzpatrick.com/browse/books/ on the subject.