且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 QML 中的同一事件之后创建/销毁动态对象?

更新时间:2023-01-31 22:49:31

首先,不需要使用两步创建对象的方法——只有当你从远程源加载组件时才需要,这就完成了异步.从本地存储加载组件时,您实际上并不需要它,当您的 Component 在源代码中内嵌时更是如此.

First of all, there is no need to use the two step object creation method - it is only necessary when you are loading components from remote sources, which is done asynchronously. You don't really need that for loading components from local storage, even less so when your Component is in-line in the source.

第二,由于多个信号连接的堆叠方式,当你按下你的按钮时,你执行的是第一个连接,也就是创建函数,它增加了更多的连接,所以它们在第一个连接之后执行,导致立即删除刚刚创建的对象.没有一种很好的方式可以说直到下一次才处理这些连接".您可以使用计时器来延迟连接,但除了笨拙之外,这也为错误打开了空间.

Second, due to the way multiple signal connections stack, when you press your button, you execute the first connection which is the creation function, which adds more connections, so they are executed after the first connection, which leads to the immediate deletion of the objects that were just created. There isn't a nice way to say "don't process those connections until next time". You could use a timer to delay the connections, but aside from clumsy, that also opens room for bugs.

你的设计很糟糕.相反,您应该选择简单而实用的东西.例如,有一个 property var images : [] - 一个 JS 数组,您可以在其中存储对现有图像的引用.因此,每次按下按钮时 - 删除现有图像(如果有),然后创建新图像并将它们推入阵列.您还可以通过这种方式节省连接和事件处理.

Your design is plain out bad. Instead you should go for something simple and functional. For example, have a property var images : [] - a JS array in which you store references to the existing images. So each time you press the button - delete the existing images if any, then create the new ones and push them into the array. You will also save on connections and event handling this way.