学习一:Qt中Connect和多线程

目录

1、信号与槽

1.1 举例:在同一个cpp文件中。

1.2 举例:在不同cpp文件中。

1.3 断开连接

2、多线程

2.1 公共函数

2.2 信号与槽

2.3 静态函数

2.4 保护功能

2.5 静态保护成员

3.6 举例

1、信号与槽

        在Qt中connect函数主要用来建立信号与槽函数。通过信号与槽函数机制可以实现不同线程之间的数据传输(不止这一种方式,这里就单描述信号与槽)。

        因为在Qt中,通常是主线程对窗口进行赋值,子线程不能直接对窗口的数据进行操作,这里connect函数就尤为重要。

QMetaObject::Connection QObject::connect(const QObject *sender, const char *signal, const QObject *receiver, const char *method, Qt::ConnectionType type = Qt::AutoConnection)
参数1:信号发射者;

参数2:信号发射者的信号;

参数3:信号接收者;

参数4:执行的槽函数
connect(spinNum, SIGNAL((valueChangedint)), this, SLOT(updateStatus(int)));

QMetaObject::Connection QObject::connect(const QObject *sender, const QMetaMethod &signal, QObject *receiver, const QMetaMethod &method, Qt::ConnectionType type = Qt::AutoConnection)

参数1:信号发射者;

参数2:信号发射者的信号;

参数3:信号接收者;

参数4:执行的槽函数
connect(lineEdit, &QLineEdit::textChanged, this, &widget::on_textChanged)

1.1 举例:在同一个cpp文件中。

// 在.h 文件中
signals:
    void starting(int num);        //定义一个信号
private slots:
    void statPushbutton();        // 定义一个槽函数
// 在.cpp文件中
connect(ui->start, &QPushButton::clicked, this, &Widget::statPushbutton);    // 事件1
connect(this, &Widget::starting, this, &Widget::emitStarting);               // 事件2

void Widget::statPushbutton()
{
    emit starting(10000);
    qDebug() << "事件1" << endl;
}

void Widget::emitStarting()
{
    qDebug() << "事件2" << endl;
}

/****************** 注释

事件1:在ui中有一个名叫start控件的按键,当点击事件触发后,执行statPushbutton槽函数。
事件2:当starting信号发射出来后,事件2被触发,响应槽函数emitStarting。打印显示事件2

*******************/

1.2 举例:在不同cpp文件中。

/**** 
    主线程中,通过按键来触发信号的发送,然后在新建的cpp中获取到发送的信号,并显示传输的数据值,
打印出来后触发一个信号,让主线程来获取这个信号,实现槽函数功能打印发送的数据。
****/

// 主线程.h中
signals:
    void starting(int num);        // 信号

private slots:
    void statPushbutton();         // 一个槽函数

// 主线程.cpp中
Generte* gen = new Generte;     //实例化薪cpp文件的对象

connect(ui->start, &QPushButton::clicked, this, &Widget::statPushbutton);    // 连接按键触发槽函数
connect(this, &Widget::starting, gen, &Genertae::recvNum);    // 连接到新的cpp中的槽函数
connect(gen, &Genertae::SendNum, this, &Widget::recvNum)

void Widget::statPushbutton()
{
    emit starting(500);
    gen->start();
}
void Widget::recvNum(int num)
{
   qDebug() << "获取 Genertae发送的数据" << m_num << endl;
}

/******************************** 新建的.h 和 .cpp **********************************/
// .h中
class Genertae : public QObject {

public:
    void recvNum(int num);
signals:
    void S

你可能感兴趣的:(Qt,qt,开发语言)