2

我想在TextField有可接受的文本时启用按钮(我正在使用validator),并且此代码工作正常:

import QtQuick 2.3
import QtQuick.Controls 1.2

ApplicationWindow {
    visible: true
    width: 400
    height: 100
    id: mainWindow
    property int _buttonSize: 30
    property int _interval: 10

    TextField {
        y: _interval
        width: parent.width
        height: _buttonSize
        id: ipInput
        horizontalAlignment: Text.AlignHCenter
        verticalAlignment: Text.AlignVCenter
        placeholderText: "IP"
        validator: RegExpValidator
        {
            regExp:/^(([01]?[0-9]?[0-9]|2([0-4][0-9]|5[0-5]))\.){3}([01]?[0-9]?[0-9]|2([0-4][0-9]|5[0-5]))$/
        }
    }

    Button {
        enabled: ipInput.acceptableInput
        id: go
        anchors.horizontalCenter: parent.horizontalCenter
        y: ipInput.y+_buttonSize+_interval
        width: parent.width
        height: _buttonSize
        text: "GO"
    }
}

所以,我添加Action到这个Button

Button {
    enabled: ipInput.acceptableInput
    id: go
    anchors.horizontalCenter: parent.horizontalCenter
    y: ipInput.y+_buttonSize+_interval
    width: parent.width
    height: _buttonSize
    text: "GO"
    action: goAction
    Action {
        id: goAction
        shortcut: "Enter"
        enabled: go.enabled && go.visible
        onTriggered: {
            console.log("good")
        }
    }
}

现在Button总是禁用。我该如何解决?

4

1 回答 1

1

Actions 通过同步Item它们绑定到的所有 s 的状态来工作。文档说:

在应用程序中,可以通过菜单、工具栏按钮和键盘快捷键调用许多常用命令。由于用户希望每个命令都以相同的方式执行,因此无论使用何种用户界面,将每个命令表示为一个动作是很有用的。

动作可以绑定到菜单项和工具栏按钮,它会自动使它们保持同步。例如,在文字处理器中,如果用户按下粗体工具栏按钮,将自动选中粗体菜单项。

从这个意义上说,Action属性支配着它所绑定的 s 的属性,Item反之则不然。Action启用时,它所附加的所有 s 也都启用Item因此,启用条件应移至Action.

这是您的代码的重新访问版本。我添加了另一个Button来强调Action功能。这里两个Buttons 都在满足条件时自动启用,因为它是关联Action的启用。

import QtQuick 2.3
import QtQuick.Controls 1.2

ApplicationWindow {
    visible: true
    id: mainWindow

    Column {
        spacing: 10
        TextField {
            width: 400
            height: 40
            id: ipInput
            horizontalAlignment: TextInput.AlignHCenter
            placeholderText: "IP"
            validator: RegExpValidator {
                regExp:/^(([01]?[0-9]?[0-9]|2([0-4][0-9]|5[0-5]))\.){3}([01]?[0-9]?[0-9]|2([0-4][0-9]|5[0-5]))$/
            }
        }

        Action {
            id: goAction
            shortcut: "Enter"
            enabled: ipInput.acceptableInput
            onTriggered: {
                console.log("good")
            }
        }

        Button {
            id: go
            width: 400
            height: 40
            text: "GO"
            action: goAction
        }

        Button {
            id: go2
            width: 400
            height: 40
            text: "GO2"
            action: goAction
        }
    }
}
于 2015-12-06T11:08:41.123 回答