ComboBox QML Type

Combined button and popup list for selecting options. 更多...

import 语句: import QtQuick.Controls
继承:

Control

特性

信号

方法

详细描述

ComboBox is a combined button and popup list. It provides a means of presenting a list of options to the user in a way that takes up the minimum amount of screen space.

ComboBox is populated with a data model. The data model is commonly a JavaScript array, a ListModel or an integer, but other types of data models are also supported.

ComboBox {
    model: ["First", "Second", "Third"]
}
					

Editable ComboBox

ComboBox can be made editable . An editable combo box auto-completes its text based on what is available in the model.

The following example demonstrates appending content to an editable combo box by reacting to the accepted 信号。

ComboBox {
    editable: true
    model: ListModel {
        id: model
        ListElement { text: "Banana" }
        ListElement { text: "Apple" }
        ListElement { text: "Coconut" }
    }
    onAccepted: {
        if (find(editText) === -1)
            model.append({text: editText})
    }
}
					

ComboBox's Popup

By default, clicking outside of ComboBox's popup will close it, and the event is propagated to items lower in the stacking order. To prevent the popup from closing, set its closePolicy :

    popup.closePolicy: Popup.CloseOnEscape
					

To prevent event propagation, set its modal 特性到 true :

    popup.modal: true
					

ComboBox Model Roles

ComboBox is able to visualize standard data models that provide the modelData role:

  • models that have only one role
  • models that do not have named roles (JavaScript array, integer)

When using models that have multiple named roles, ComboBox must be configured to use a specific text role for its display text and delegate instances. If you want to use a role of the model item that corresponds to the text role, set valueRole currentValue 特性和 indexOfValue () method can then be used to get information about those values.

例如:

ApplicationWindow {
    width: 640
    height: 480
    visible: true
    // Used as an example of a backend - this would usually be
    // e.g. a C++ type exposed to QML.
    QtObject {
        id: backend
        property int modifier
    }
    ComboBox {
        textRole: "text"
        valueRole: "value"
        // When an item is selected, update the backend.
        onActivated: backend.modifier = currentValue
        // Set the initial currentIndex to the value stored in the backend.
        Component.onCompleted: currentIndex = indexOfValue(backend.modifier)
        model: [
            { value: Qt.NoModifier, text: qsTr("No modifier") },
            { value: Qt.ShiftModifier, text: qsTr("Shift") },
            { value: Qt.ControlModifier, text: qsTr("Control") }
        ]
    }
}
					

注意: If ComboBox is assigned a data model that has multiple named roles, but textRole is not defined, ComboBox is unable to visualize it and throws a ReferenceError: modelData is not defined .

另请参阅 Customizing ComboBox , 输入控件 ,和 Focus Management in Qt Quick Controls .

特性文档编制

acceptableInput : bool [read-only, since QtQuick.Controls 2.2 (Qt 5.9)]

This property holds whether the combo box contains acceptable text in the editable text field.

If a validator has been set, the value is true only if the current text is acceptable to the validator as a final string (not as an intermediate string).

This property was introduced in QtQuick.Controls 2.2 (Qt 5.9).

另请参阅 validator and accepted .

count : int [read-only]

This property holds the number of items in the combo box.

currentIndex : int

This property holds the index of the current item in the combo box.

默认值为 -1 count is 0 ,和 0 否则。

另请参阅 activated (), currentText ,和 highlightedIndex .

currentText : string [read-only]

This property holds the text of the current item in the combo box.

另请参阅 currentIndex , displayText , textRole ,和 editText .

currentValue : var [read-only, since QtQuick.Controls 2.14 (Qt 5.14)]

This property holds the value of the current item in the combo box.

For an example of how to use this property, see ComboBox Model Roles .

This property was introduced in QtQuick.Controls 2.14 (Qt 5.14).

另请参阅 currentIndex , currentText ,和 valueRole .

delegate : Component

This property holds a delegate that presents an item in the combo box popup.

It is recommended to use ItemDelegate (or any other AbstractButton derivatives) as the delegate. This ensures that the interaction works as expected, and the popup will automatically close when appropriate. When other types are used as the delegate, the popup must be closed manually. For example, if MouseArea is used:

delegate: Rectangle {
    // ...
    MouseArea {
        // ...
        onClicked: comboBox.popup.close()
    }
}
					

另请参阅 ItemDelegate and Customizing ComboBox .

displayText : string

This property holds the text that is displayed on the combo box button.

By default, the display text presents the current selection. That is, it follows the text of the current item. However, the default display text can be overridden with a custom value.

ComboBox {
    currentIndex: 1
    displayText: "Size: " + currentText
    model: ["S", "M", "L"]
}
					

另请参阅 currentText and textRole .

down : bool [since QtQuick.Controls 2.2 (Qt 5.9)]

This property holds whether the combo box button is visually down.

Unless explicitly set, this property is true pressed or popup.visible is true . To return to the default value, set this property to undefined .

This property was introduced in QtQuick.Controls 2.2 (Qt 5.9).

另请参阅 pressed and popup .

editText : string [since QtQuick.Controls 2.2 (Qt 5.9)]

This property holds the text in the text field of an editable combo box.

This property was introduced in QtQuick.Controls 2.2 (Qt 5.9).

另请参阅 editable , currentText ,和 displayText .

editable : bool [since QtQuick.Controls 2.2 (Qt 5.9)]

This property holds whether the combo box is editable.

默认值为 false .

This property was introduced in QtQuick.Controls 2.2 (Qt 5.9).

另请参阅 validator .

flat : bool [since QtQuick.Controls 2.1 (Qt 5.8)]

This property holds whether the combo box button is flat.

A flat combo box button does not draw a background unless it is interacted with. In comparison to normal combo boxes, flat combo boxes provide looks that make them stand out less from the rest of the UI. For instance, when placing a combo box into a tool bar, it may be desirable to make the combo box flat so it matches better with the flat looks of tool buttons.

默认值为 false .

该特性在 QtQuick.Controls 2.1 (Qt 5.8) 引入。

highlightedIndex : int [read-only]

This property holds the index of the highlighted item in the combo box popup list.

When a highlighted item is activated, the popup is closed, currentIndex 被设为 highlightedIndex , and the value of this property is reset to -1 , as there is no longer a highlighted item.

另请参阅 highlighted () 和 currentIndex .

implicitContentWidthPolicy : enumeration [since QtQuick.Controls 6.0 (Qt 6.0)]

This property controls how the implicitContentWidth ComboBox is calculated.

When the width of a ComboBox is not large enough to display text, that text is elided. Depending on which parts of the text are elided, this can make selecting an item difficult for the end user. An efficient way of ensuring that a ComboBox is wide enough to avoid text being elided is to set a width that is known to be large enough:

width: 300
implicitContentWidthPolicy: ComboBox.ContentItemImplicitWidth
					

However, it is often not possible to know whether or not a hard-coded value will be large enough, as the size of text depends on many factors, such as font family, font size, translations, and so on.

implicitContentWidthPolicy provides an easy way to control how the implicitContentWidth is calculated, which in turn affects the implicitWidth ComboBox and ensures that text will not be elided.

The available values are:

常量 描述
ContentItemImplicitWidth The implicitContentWidth will default to that of the contentItem . This is the most efficient option, as no extra text layout is done.
WidestText The implicitContentWidth will be set to the implicit width of the the largest text for the given textRole every time the model changes. This option should be used with smaller models, as it can be expensive.
WidestTextWhenCompleted The implicitContentWidth will be set to the implicit width of the the largest text for the given textRole once after component completion . This option should be used with smaller models, as it can be expensive.

默认值为 ContentItemImplicitWidth .

As this property only affects the implicitWidth ComboBox , setting an explicit width can still result in eliding.

注意: This feature requires the contentItem to be a type derived from TextInput .

注意: This feature requires text to be laid out, and can therefore be expensive for large models or models whose contents are updated frequently.

This property was introduced in QtQuick.Controls 6.0 (Qt 6.0).

implicitIndicatorHeight : real [read-only, since QtQuick.Controls 2.5 (Qt 5.12)]

This property holds the implicit indicator height.

值等于 indicator ? indicator.implicitHeight : 0 .

This is typically used, together with implicitContentHeight and implicitBackgroundHeight , to calculate the implicitHeight .

该特性在 QtQuick.Controls 2.5 (Qt 5.12) 引入。

另请参阅 implicitIndicatorWidth .

implicitIndicatorWidth : real [read-only, since QtQuick.Controls 2.5 (Qt 5.12)]

This property holds the implicit indicator width.

值等于 indicator ? indicator.implicitWidth : 0 .

This is typically used, together with implicitContentWidth and implicitBackgroundWidth , to calculate the implicitWidth .

该特性在 QtQuick.Controls 2.5 (Qt 5.12) 引入。

另请参阅 implicitIndicatorHeight .

indicator : Item

This property holds the drop indicator item.

另请参阅 Customizing ComboBox .

inputMethodComposing : bool [read-only, since QtQuick.Controls 2.2 (Qt 5.9)]

This property holds whether an editable combo box has partial text input from an input method.

While it is composing, an input method may rely on mouse or key events from the combo box to edit or commit the partial text. This property can be used to determine when to disable event handlers that may interfere with the correct operation of an input method.

This property was introduced in QtQuick.Controls 2.2 (Qt 5.9).

inputMethodHints : flags [since QtQuick.Controls 2.2 (Qt 5.9)]

Provides hints to the input method about the expected content of the combo box and how it should operate.

默认值为 Qt.ImhNoPredictiveText .

The value is a bit-wise combination of flags or Qt.ImhNone if no hints are set.

Flags that alter behavior are:

  • Qt.ImhHiddenText - Characters should be hidden, as is typically used when entering passwords.
  • Qt.ImhSensitiveData - Typed text should not be stored by the active input method in any persistent storage like predictive user dictionary.
  • Qt.ImhNoAutoUppercase - The input method should not try to automatically switch to upper case when a sentence ends.
  • Qt.ImhPreferNumbers - Numbers are preferred (but not required).
  • Qt.ImhPreferUppercase - Upper case letters are preferred (but not required).
  • Qt.ImhPreferLowercase - Lower case letters are preferred (but not required).
  • Qt.ImhNoPredictiveText - Do not use predictive text (i.e. dictionary lookup) while typing.
  • Qt.ImhDate - The text editor functions as a date field.
  • Qt.ImhTime - The text editor functions as a time field.

Flags that restrict input (exclusive flags) are:

  • Qt.ImhDigitsOnly - Only digits are allowed.
  • Qt.ImhFormattedNumbersOnly - Only number input is allowed. This includes decimal point and minus sign.
  • Qt.ImhUppercaseOnly - Only upper case letter input is allowed.
  • Qt.ImhLowercaseOnly - Only lower case letter input is allowed.
  • Qt.ImhDialableCharactersOnly - Only characters suitable for phone dialing are allowed.
  • Qt.ImhEmailCharactersOnly - Only characters suitable for email addresses are allowed.
  • Qt.ImhUrlCharactersOnly - Only characters suitable for URLs are allowed.

掩码:

  • Qt.ImhExclusiveInputMask - This mask yields nonzero if any of the exclusive flags are used.

This property was introduced in QtQuick.Controls 2.2 (Qt 5.9).

model : model

This property holds the model providing data for the combo box.

ComboBox {
    textRole: "key"
    model: ListModel {
        ListElement { key: "First"; value: 123 }
        ListElement { key: "Second"; value: 456 }
        ListElement { key: "Third"; value: 789 }
    }
}
					

另请参阅 textRole and 数据模型 .

This property holds the popup.

The popup can be opened or closed manually, if necessary:

onSpecialEvent: comboBox.popup.close()
					

另请参阅 Customizing ComboBox .

pressed : bool [read-only]

This property holds whether the combo box button is physically pressed. A button can be pressed by either touch or key events.

另请参阅 down .

selectTextByMouse : bool [since QtQuick.Controls 2.15 (Qt 5.15)]

This property holds whether the text field for an editable ComboBox can be selected with the mouse.

默认值为 false .

This property was introduced in QtQuick.Controls 2.15 (Qt 5.15).

textRole : string

This property holds the model role used for populating the combo box.

When the model has multiple roles, textRole can be set to determine which role should be displayed.

另请参阅 model , currentText , displayText ,和 ComboBox Model Roles .

validator : Validator [since QtQuick.Controls 2.2 (Qt 5.9)]

This property holds an input text validator for an editable combo box.

When a validator is set, the text field will only accept input which leaves the text property in an intermediate state. The accepted signal will only be emitted if the text is in an acceptable state when the 返回 or Enter key is pressed.

The currently supported validators are IntValidator , DoubleValidator ,和 RegularExpressionValidator . An example of using validators is shown below, which allows input of integers between 0 and 10 into the text field:

ComboBox {
    model: 10
    editable: true
    validator: IntValidator {
        top: 9
        bottom: 0
    }
}
					

This property was introduced in QtQuick.Controls 2.2 (Qt 5.9).

另请参阅 acceptableInput , accepted ,和 editable .

valueRole : string [since QtQuick.Controls 2.14 (Qt 5.14)]

This property holds the model role used for storing the value associated with each item in the model.

For an example of how to use this property, see ComboBox Model Roles .

This property was introduced in QtQuick.Controls 2.14 (Qt 5.14).

另请参阅 model and currentValue .

信号文档编制

[since QtQuick.Controls 2.2 (Qt 5.9)] void accepted ()

此信号发射当 返回 or Enter key is pressed on an editable combo box.

You can handle this signal in order to add the newly entered item to the model, for example:

ComboBox {
    editable: true
    model: ListModel {
        id: model
        ListElement { text: "Banana" }
        ListElement { text: "Apple" }
        ListElement { text: "Coconut" }
    }
    onAccepted: {
        if (find(editText) === -1)
            model.append({text: editText})
    }
}
					

Before the signal is emitted, a check is done to see if the string exists in the model. If it does, currentIndex will be set to its index, and currentText to the string itself.

After the signal has been emitted, and if the first check failed (that is, the item did not exist), another check will be done to see if the item was added by the signal handler. If it was, the currentIndex and currentText are updated accordingly. Otherwise, they will be set to -1 and "" ,分别。

注意: 若有 validator set on the combo box, the signal will only be emitted if the input is in an acceptable state.

注意: 相应处理程序是 onAccepted .

This signal was introduced in QtQuick.Controls 2.2 (Qt 5.9).

void activated ( int index )

This signal is emitted when the item at index is activated by the user.

An item is activated when it is selected while the popup is open, causing the popup to close (and currentIndex to change), or while the popup is closed and the combo box is navigated via keyboard, causing the currentIndex to change. The currentIndex property is set to index .

注意: 相应处理程序是 onActivated .

另请参阅 currentIndex .

void highlighted ( int index )

This signal is emitted when the item at index in the popup list is highlighted by the user.

The highlighted signal is only emitted when the popup is open and an item is highlighted, but not necessarily activated .

注意: 相应处理程序是 onHighlighted .

另请参阅 highlightedIndex .

方法文档编制

void decrementCurrentIndex ()

Decrements the current index of the combo box, or the highlighted index if the popup list is visible.

另请参阅 currentIndex and highlightedIndex .

int find ( string text , enumeration flags )

Returns the index of the specified text ,或 -1 if no match is found.

The way the search is performed is defined by the specified match flags . By default, combo box performs case sensitive exact matching ( Qt.MatchExactly ). All other match types are case-insensitive unless the Qt.MatchCaseSensitive 标志也有指定。

常量 描述
Qt.MatchExactly The search term matches exactly (default).
Qt.MatchRegularExpression The search term matches as a regular expression.
Qt.MatchWildcard The search term matches using wildcards.
Qt.MatchFixedString The search term matches as a fixed string.
Qt.MatchStartsWith 搜索术语匹配项开头。
Qt.MatchEndsWidth 搜索术语匹配项末尾。
Qt.MatchContains 搜索术语包含在项中。
Qt.MatchCaseSensitive 搜索区分大小写。

注意: This function can only be used after Component.completed () is emitted for the ComboBox .

例如:

ComboBox {
    model: ListModel {
        ListElement { text: "Banana" }
        ListElement { text: "Apple" }
        ListElement { text: "Coconut" }
    }
    Component.onCompleted: currentIndex = find("Coconut")
}
					

另请参阅 textRole .

void incrementCurrentIndex ()

Increments the current index of the combo box, or the highlighted index if the popup list is visible.

另请参阅 currentIndex and highlightedIndex .

[since QtQuick.Controls 2.14 (Qt 5.14)] int indexOfValue ( 对象 value )

Returns the index of the specified value ,或 -1 if no match is found.

For an example of how to use this method, see ComboBox Model Roles .

注意: This function can only be used after Component.completed () is emitted for the ComboBox .

This method was introduced in QtQuick.Controls 2.14 (Qt 5.14).

另请参阅 find (), currentValue , currentIndex , valueRole ,和 valueAt .

[since QtQuick.Controls 2.2 (Qt 5.9)] void selectAll ()

Selects all the text in the editable text field of the combo box.

This method was introduced in QtQuick.Controls 2.2 (Qt 5.9).

另请参阅 editText .

string textAt ( int index )

Returns the text for the specified index , or an empty string if the index is out of bounds.

注意: This function can only be used after Component.completed () is emitted for the ComboBox .

例如:

ComboBox {
    model: ListModel {
        ListElement { text: "Banana" }
        ListElement { text: "Apple" }
        ListElement { text: "Coconut" }
    }
    onActivated: (index) => { print(textAt(index)) }
}
					

另请参阅 textRole .

[since QtQuick.Controls 2.14 (Qt 5.14)] var valueAt ( int index )

Returns the value at position index in the combo box.

This method was introduced in QtQuick.Controls 2.14 (Qt 5.14).

另请参阅 indexOfValue .