Qt:复选框单击不起作用

时间:2018-04-12 22:32:15

标签: qt checkbox qml qtquickcontrols2

我在 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
            }
        }
    }
}

我错过了什么?

1 个答案:

答案 0 :(得分:0)

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

相反,

通过将属性(如currentIndex)设置为使用currentIndex: <my property><my property>

创建的其他属性,对此属性绑定使用

然后,您可以通过设置 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 */ } } 来更改currentIndex的值,而不会中断事情的流动。

# extract records: log file may contain other informations
awk '$4=="start_time";$4=="end_time"' logs.txt  |
# wrap records:
# # start_time and end_time may appear alternately in the log.
# # wrap a pair into 1 line.
awk '{if(NR%2==1){ printf("%s ",$0) }else{ print }}'    |
# and convert
# # tr command character wise editor, read ``man tr''.
tr '.:' ' ' |
# # make your favorite output
awk -v OFS="," '{
    print $3 "-" $2 "-" $1 " " $4 ":" $5 ":" $6,
    3600 * ($12-$4) + 60 * ($13-$5) + ($14-$6)
    }'

这将允许chckbox与滚筒一起改变状态,而不会遇到因当前索引更改而导致的状态冲突。