Qt:复选框单击不起作用

Qt: checkbox single click not working

我在 Qt 5.9 中使用 QtQuick,我遇到了一个奇怪的问题。 当我在 QML 中创建两个 Tumblers 和一个 CheckBox 时,一切正常。

但是,当我为 id: secondTumbler 创建一个事件处理程序来操纵 testCheckBox.checked 状态时,CheckBox 开始以一种奇怪的方式运行。

当我启动应用程序并首先滚动任何玻璃杯然后单击 CheckBox 时,它不会检查。第二次点击最终会检查它,但这是一种奇怪的行为。

我唯一写的是 main.qml 中的以下代码:

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")

    Tumbler {
        id: firstTumbler
        model: 10
        anchors.left: parent.left
    }

    Tumbler {
        id: secondTumbler
        model: 10
        anchors.right: parent.right

        onCurrentIndexChanged: {
                testCheckBox.checked = false
        }
    }

    CheckBox {
        id: testCheckBox
        anchors.left: firstTumbler.right

        onCheckedChanged: {
            if(testCheckBox.checked == true)
            {
                secondTumbler.currentIndex = firstTumbler.currentIndex
            }
        }
    }
}

我错过了什么?

问题是 javascript 异步运行。因此,信号和槽不像在 C++ 中那样工作。它们与其他代码一起触发,而不是按顺序触发。这使它们成为逻辑处理的不可靠中介,因为事件发生的顺序可能会有所不同。

相反,

通过将 属性(例如 currentIndex)设置为使用 property var <my property>currentIndex: <my property>[=14= 创建的另一个 属性,为此使用 属性 绑定]

然后您可以通过设置 <my property> 来更改 currentIndex 的值,而不会中断事物的流动。

    Tumbler {
            id: firstTumbler
            model: 10
            anchors.left: parent.left
        } 


       /* Edit in response to comment #1 
        */

     property bool followFirst: testCheckbox.checked


       /* end of Edit in response to comment #1 */

        Tumbler {
            id: secondTumbler
            model: 10


            /* modify the property of currentIndex  by changing this variable which will be bound to the currentIndex property */
            property var m_index: 0


            anchors.right: parent.right


           /* conditional assignment for currentIndex -- do not set currentIndex directly or this will disappear.. 
  instead set secondTumbler.m_index */
            currentIndex: testCheckBox.checked === true ?    firstTumbler.currentIndex : m_index

            /* ensures that changing the currentIndex does not change the     actual property, but instead changes m_index which will be bound to that property */
            onCurrentIndexChanged: {
                   m_index = currentIndex;




                  /* Edit in response to comment #1 
                  */

                   if (followFirst) { testCheckBox.checked = false }

                  /* end of Edit in response to comment #1 */
            }
        }

这将允许 chckbox 与 tumbler 一起更改状态,而不会 运行 进入当前索引更改引起的状态冲突。