Search code examples
c++qtuser-interfaceqt-creator

use a signal between 2 classes Qt


I have a MainWindow class which contain a QComboBox and a widget which is from another class. This second class contain a QCheckBox and a QComboBox. I want to use a signal to change the checkState of my QCheckBox and the string displayed in my QComboBox from my widget class when the string displayed in my QComboBox from my MainWindow has changed.

But I don't really understand which form my signal must have and how I can use it in my widget class.

MainWindow.h :

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QWidget>
#include <QComboBox>

#include "devices_left_widget.h"

#define STRING_DEVICE1 "DEVICE1"
#define STRING_DEFAULT ""

class MainWindow : public QMainWindow {
    Q_OBJECT

public:
    explicit MainWindow(QWidget* parent = nullptr);

signals:

public slots:
    void carte_OK();

protected:
    QComboBox* carte_type_combo_box;

    devices_left_widget* left_widget;
};

#endif // MAINWINDOW_H

device_left_widget.h :

#ifndef DEVICE_LEFT_WIDGET_H
#define DEVICE_LEFT_WIDGET_H

#include <QWidget>
#include <QCheckBox>
#include <QComboBox>

#define STRING_DEVICE1 "DEVICE1"
#define STRING_DEFAULT ""

    class device_left_widget : public QWidget {
    Q_OBJECT
public:
    explicit device_left_widget(QWidget* parent = nullptr);

signals:

public slots:

protected:
    QGridLayout* main_grid_layout;

    QCheckBox* device_checkbox;

    QComboBox* device_type_combo_box;
};

#endif // DEVICES_LEFT_WIDGET_H

Solution

  • Let's call your widget's name container. We want to connect QComboBox's currentTextChanged(const QString &text) signal to the widget, so we create a slot that corresponds to the signal, let it be chosenTextChanged(const QString& text). We connect them inside MainWindow constructor:

        connect(ui->comboBox, SIGNAL(currentTextChanged(const QString &)),
                ui->container, SLOT(chosenTextChanged(const QString &)));
    

    And inside your container class, define the slot as public:

    public slots:
        void chosenTextChanged(const QString &text) {
            //change your QCheckBox's state and
            //change your QComboBox's text
    }