问题描述
我希望我的 ComboBox
必须使其 width
适应我列表中最长的 String Item
.
I would like that my ComboBox
has to adapt its width
to the longest String Item
of my list.
代码示例:
ComboBox {
model: [ "Banana", "Apple", "ThisIsTheLongestWordThatIHave,"Coconut" ]
}
知道怎么做吗?
推荐答案
Quick-Controls-2 组合框(在撰写本文时,Qt 5.9)中没有内置机制,所以你必须这样做你自己.像这样的...
There is no built-in mechanism for this in Quick-Controls-2 combobox (at the time of writing, Qt 5.9), so you have to do it yourself. Something like this...
MyComboBox {
id: comboBox1
sizeToContents: false
model: [ "Banana", "Apple", "ThisIsTheLongestWordThatIHave", "Coconut" ]
}
MyComboBox {
id: comboBox2
anchors.top: comboBox1.bottom
sizeToContents: true
model: [ "Banana", "Apple", "ThisIsTheLongestWordThatIHave", "Coconut" ]
}
MyComboBox.qml
ComboBox {
id: control
property bool sizeToContents
property int modelWidth
width: (sizeToContents) ? modelWidth + 2*leftPadding + 2*rightPadding : implicitWidth
delegate: ItemDelegate {
width: control.width
text: control.textRole ? (Array.isArray(control.model) ? modelData[control.textRole] : model[control.textRole]) : modelData
font.weight: control.currentIndex === index ? Font.DemiBold : Font.Normal
font.family: control.font.family
font.pointSize: control.font.pointSize
highlighted: control.highlightedIndex === index
hoverEnabled: control.hoverEnabled
}
TextMetrics {
id: textMetrics
}
onModelChanged: {
textMetrics.font = control.font
for(var i = 0; i < model.length; i++){
textMetrics.text = model[i]
modelWidth = Math.max(textMetrics.width, modelWidth)
}
}
}
请注意,如果您将模型类型从 QML 列表更改为其他类型,例如 C++ QStringList
、QList
或 QAbstractListModel
,那么您可能需要修改这一行 textMetrics.text = model[i]
以稍微不同的方式从模型项中检索文本.
Note that if you change the model type from a QML List to a different type, such as C++ QStringList
, QList<QObject*>
or QAbstractListModel
, then you migth need to modify this line textMetrics.text = model[i]
to retrieve the text from the model items in a slightly different way.
这篇关于如何设置 ComboBox 宽度以适合最大项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!