QT 关于信号与槽注意事项

 有些时候信号与槽在连接时需要注意信号函数的参数与槽函数的参数要保持一致。

还有需要注意的是:不要被当前类中新new的窗口所误导。

刚开始时我写了个错误的信号与槽

QObject::connect(log, SIGNAL(sendText(QString)), this, SLOT(showText(QString)));  //错误示范,因为我的信号函数与槽函数都在同一个类里面,所以应该都是this,而不是其它。

 

例如:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDialog>
#include <QPushButton>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QObject::connect(this, SIGNAL(sendText(QString)), this, SLOT(showText(QString)));  //信号与槽连接
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    QDialog *log = new QDialog;
    log->deleteLater();
    log->setMinimumSize(200,200);
    QPushButton *pb = new QPushButton("确定",log);
    connect(pb, &QPushButton::clicked, log, [=](){
        QString str= "hello QT!";
        emit sendText(str);   // 发射信号
    });
    log->exec();
}

void MainWindow::showText(QString sql)
{
    QString sqls = sql;
    qDebug() << sqls;
}
namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

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

signals:
    void sendText(QString);

private slots:
    void on_pushButton_clicked();

    void showText(QString);

private:
    Ui::MainWindow *ui;
};

 

posted on 2020-11-06 16:12  缘随风烬  阅读(229)  评论(0编辑  收藏  举报