gpt4 book ai didi

qt - 在 QML 中动态创建按钮

转载 作者:行者123 更新时间:2023-12-04 16:49:59 32 4
gpt4 key购买 nike

使用 qt 5.2,我正在尝试动态添加一个像这样的简单按钮:

ApplicationWindow
{
id: appWindow

width: 640
height: 420
minimumHeight: 400
minimumWidth: 600

function addButton() {

var obj = Qt.createComponent("Button.qml");

if (obj.status == obj.Ready)
{
var button = obj.createObject(appWindow);
button.color = "red";
button.width=50;
button.height=80;
button.x=50; button.y=50;
}
}


Button {
anchors.centerIn: parent;
text: "ok";

onClicked: {
addButton();
}
} ...

但是在 createComponent 之后我总是得到:

QQmlComponent: Component is not ready

怎么了?

最佳答案

要确保组件准备就绪,最好的方法是简单地在 QML 部分内声明它,在组件对象内,以便它与文件的其余部分同时预加载:

ApplicationWindow {
id: appWindow;

Component {
id: myButton;

Button { }
}

function addButton () {
var button = myButton.createObject (appWindow, {
"color" : "red",
"width" : 50,
"height" : 80,
"x" : 50,
"y" : 50
});
}

...
}

如您所见,我还冒昧地向您展示了直接一次性创建具有良好属性的对象的语法,而不是用老式的方式手动设置它们。代码更简洁,性能可能更高。

关于qt - 在 QML 中动态创建按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21352929/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com