qt-C++笔记之使用信号和槽实现跨类成员变量同步响应
—— 杭州 2024-01-24
code review!
文章目录
- qt-C++笔记之使用信号和槽实现跨类成员变量同步响应
- 1.运行
- 2.main.cpp
- 3.test.pro
- 4.编译
1.运行
2.main.cpp
代码
#include <QCoreApplication>
#include <QObject>
#include <QDebug>// MySource 类定义
class MySource : public QObject {Q_OBJECTpublic: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_OBJECTpublic 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.promake