Communication between ui.qml, .qml and .py
-
I am new to QTCreator 16.0.2, Qt Design Studio 4.7 and Python 3.13.5. with PySide6.
I created a file called testMain.ui.qml with QT Design Studio (geometry settings only, javascript is rejected). I created another file main.qml to provide signals/javascript for some defined items in testMain.ui.qml (for buttons for example) and as a "connection" between .ui.qml and .py. The python file should then contain the associated slots to the signals in the backend.
My question now is: How can I introduce/initialise the items of testMain.ui.qml to/in main.qml so that I can set a onClicked() for e.g. a button there?
testMain.ui.qml and main.qml and mainprogram.py are located in the same directory.
The following does not work (Where are the faults?):testMain.ui.qml:
import QtQuick
import QtQuick.Controls
Rectangle {
id: myRectangle
width: 640
height: 480
visible: true
Button {
id: myButton
x: 200
y: 200
text: "Click me"
}
}main.qml: //here MyComponents.TestMain is wrong (unknown)
//have tried several workarounds with no success unfortunately
import QtQuick
import QtQuick.Window
import QtQuick.Controls
import "./" as MyComponents
Window {
width: 600
height: 400
visible: true
title: "Projekt Test"
signal buttonClicked()
MyComponents.TestMain {
id: testScreen
Connections {
target: testScreen.myButton
onClicked: {
qmllogger.hello()
buttonClicked()
}
}
}
}mainprogram.py:
import sys
from pathlib import Pathfrom PySide6.QtGui import QGuiApplication
from PySide6.QtQml import QQmlApplicationEngine
from PySide6.QtCore import QObject, Slotclass Logger(QObject):
@Slot()
def hello(self):
print("hello")if name == "main":
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
qml_file = Path(file).resolve().parent / "main.qml"
engine.load(qml_file)
logger=Logger()
engine.rootContext().setContextProperty("qmllogger", logger)if not engine.rootObjects(): sys.exit(-1) sys.exit(app.exec())
I would be grateful for any help. Thank you in advance.
-
Ir seems the @QmlElement decorator is missing (see
Tutorial , QmlElement and one example of the tutorial examples. -
It seems to me that the @QMLElement would be necessary to introduce new elements to QML.
My problem is the communication between the ui.qml (only geometry, rectangles, buttons) from Qt Design Studio and the .qml (events, signals for buttons, radiobuttons,...) e.g. from Qt Creator. I don't know how to refer/connect the objects in ui.qml to/with the associated events in .qml, I guess.
Button with id=button1 in ui.qml and on the other hand button1.onClicked in .qml, how can I address to button1 from ui.qml to qml?