我遇到了 aListView
和 simple的问题ListModel
;
import QtQuick 2.12
import QtQuick.Controls 2.12
ApplicationWindow
{
id: app
visible: true
width: 640
height: 480
property int bheight: 48
ListModel
{
id: jmodel
}
function dosomething1()
{
jmodel.clear();
jmodel.append({"atext":"hello"})
}
function dosomething2()
{
jmodel.clear();
jmodel.append({"atext":"hello","btext":"world"});
}
ListView
{
id: alist
width: parent.width
height: parent.height - bheight
model: jmodel
delegate: Item
{
width: app.width
height: 48
Row
{
spacing: 8
Text
{
text: model.atext || ""
}
Text
{
text: model.btext || ""
}
}
}
}
Row
{
height: bheight
anchors.top: alist.bottom
Button
{
// press "plan A" first and it will say "hello"
// press "plan B" after and it will remain "hello"
// pressing A & B will NOT toggle
text: "Plan A"
onClicked: dosomething1();
}
Button
{
// press "plan B" first and it will say "hello world"
// press "plan A" after and it will say "hello"
// pressing A & B will toggle
text: "Plan B"
onClicked: dosomething2();
}
}
}
我无法让它始终如一地工作。也许缺少一些简单的东西或者我不明白。
按“Plan A”会说“你好”,按“Plan B”后不会改变它。
但,
先按“Plan B”会说“hello world”,然后按“plan A”和“plan B”会在“hello world”和“hello”之间切换。
它不应该取决于首先按下哪个按钮,我每次都在清除模型。
我在 Qt5.12.3 和 5.9 上试过这个,没有任何变化。
更新
在@eyllanesc 回答之后,我更新了我的代码,而是为每次更新创建一个新模型。这可行,但我不知道我现在是否有内存泄漏。
这是我的代码:
import QtQuick 2.12
import QtQuick.Controls 2.12
ApplicationWindow
{
id: app
visible: true
width: 640
height: 480
property int bheight: 48
Component
{
id: jmodel
ListModel {}
}
function dosomething1()
{
var m = jmodel.createObject()
m.append({"atext":"hello"})
alist.model = m;
}
function dosomething2()
{
var m = jmodel.createObject()
m.append({"atext":"hello","btext":"world"});
alist.model = m;
}
ListView
{
id: alist
width: parent.width
height: parent.height - bheight
delegate: Item
{
width: app.width
height: 48
Row
{
spacing: 8
Text
{
text: model.atext || ""
}
Text
{
text: model.btext || ""
}
}
}
}
Row
{
height: bheight
anchors.top: alist.bottom
Button
{
text: "Plan A"
onClicked: dosomething1();
}
Button
{
text: "Plan B"
onClicked: dosomething2();
}
}
}