qml中的自定义单选按钮

时间:2013-03-05 21:39:38

标签: qml

我想要一个带3个按钮的窗口,但这个按钮应该像单选按钮一样工作! 所以这是我的代码:

Rectangle {
    id: sideButton
    color:  sideButtonMouseArea.containsMouse ? '#DDDDDD' : '#F4F4F4'
    property string text: 'Button'
    MouseArea {
        id: sideButtonMouseArea
        anchors.fill: parent
        hoverEnabled: true
        onClicked: {
            parent.color = '#4872E8'
            sideButtonLabel.color = '#E2EBFC'
        }
    }

    Text {
        id: sideButtonLabel
        text: sideButton.text
        font.pixelSize: 20
        font.family: 'Tahoma'
        anchors.centerIn: sideButton
        color: '#787878'
    }
}

我使用这个矩形代替按钮但是在2个时间点击其他按钮时会出现问题 我怎么能解决它?

1 个答案:

答案 0 :(得分:4)

此代码适用于我:

<强> MyRadioGroup.qml

import QtQuick 1.0

QtObject {
    property Item selected : null
}

<强> MyRadioButton.qml

import QtQuick 1.0

Rectangle {
    id: sideButton
    property string text: 'Button'
    property MyRadioGroup radioGroup

    color:  radioGroup.selected === sideButton ? '#E2EBFC' :
            (sideButtonMouseArea.containsMouse ? '#DDDDDD' : '#F4F4F4')
    MouseArea {
        id: sideButtonMouseArea
        anchors.fill: parent
        hoverEnabled: true
        onClicked: sideButton.radioGroup.selected = sideButton
    }

    Text {
        id: sideButtonLabel
        text: sideButton.text
        font.pixelSize: 20
        font.family: 'Tahoma'
        anchors.centerIn: sideButton
        color: radioGroup.selected === sideButton ? '#E2EBFC' : '#787878'
    }
}

<强> main.qml

import QtQuick 1.0

Rectangle {
    height: 600
    width: 600

    MyRadioGroup {
        id: radioGroup1
    }

    Column {
        anchors.fill: parent

        MyRadioButton {
            anchors { left: parent.left; right: parent.right }
            text: "Button 1"
            radioGroup: radioGroup1
            height: 100
        }

        MyRadioButton {
            anchors { left: parent.left; right: parent.right }
            text: "Button 2"
            radioGroup: radioGroup1
            height: 100
        }

        MyRadioButton {
            anchors { left: parent.left; right: parent.right }
            text: "Button 3"
            radioGroup: radioGroup1
            height: 100
        }

        MyRadioButton {
            anchors { left: parent.left; right: parent.right }
            text: "Button 4"
            radioGroup: radioGroup1
            height: 100
        }
    }   
}

它的作用:我创建了容器MyRadioGroup来保存当前选中的项目。然后,我声明性地将其selected属性绑定到color - s的MyRadioButton属性,因此它会在每次selected更改时更新。


说完之后,请检查一下,你的组件提供商还没有包含这样的东西---也许你正在重新发明轮子。