I am fairly new to Qt/PyQt and currently struggling with some basic functionality. What I'm trying to do is, to dynamically load QML-Views (*.qml) files from python and replace specific content on the fly. For example a checkbox gets checked and part of my current view is replaced with another qml file. First I wanted to provide this logic via PyQt, but it seems a StackView is a better idea (multiple qml files in pyqt).
However, in this case I am not able to inject properties into my QML files. I am only able to inject a property into the rootContext. That however limits the usage of my QML-Views since I can only use one view (of the same type) at once. I would like to inject properties dynamically into QML-Views and make them only visible to this particular view. In this case I can use the same view more than once with more than one object in the back-end to catch the signals.
Here is my SimpleMainWindow.qml file (the main view:
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.3
import QtQuick.Controls 1.4
ApplicationWindow {
id: window
visible: true
width: 640
height: 480
title: qsTr("Hello World")
objectName : "WINDOW"
property ApplicationWindow appWindow : window
}
And here the file I try to load (TestViewButton.qml):
import QtQuick 2.9
import QtQuick.Controls 1.4
Button {
id: test
text: "test"
objectName : "Button"
onClicked: {
configurator.sum(1, 2)
configurator.info("TestOutput")
}
}
Python file loading QML-View (Component)
from PyQt5.QtCore import QObject, QUrl
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlApplicationEngine, QQmlComponent
if __name__ == "__main__":
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
engine.load("qml/SimpleMainWindow.qml")
engine.quit.connect(app.quit)
rootWindow = engine.rootObjects()[0].children()[0].parent()
# create component
component = QQmlComponent(engine)
component.loadUrl(QUrl("qml/TestViewButton.qml"))
configurator = SignalHandler()
component.setProperty("configurator", configurator)
itm = component.create()
itm.setParentItem(rootWindow.children()[0])
itm.setProperty("configurator", configurator)
app.exec_()
And the python object that I use to handle the signals from the view (SignalHandler.py):
from PyQt5.QtCore import QObject, pyqtSlot
class SignalHandler(QObject):
#pyqtSlot(int, int)
def sum(self, arg1, arg2):
print("Adding two numbers")
#pyqtSlot(str)
def info(self, arg1):
print("STR " + arg1)
The button loads fine (by the way, is there a better way to identify the parent I want to add my button to, wasn't having any look with findChild). What is not working is the component.setProperty.... part. If I set the property in the rootContext of the engine it works fine (the SignalHandler methods are called). Already checked similar topics (like Load a qml component from another qml file dynamically and access that component's qml type properties ...)
Is this possible, or am I getting something wrong here?
thanks
From what I understand, you want to load the configuration object only in TestViewButton.qml and it is not visible in SimpleMainWindow.qml.
To do this TestViewButton.qml must have its own QQmlContext when it is loaded and is not the rootContext().
To test my response and observe that behavior we will create a similar button that tries to use the configurator, if this is pressed it should throw an error noting that the property does not exist but if the button loaded is pressed by the QQmlComponent should do its job normally.
qml/SimpleMainWindow.qml
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.3
import QtQuick.Controls 1.4
ApplicationWindow {
id: window
visible: true
width: 640
color: "red"
height: 480
title: qsTr("Hello World")
Button {
x: 100
y: 100
text: "ApplicationWindow"
onClicked: {
console.log("ApplicationWindow")
configurator.sum(1, 2)
configurator.info("TestOutput")
}
}
}
As I commented previously I added the component with a new context:
if __name__ == "__main__":
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
configurator = SignalHandler()
engine.load("qml/SimpleMainWindow.qml")
engine.quit.connect(app.quit)
rootWindow = engine.rootObjects()[0]
content_item = rootWindow.property("contentItem")
context = QQmlContext(engine)
component = QQmlComponent(engine)
component.loadUrl(QUrl("qml/TestViewButton.qml"))
itm = component.create(context)
context.setContextProperty("configurator", configurator)
itm.setProperty("parent", content_item)
sys.exit(app.exec_())
At the end we get the following output:
qml: Component
Adding two numbers
STR TestOutput
qml: ApplicationWindow
file:///xxx/qml/SimpleMainWindow.qml:20: ReferenceError: configurator is not defined
qml: Component
Adding two numbers
STR TestOutput
qml: ApplicationWindow
file:///xxx/qml/SimpleMainWindow.qml:20: ReferenceError: configurator is not defined
Where we observe the desired behavior. The complete example can be found in the following link.
Related
I am trying to create a circular guage using Qml in Python as a QQuickWidget.
I am unable to do so as I receive the Error CircularGauge.qml:18:9: NumberAnimation is not a type
I am working on windows, where I have added C:\Qt\Tools\QtCreator\bin\qml to my path.
I have copied CircularGauge.qml exactly as is from example found on the Qt site doc.qt.io
to solve this issue I tried adding import QtQuick 2.0 to the CircularGauge.qml file, but then I receive the error CircularGauge is instantiated recursively
My python code is as follows:
import sys
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout
from PySide6.QtQuick import QQuickView, QQuickWindow, QSGRendererInterface
from PySide6.QtQuickWidgets import QQuickWidget
if __name__ == '__main__':
app = QApplication()
QQuickWindow.setGraphicsApi(QSGRendererInterface.OpenGL)
widget = QQuickWidget()
widget.setSource('CircularGauge.qml')
layout = QVBoxLayout(widget)
widget.show()
sys.exit(app.exec())
I have confirmed this works with other qml exampls,
for example if I replace widget.setSource('CircularGauge.qml') with widget.setSource('view.qml')
where view.qml is:
import QtQuick
Rectangle {
id: main
width: 200
height: 200
color: "green"
Text {
text: "Hello World"
anchors.centerIn: main
}
}
I get the desired result of a qml file loaded into a QQuickWidget
How can I load the CircularGauge in the same way?
I have a qt quick pyside application .I had a question before,but now another proplem is there .Just a empty window appears and then in application window I see below message.Although I have another qt quick application that I written that in c++ and there is no problem displaying it, this message is displayed!,This application is in python(pyside6)
I use Qt 6.0.2,Python 3.9.2,Qt Creator 4.14.1 and Pyside6
Failed to create vertex shader: Error 0x80070057: The parameter is incorrect.
Failed to build graphics pipeline state
*main.qml
import QtQuick 2.15
import QtQuick.Window 2.15
import QtQuick.Controls 2.15
Window {
id:mainWindow
width: 1000
height: 580
visible: true
title: qsTr("JooyaTrader")
Rectangle{
width: 152
height: 62
anchors.fill: parent
color: "red"
}
}
main.py
import sys,os
from PySide6.QtGui import QGuiApplication
from PySide6.QtQml import QQmlApplicationEngine
import PySide6
if __name__ == "__main__":
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
engine.load(os.path.join(os.path.dirname(__file__), "main.qml"))
if not engine.rootObjects():
sys.exit(-1)
sys.exit(app.exec_())
The problem is caused because the backend that Qt Quick uses for rendering does not work for your case, either because there are missing libraries or the version is not according to what Qt expects. In that one solution is to set the QT_QUICK_BACKEND in "software" making the rendering do it Qt Quick 2D Renderer:
os.environ["QT_QUICK_BACKEND"] = "software"
app = QGuiApplication(sys.argv)
For more information read Scene Graph Adaptations.
The objective:
I'm writing a Gui front-end for a Matplotlib-based library for nested samples (pip install anesthetic if you want to have a look).
How I would go about it in C++: My previous experience with QML was a C++ program, where instead of going into QML to find a canvas to render to, I created a C++ object, registered it in QML's type system, and had it behave as a QtQuick controls widget. As far as I know this is the recommended way of doing things: have all the rendering be done in QML, and have all the business-end-logic in C++.
THe best approach and why I can't do it: This approach doesn't work here. AFAIK you can only implement custom QML using C++, and I need for the program to be pure-ish Python (for others to be able to maintain it) some JS is accessible and QML is pretty easy to understand and edit, so I had no objections (C++ was a hard no).
what I got working: I have a working implementation of what I want. It was all in one file. So, naturally I wanted to split the canvas to which I'm drawing to into a separate file: figure.qml. Trouble is, I can't seem to find the object by that name whenever it's loaded from a separate file (the next step is to use a Loader, because the Figure is quite clunky).
I have a two-file project with view.qml being the root, and a component in Figure.qml.
The trouble is, it only works if I load the thing with objectName: "component" in view.qml and not in Component.qml.
So how does one findChild in Pyside for an objectName that's in a different .qml file?
MWE:
main.py
import sys
from pathlib import Path
from matplotlib_backend_qtquick.backend_qtquickagg import FigureCanvasQtQuickAgg
from matplotlib_backend_qtquick.qt_compat import QtGui, QtQml, QtCore
def main():
app = QtGui.QGuiApplication(sys.argv)
engine = QtQml.QQmlApplicationEngine()
displayBridge = DisplayBridge()
context = engine.rootContext()
qmlFile = Path(Path.cwd(), Path(__file__).parent, "view.qml")
engine.load(QtCore.QUrl.fromLocalFile(str(qmlFile)))
win = engine.rootObjects()[0]
if win.findChild(QtCore.QObject, "figure"):
print('success') # This fails
app.exec_()
view.qml
import QtQuick.Controls 2.12
import QtQuick.Windows 2.12
ApplicationWindow{
Figure {
}
}
Figure.qml
import QtQuick.Controls 2.12
import QtQuick 2.12
Component{
Rectangle{
objectName: "figure"
}
}
Component is used to define a QML element, it does not instantiate it, therefore you cannot access the object. Creating a Figure.qml is equivalent to creating a Component, and you are creating a Component inside another Component.
The solution is not to use Component:
Figure.qml
import QtQuick.Controls 2.12
import QtQuick 2.12
Rectangle{
objectName: "figure"
}
But it is not recommended to use objectName since, for example, if you create multiple components, how will you identify which component it is? o If you create the object after a time T, or use Loader or Repeater you will not be able to apply that logic. Instead of them it is better to create a QObject that allows obtaining those objects:
from PySide2 import QtCore
import shiboken2
class ObjectManager(QtCore.QObject):
def __init__(self, parent=None):
super().__init__(parent)
self._qobjects = []
#property
def qobjects(self):
return self._qobjects
#QtCore.Slot(QtCore.QObject)
def add_qobject(self, obj):
if obj is not None:
obj.destroyed.connect(self._handle_destroyed)
self.qobjects.append(obj)
print(self.qobjects)
def _handle_destroyed(self):
self._qobjects = [o for o in self.qobjects if shiboken2.isValid(o)]
# ...
object_manager = ObjectManager()
context = engine.rootContext()
context.setContextProperty("object_manager", object_manager)
qmlFile = Path(Path.cwd(), Path(__file__).parent, "view.qml")
engine.load(QtCore.QUrl.fromLocalFile(str(qmlFile)))
# ...
import QtQuick.Controls 2.12
import QtQuick 2.12
Rectangle{
Component.onCompleted: object_manager.add_qobject(this)
}
I have a problem with Toolbar when I use the qml file with PyQt5. The result is not the seem : no background image when mouse is over, image no resize automatically.
I want to know if it's normal.
How can I do for have the same result with PyQt5
The result with qmlscene:
The result with Python:
Thanks you for your help.
File : _test.py
from PyQt5.QtCore import (
pyqtProperty,
pyqtSignal,
pyqtSlot,
QAbstractListModel,
QModelIndex,
QObject,
Qt,
QTimer,
)
from PyQt5.QtGui import QGuiApplication
from PyQt5.QtQml import QQmlApplicationEngine
from PyQt5.QtQuick import QQuickView
class MainWindow(QObject):
def __init__(self, parent=None):
super().__init__(parent)
if __name__ == "__main__":
import sys
app = QGuiApplication(sys.argv)
engine = QQmlApplicationEngine()
engine.quit.connect(app.quit)
main_window = MainWindow()
engine.load("_test.qml")
if not engine.rootObjects():
sys.exit(app.exec_())
sys.exit(app.exec())
File : _test.qml
import QtQuick 2.4
import QtQuick.Layouts 1.1
import QtQuick.Controls 1.3
import QtQuick.Controls.Styles 1.3
ApplicationWindow {
width: 500
height: 200
visible: true
ToolBar {
Layout.fillWidth: true
RowLayout {
anchors.fill: parent
ToolButton {
//width: parent.height
anchors.margins: 4
iconSource: "ico/abacus.png"
}
ToolButton {
width: parent.height
Image {
source: "ico/quitter.png"
anchors.fill: parent
anchors.margins: 4
}
}
ToolButton {
width: parent.height
iconSource: "ico/start.png"
anchors.margins: 4
}
ToolButton {
width: parent.height
Image {
source: "ico/stop.png"
anchors.fill: parent
anchors.margins: 4
}
}
}
}
}
Analyzing the source code of qmlscene and testing with the --apptype option I get the following:
qmlscene _test.qml --apptype gui
qmlscene _test.qml --apptype widgets
So analyzing the fundamental difference is that QApplicacion is being used and not QGuiApplication, so internally it should activate some flag that scales the icons.
Considering the above, the solution is:
from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQml import QQmlApplicationEngine
if __name__ == "__main__":
import os
import sys
app = QApplication(sys.argv)
engine = QQmlApplicationEngine()
current_dir = os.path.dirname(os.path.realpath(__file__))
file = os.path.join(current_dir, "_test.qml")
engine.load(QUrl.fromLocalFile(file))
if not engine.rootObjects():
sys.exit(-1)
sys.exit(app.exec_())
According to the docs of Qt Quick Controls 1:
Note: We are using QApplication and not QGuiApplication in this
example. Though you can use QGuiApplication instead, doing this will
eliminate platform-dependent styling. This is because it is relying on
the widget module to provide the native look and feel.
So it seems that the scaling of the icons is part of the style of the platform.
Each type of project requires a QXApplication:
Console application: You can use any of the 3 types of QXApplication, but using QCoreApplication is the most optimal since the other QXApplication require that they have a window system that in that case is an unnecessary requirement.
QML Application: It requires at least one QGuiApplication, but for certain ones such as the need to use the styles of each platform it is necessary to use QApplication.
Qt Widgets Application: A QApplication is necessary because QWidgets use the styles of each platform.
The fact that sizes change, is this a problem of QtQuick.Controls 1?
Yes, one of the main differences between QQC1 and QQC2 is that the first one is developed to support desktop platforms so you use the styles, unlike the second one that is designed for embedded systems where the main objective is performance. For more information read Differences with Qt Quick Controls 1
Conclusions:
If you want your GUI made with QML to respect the styles of your desktop platform then you must use QQC1 with QApplication.
If your goal is that the style of your application does not respect the style of the desktop in addition to wanting more performance you should use QQC2 with QGuiApplication.
I am using pyqt and I have the following directory structure:
root
----> apps/
----> ui/
I have a simple qml based application in the app folder as:
apps/testqt.py
from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import QApplication
from PyQt5.QtQuick import QQuickView, QQuickWindow
from PyQt5.QtQml import qmlRegisterType, QQmlApplicationEngine
import sys
app = QApplication(sys.argv)
engine = QQmlApplicationEngine('ui/window.qml')
topLevel = engine.rootObjects()[0]
win = QQuickWindow(topLevel)
win.show()
app.exec_()
ui/window.qml
The qml file defines the app window and uses a StackView as follows:
import QtQuick 2.0
import QtQuick.Window 2.1
import QtQuick.Layouts 1.1
import QtQuick.Controls 1.4
ApplicationWindow {
id: rootWindow
objectName: "window"
visible: true
width: 800
height: 480
title: "Window"
Component.onCompleted: {
setX(Screen.width / 2 - width / 2);
setY(Screen.height / 2 - height / 2);
}
property Component loginView: LoginView {}
StackView {
id: stackView
anchors.fill: parent
Component.onCompleted:
{
stackView.push(loginView)
}
}
}
This uses the LoginView component which is defined as:
apps/LoginView.qml
import QtQuick 2.0
import QtQuick.Window 2.1
import QtQuick.Layouts 1.1
import QtQuick.Controls 1.4
import QtQuick.Dialogs 1.0
ControlView {
ColumnLayout {
anchors.centerIn: parent
spacing: 25
width: 200
TextField {
id: username_fld
placeholderText: qsTr("User name")
Layout.fillWidth: true
}
TextField {
id: password_fld
placeholderText: qsTr("Password")
Layout.fillWidth: true
echoMode: TextInput.Password
}
RowLayout {
Button {
id: login_button
text: "Log In"
Layout.fillWidth: true
}
Button {
id: cancel_button
text: "Cancel"
Layout.fillWidth: true
}
}
}
}
Now when I use qmlscene, the view loads just fine. However, running python results in the application hanging while trying to load the QQmlApplicationEngine. I have a feeling it has something to do with the qml paths perhaps, so I included import ../ui into the window.qml imports but that did not change anything.
I am using Python 2.7 with Qt 5.6 in an Anaconda environment. Qt was installed from here: https://anaconda.org/anaconda/pyqt
Similarly i use multiple qml files along with multiple python files. When i access application it loads perfectly two qml files successfully but when stacked through third qml page, the application crashes. It throws segmentation fault.
I use Stackview to push and pop through QML pages, during debugging i found that it works when push and pop are done for just for two pages.
I have came across if i use Swipeview too. What i guess is that the engine that was created can be loaded with two stack QML files.