Setting checked property of a button
Solved
QML and Qt Quick
-
I am having a group of buttons in a
Column
and i have setautoExclusive : true
. Now only one button can be checked as expected. But, how to disable the checked state if i click on the button which is already checked? Following is the code:Column { id: column Button { checked: true text: qsTr("button 1") autoExclusive : true checkable : true background: Rectangle { color:checked ? "red" : "white" } } Button { checked: true text: qsTr("button 2") autoExclusive : true checkable : true background: Rectangle { color:checked ? "red" : "white" } } Button { checked: true text: qsTr("button 3") autoExclusive : true checkable : true background: Rectangle { color:checked ? "red" : "white" } } }
-
Hi! Unfortunately, this is not supported by the exclusive group mechanism. But it's easy to implement it yourself.
mygroup.h
#ifndef MYGROUP_H #define MYGROUP_H #include <QObject> class MyGroup : public QObject { Q_OBJECT Q_PROPERTY(QList<QObject*> buttons READ buttons WRITE setButtons NOTIFY buttonsChanged) public: MyGroup(QObject *parent = nullptr); QList<QObject*> buttons(); void setButtons(QList<QObject*> btns); signals: void buttonsChanged(QList<QObject*>); private slots: void disableOthers(); private: QList<QObject*> m_buttons; }; #endif // MYGROUP_H
mygroup.cpp
#include "mygroup.h" #include <QVariant> MyGroup::MyGroup(QObject *parent) : QObject(parent) { } QList<QObject *> MyGroup::buttons() { return m_buttons; } void MyGroup::setButtons(QList<QObject *> btns) { if (m_buttons == btns) return; for (auto i: m_buttons) disconnect(i, SIGNAL(clicked()), this, SLOT(disableOthers())); m_buttons = btns; for (auto i: m_buttons) connect(i, SIGNAL(clicked()), this, SLOT(disableOthers())); emit buttonsChanged(m_buttons); } void MyGroup::disableOthers() { for (auto i: m_buttons) { if (i == sender()) continue; i->setProperty("checked", false); } }
in main.cpp
qmlRegisterType<MyGroup>("io.qt.forum", 1, 0, "MyGroup");
main.qml
import QtQuick 2.7 import QtQuick.Controls 2.0 import QtQuick.Layouts 1.3 import io.qt.forum 1.0 as Forum ApplicationWindow { visible: true width: 640 height: 480 color: "black" Forum.MyGroup { buttons: [btn1, btn2, btn3] } Column { id: column anchors.centerIn: parent spacing: 10 Button { id: btn1 text: "button1" checkable : true background: Rectangle { color: parent.checked ? "red" : "white" } } Button { id: btn2 text: "button2" checkable : true background: Rectangle { color: parent.checked ? "red" : "white" } } Button { id: btn3 text: "button3" checkable : true background: Rectangle { color: parent.checked ? "red" : "white" } } } }
-
@Wieland thanks !!! for the answer.