// mysingal.h
#ifndef MYSINGAL_H
#define MYSINGAL_H
#include <QObject>
class MySingal : public QObject
{
Q_OBJECT
public:
explicit MySingal(QObject *parent = nullptr) : QObject(parent) { }
signals:
void TextSingal(int n);
public slots:
};
#endif // MYSINGAL_H
// myslot.h
#ifndef MYSLOT_H
#define MYSLOT_H
#include <QObject>
class MySlot : public QObject
{
Q_OBJECT
public:
explicit MySlot(QObject *parent = nullptr) : QObject(parent) { }
signals:
public slots:
};
#endif // MYSLOT_H
// mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QPushButton>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
bool bAttach = false;
private:
QPushButton* CreateBtn(const QString& btnName, const QSize& sz);
void Close(const QString& btnName, const QSize& sz);
void Switch(const QString& btnName, const QSize& sz, int n);
};
#endif // MAINWINDOW_H
// mainwindow.cpp
#include "mainwindow.h"
#include <QPushButton>
#include "mysingal.h"
#include "myslot.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
setFixedSize(600, 400);
Close("关闭", { 50, 50 });
Switch("输出", { 150, 50 }, 10);
}
MainWindow::~MainWindow()
{
}
QPushButton* MainWindow::CreateBtn(const QString &btnName, const QSize& sz)
{
if(btnName.toUtf8().data() == nullptr) return nullptr;
QPushButton* btn = new QPushButton(btnName, this);
if(!btn) return nullptr;
btn->move(sz.width(), sz.height());
btn->show();
return btn;
}
void MainWindow::Close(const QString& btnName, const QSize& sz)
{
QPushButton* btn = CreateBtn(btnName, sz);
connect(btn, &QPushButton::clicked, this, [this]() {
qDebug() << "CLose my window\n";
close();
});
}
void MainWindow::Switch(const QString& btnName, const QSize& sz, int n)
{
QPushButton* btn = CreateBtn(btnName, sz);
MySingal* pSingal = new MySingal(this);
if(!pSingal) return;
// 将输出按钮与信号关联, 需要捕获this的成员bAttach, 信号对象的地址, 信号函数的参数, 无需传参
connect(btn, &QPushButton::clicked, this, [this, pSingal, n] () mutable {
if(!bAttach) // bAttach为false 按钮无需关联信号函数
{
qDebug() << "*************";
qDebug() << "信号与槽断开连接";
qDebug() << "*************";
}
else // 否则, 发送信号
{
qDebug() << "*************";
qDebug() << "信号发送有参信号";
emit pSingal->TextSingal(n);
}
bAttach = !bAttach; // 反转关联变量的值
});
MySlot* mySlot = new MySlot(this);
if(!mySlot) return;
// 关联信号与槽, 只需传递参数
connect(pSingal, &MySingal::TextSingal, mySlot, [] (int n) mutable {
qDebug() << "槽函数接收到有参信号: " << n;
qDebug() << "*************";
});
}
// main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}