在HTML中可以使用group制作选择选项:
<select>
<optgroup label="Swedish Cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
</optgroup>
<optgroup label="German Cars">
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</optgroup>
</select>
QTQuick(ComboBox)有可能吗?怎么样?
答案 0 :(得分:2)
使用默认的QtQuick控件(1.0或2.0)无法直接实现,您必须稍微更改控件。
然而,这并不太难:这是一个完整的例子。
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.2
Window {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
ComboBox {
id: control
width: 200
model: ListModel {
ListElement { textRole: "Swedish cars"; kind: "header" }
ListElement { textRole: "Saab"; kind: "element" }
ListElement { textRole: "Volvo"; kind: "element" }
ListElement { textRole: "German cars"; kind: "header" }
ListElement { textRole: "Mercedes"; kind: "element" }
ListElement { textRole: "Audi"; kind: "element" }
}
currentIndex: 2
delegate: ItemDelegate {
width: parent.width
contentItem: Text {
text: textRole
font.bold: kind == "header"
}
highlighted: control.highlightedIndex === index
MouseArea {
anchors.fill: parent
onClicked: {
if(kind == "element") {
control.currentIndex = index
control.popup.close()
}
}
}
}
contentItem: Text {
leftPadding: 5
rightPadding: control.indicator.width + control.spacing
text: control.model.get(control.currentIndex).textRole
font: control.font
horizontalAlignment: Text.AlignLeft
verticalAlignment: Text.AlignVCenter
elide: Text.ElideRight
}
}
}
然后你可以将它清理一下,把它放在自己的文件中,然后像
一样使用它ComboBox {
model: ListModel {
ListElement { textRole: "Swedish cars"; kind: "header" }
ListElement { textRole: "Saab"; kind: "element" }
ListElement { textRole: "Volvo"; kind: "element" }
ListElement { textRole: "German cars"; kind: "header" }
ListElement { textRole: "Mercedes"; kind: "element" }
ListElement { textRole: "Audi"; kind: "element" }
}
}
或者可能创建自定义的HeaderElement和TextElement子类,使其看起来像
ComboBox {
model: ListModel {
ComboHeader { text: "Swedish cars" }
ComboText { text: "Saab" }
ComboText { text: "Volvo" }
ComboHeader { text: "German cars" }
// etc...
}
}
......这取决于你想要走多远的工程规模:p
答案 1 :(得分:0)
与@ Jean-MichaëlCelerier相同的解决方案建议但有点简化:
ComboBox {
anchors.centerIn: parent
model: ListModel {
ListElement {name: "item1"; group: true }
ListElement {name: "subitem1" }
ListElement {name: "subitem2" }
ListElement {name: "item2"; group: true }
ListElement {name: "subitem1" }
ListElement {name: "subitem2" }
}
delegate: ItemDelegate {
text: name
enabled: (group != true)
font.bold: (group == true)
font.capitalization: (group == true ? Font.AllUppercase : Font.MixedCase)
leftPadding: (group == true ? 10 : 5)
}
}