Unsolved Depending on the user input, create some sliders, rectangles etc.
-
Hey there,
I am beginner to Qt Quick. I am wondering, is it possible to create custom number of sliders, rectangles, dials etc. depending on the user input. For example, when user writes 5 in a text box, I want to create 5 sliders and let the user to place them in anywhere on the app screen. Thanks in advance.
-
Hi @fgfgfg
Have a look at dynamic object creation:
http://doc.qt.io/qt-5/qtqml-javascript-dynamicobjectcreation.htmlIn its simplest form, e.g. for
Rectangle
objects, you could have something like this:First, instantiate a component, either using the
Component
type as in the example below, or viaQt.createComponent()
as in the Qt doc.Component { id: rectComponent Rectangle { width: 200 height: 50 } }
Then, using JavaScript, you can create objects from the component, e.g. as follows:
onClicked: { for (var i=0; i<parseInt(textInput.text); ++i) { rectComponent.createObject(visualParent, {"x": 100, "y": i*300}) } }
where
visualParent
is the visual parent item under which you want to create the objects (e.g. the id of yourMainWindow
)As stated in the doc, it may be more efficient to pass object parameters (
x
andy
for example) directly in the call to `createObject()' rather than to set them after the object is created.Since you want move the objects around, you must enable drag & drop on your object.
I used this example to learn about drag/drop in QML:
http://doc.qt.io/qt-5/qtquick-draganddrop-example.html -
Hi @Diracsbracket
Thank you for your reply.Now, depending on the user input I am creating some objects. For example, when i=2, it creates 2 objects. i = 4, it creates 4 objects.
//main.qml Component.onCompleted: { button.clicked.connect (MyScript.createSpriteObjects) }
But when i=3 (less than the previous i), there is still 4 objects. I could not destroy the previous objects.
//JS File var component; var sprite; var i; function createSpriteObjects() { for (var i=0; i<parseInt(textField.text); i++){ component = Qt.createComponent("Sprite.qml"); sprite = component.createObject(appWindow, {"x": 400, "y": i*100}); } if (sprite === null) { // Error Handling console.log("Error creating object"); } }
Is there any way to do that instead of defining another button and sending signal to destroy function. Thanks in advance.
-
@fgfgfg
You need to keep track of the object you create, and when you no longer need them, i.e. just before creating your new batch of objects, you should destroy them.
http://doc.qt.io/qt-5/qtqml-javascript-dynamicobjectcreation.html#deleting-objects-dynamicallyAs to the question of how you keep track of those objects, you could e.g. store the objects in a list, or iterate over the
children
of the commonparent
object to find the objects and then invoke thedestroy()
method on each of these.Good luck!