qt-C++笔记之使用信号和槽实现跨类成员变量同步响应

发布于:2024-01-25 ⋅ 阅读:(50) ⋅ 点赞:(0)

qt-C++笔记之使用信号和槽实现跨类成员变量同步响应

在这里插入图片描述

—— 杭州 2024-01-24

code review!

1.运行

在这里插入图片描述

2.main.cpp

在这里插入图片描述

代码

#include <QCoreApplication>
#include <QObject>
#include <QDebug>

// MySource 类定义
class MySource : public QObject {
    Q_OBJECT

public:
    MySource() : m_value(0) {}

    void setValue(int value) {
        if (m_value != value) {
            m_value = value;
            emit valueChanged(m_value);
        }
    }

signals:
    void valueChanged(int newValue);

private:
    int m_value;
};

// MyTarget 类定义
class MyTarget : public QObject {
    Q_OBJECT

public slots:
    void onValueChanged(int newValue) {
        qDebug() << "Value changed to:" << newValue;
        m_value = newValue;
        // 这里可以添加其他响应newValue变化的代码
    }

private:
    int m_value;
};

#include "main.moc" // 如果你使用的是qmake,确保这个文件可以被moc工具找到

// 主函数
int main(int argc, char *argv[]) {
    QCoreApplication a(argc, argv);

    MySource source;
    MyTarget target;

    // 将source的valueChanged信号连接到target的onValueChanged槽
    QObject::connect(&source, &MySource::valueChanged, &target, &MyTarget::onValueChanged);

    // 当我们设置source的值时,target的onValueChanged槽将被调用
    source.setValue(10); // target的onValueChanged将被调用,打印"Value changed to: 10"
    source.setValue(20); // target的onValueChanged将被调用,打印"Value changed to: 20"

    return a.exec();
}

3.test.pro

# filename: test.pro
QT       += core
QT       -= gui
TARGET    = test
CONFIG   += console
CONFIG   -= app_bundle
TEMPLATE = app
SOURCES  += main.cpp

4.编译

/usr/lib/qt5/bin/qmake test.pro

make
本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到