Accessing TableView from second QML file with PySide2

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.


PyQt/PySide 1:1 Coaching with Martin Fitzpatrick — Save yourself time and frustration. Get one on one help with your Python GUI projects. Working together with you I'll identify issues and suggest fixes, from bugs and usability to architecture and maintainability.

Book Now 60 mins ($195)

Mark As Complete
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.