Programación Gráfica en C++: Crear Casilla de Verificación con Qt Quick CheckBox

Para crear un componente CheckBox en Qt Quick, utilizaremos el componente CheckBox proporcionado por Qt Quick Controls 2:

import QtQuick
import QtQuick.Controls

ApplicationWindow {
    visible: true
    width: 400
    height: 200
    title: "Ejemplo de CheckBox"

    Column {
        spacing: 10
        anchors.centerIn: parent

        CheckBox {
            text: "Habilitar función"
            checked: true // Puedes establecer el estado inicial del CheckBox aquí

            onClicked: {
                // Maneja el evento cuando el CheckBox se hace clic
                console.log("CheckBox está marcado:", checked);
            }
        }
    }
}

En este ejemplo, hemos creado un CheckBox dentro de un diseño de columna. El atributo text se utiliza para proporcionar una etiqueta junto al CheckBox. También hemos establecido el atributo checked en true para que el CheckBox esté marcado inicialmente.

El evento onClicked se utiliza para manejar cuando el CheckBox se hace clic. Puedes realizar acciones específicas según el estado del CheckBox.

Un ejemplo más elaborado: Crear, copiar los códigos y ejecutar el proyecto que contiene los 3 archivos siguientes: myObject.h, main.cpp y Main.qml:

myObject.h

#ifndef MYOBJECT_H
#define MYOBJECT_H

#include <QObject>
#include <QQmlContext>
#include <QtQml>

class MyObject : public QObject
{
    Q_OBJECT
    QML_ELEMENT
    Q_PROPERTY(bool new_checkboxState MEMBER m_functionEnabled NOTIFY functionEnabledChanged);

public:
    explicit MyObject(QObject *parent = nullptr);

public slots:
    void enableFunction();
    void disableFunction();
    void toggleCheckBox();

signals:
    void functionEnabledChanged(bool enabled);

private:
    bool m_functionEnabled;
};

#endif // MYOBJECT_H

main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include <QDebug>
#include "myObject.h"

MyObject::MyObject(QObject *parent)
    : QObject(parent)
{
}

void MyObject::enableFunction() {
    m_functionEnabled = true;
    qDebug() << "Función habilitada desde QML";
        emit functionEnabledChanged(m_functionEnabled);
}

void MyObject::disableFunction() {
    m_functionEnabled = false;
    qDebug() << "Función deshabilitada desde QML";
        emit functionEnabledChanged(m_functionEnabled);
}

void MyObject::toggleCheckBox() {
    m_functionEnabled = !m_functionEnabled;
    qDebug() << "Estado del CheckBox cambiado desde C++";
        emit functionEnabledChanged(m_functionEnabled);
}

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;

    MyObject myCheckbox;
    engine.rootContext()->setContextProperty("myCheckbox", &myCheckbox);

    const QUrl url(u"qrc:/qt/qml/MiProyectoQtQuick_3/Main.qml"_qs);
    engine.load(url);

    if (engine.rootObjects().isEmpty())
        return -1;

    return app.exec();
}

Main.qml

import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Controls.Material
import MiProyectoQtQuick_3

ApplicationWindow {
    visible: true
    width: 400
    height: 400
    title: "Ejemplo de CheckBox"

    CheckBox {
        id: checkBox
        text: "Habilitar Función"
        anchors.centerIn: parent
        checked: myCheckbox.new_checkboxState
        onCheckedChanged: {
            if (checked) {
                myCheckbox.enableFunction()
            } else {
                myCheckbox.disableFunction()
            }
        }
    }

    Button {
        text: "Cambiar estado desde QML"
        anchors {
            top: checkBox.bottom
            horizontalCenter: parent.horizontalCenter
            topMargin: 20
        }
        onClicked: {
            checkBox.checked = !checkBox.checkState
        }
    }

    Button {
        text: "Cambiar estado desde C++"
        anchors {
            top: checkBox.bottom
            horizontalCenter: parent.horizontalCenter
            topMargin: 80
        }
        onClicked: {
            myCheckbox.toggleCheckBox()
            checkBox.checked = myCheckbox.new_checkboxState
            console.log(myCheckbox.new_checkboxState)
        }

    }
}
Ejemplo de Checkbox C++ / Qt Quick
  1. El CheckBox en Main.qml está vinculado al estado del CheckBox en la instancia de MyObject a través de la propiedad checked.
  2. Cuando se marca o desmarca el CheckBox en QML, se llama a las funciones enableFunction o disableFunction en la instancia de MyObject, y se emite la señal functionEnabledChanged.
  3. El botón “Cambiar estado desde QML” cambia el estado del CheckBox en QML directamente.
  4. El botón “Cambiar estado desde C++” llama a toggleCheckBox en la instancia de MyObject, lo que cambia el estado del CheckBox desde C++ y actualiza el CheckBox en QML.

One thought on “Programación Gráfica en C++: Crear Casilla de Verificación con Qt Quick CheckBox

Deja un comentario