问题
Here's what I've in my QML:
import QtQuick 2.12
import QtQuick.Window 2.12
import QtQuick.Controls 2.5
import QtQuick.Layouts 1.3
Window {
visible: true
width: 640
height: 480
title: "Test Window"
ListView{
id: listView
width: parent.width
height: parent.height
model: testContext.List
interactive: false
delegate: ItemDelegate {
width: parent.width
leftPadding: 3
rightPadding: scroll.width
topPadding: 3
bottomPadding: 3
/*
padding: {
leftPadding: 3
rightPadding: scroll.width
topPadding: 3
bottomPadding: 3
}
padding:{
left: 3
right: scroll.width
top: 3
bottom: 3
}
*/
contentItem: RowLayout{
Text{ text: modelData.name }
Text{
text: modelData.isActive
Layout.alignment: Text.AlignLeft
}
Text{
text: modelData.age
Layout.alignment: Text.AlignRight
}
}
background: Rectangle{
width: parent.width - scroll.width + 5
color: hovered? "gray" : highlighted? "green" : modelData.isActive? "lightblue" : "white"
}
highlighted: ListView.isCurrentItem
onClicked: listView.currentIndex = index
}
ScrollBar.vertical: ScrollBar{id: scroll; width: 15}
}
}
The c++ code is almost same as this. All that I've changed is added one more boolean PROPERTY in AClass:
class AClass : public QObject
{
Q_OBJECT
PROPERTY(QString, name)
PROPERTY(int, age)
PROPERTY(bool, isActive)
};
and in the constructor of ViewModel's .cpp file (i.e. Test Class) added this a->setisActive(i % 2 == 0); line before adding it in PROPERTY named List.
First problem: why do I have to define left/right/top/bottomPadding separately? I've tried to define all 4 padding: {...} inside braces BUT none of those commented out part work.
Second problem: if I put that ListView in another QML file instead of main.qml I can replace onClicked: listView.currentIndex = index with onClicked: currentIndex = index, I don't have to give it an id and can load that in a loader with a button click without any error in output. Why is it necessary to give it an id if I put it in main.qml?
Third problem: the ListView looks like this:
the second column isn't aligned properly although I've Layout.alignment: Text.AlignLeft in that Text! I've tried by setting a fixed width for the first Text (i.e. modelData.name) BUT that doesn't work.
EDIT
I've added Layout.preferredWidth and Layout.alignment for all 3 Text:
contentItem: RowLayout{
Text{
id: nameText
text: modelData.name
Layout.preferredWidth: parent.width / 3
Layout.alignment: Text.AlignRight
}
Text{
text: modelData.isActive
Layout.preferredWidth: parent.width / 3
Layout.alignment: Text.AlignRight
}
Text{
text: modelData.age
Layout.preferredWidth: parent.width / 3
Layout.alignment: Text.AlignRight
}
}
Now all columns are left aligned instead of right:
Why it is so?
来源:https://stackoverflow.com/questions/62628691/few-questions-on-customizing-listview