我想在我的项目中使用ComboBox
类型。是否可以更改下拉菜单的外观(颜色、形状、文本样式),还是需要使用矩形、ListView
和其他类型的组合?
下面的代码应用自定义,但是没有为仍然是灰色的下拉菜单定义任何修改:
ComboBox {
currentIndex: 2
activeFocusOnPress: true
style: ComboBoxStyle {
id: comboBox
background: Rectangle {
id: rectCategory
radius: 5
border.width: 2
color: "#fff"
Image {
source: "pics/corner.png"
anchors.bottom: parent.bottom
anchors.right: parent.right
anchors.bottomMargin: 5
anchors.rightMargin: 5
}
}
label: Text {
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
font.pointSize: 15
font.family: "Courier"
font.capitalization: Font.SmallCaps
color: "black"
text: control.currentText
}
}
model: ListModel {
id: cbItems
ListElement { text: "Banana" }
ListElement { text: "Apple" }
ListElement { text: "Coconut" }
}
width: 200
}
发布于 2014-11-30 19:23:51
当前的公共API不允许像声明的这里那样定制下拉菜单.Qt 5.4
,即Styles 1.3
,只是引入了一些属性来定制字体和文本(docs 这里),但仍然没有公共访问来进行下拉自定义。
此外,链接中提供的示例不适用于较新版本的Qt。下面是我在QT5.3、Qt5.4和QT5.5中测试的修改版本(记住要将import QtQuick.Controls.Private 1.0
添加到导入中):
ComboBox {
id: box
currentIndex: 2
activeFocusOnPress: true
style: ComboBoxStyle {
id: comboBox
background: Rectangle {
id: rectCategory
radius: 5
border.width: 2
color: "#fff"
}
label: Text {
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
font.pointSize: 15
font.family: "Courier"
font.capitalization: Font.SmallCaps
color: "black"
text: control.currentText
}
// drop-down customization here
property Component __dropDownStyle: MenuStyle {
__maxPopupHeight: 600
__menuItemType: "comboboxitem"
frame: Rectangle { // background
color: "#fff"
border.width: 2
radius: 5
}
itemDelegate.label: // an item text
Text {
verticalAlignment: Text.AlignVCenter
horizontalAlignment: Text.AlignHCenter
font.pointSize: 15
font.family: "Courier"
font.capitalization: Font.SmallCaps
color: styleData.selected ? "white" : "black"
text: styleData.text
}
itemDelegate.background: Rectangle { // selection of an item
radius: 2
color: styleData.selected ? "darkGray" : "transparent"
}
__scrollerStyle: ScrollViewStyle { }
}
property Component __popupStyle: Style {
property int __maxPopupHeight: 400
property int submenuOverlap: 0
property Component frame: Rectangle {
width: (parent ? parent.contentWidth : 0)
height: (parent ? parent.contentHeight : 0) + 2
border.color: "black"
property real maxHeight: 500
property int margin: 1
}
property Component menuItemPanel: Text {
text: "NOT IMPLEMENTED"
color: "red"
font {
pixelSize: 14
bold: true
}
}
property Component __scrollerStyle: null
}
}
model: ListModel {
id: cbItems
ListElement { text: "Banana" }
ListElement { text: "Apple" }
ListElement { text: "Coconut" }
}
width: 200
}
在这里,__dropDownStyle
被分配一个MenuStyle
类型。这些类型的一些属性被定制以获得所需的样式,特别是itemDelegate
(它定义了组合框中的项的外观)和frame
(总体背景)。有关详细信息,请参阅链接的MenuStyle
API。总体结果:
请注意,这种方法在Windows和Android上确实非常有效,而在OSX上则完全忽略了代码。您可以检查Qt安装中的qml样式文件(搜索像qml/QtQuick/Controls/Styles/Desktop
这样的子路径),以查看w.r.t的哪些更改。窗口并尝试修改所提供的解决方案。这部分由读者来决定。
https://stackoverflow.com/questions/27089779
复制相似问题