Qt 的信号与槽

来源:互联网 发布:数据统计免费软件 编辑:程序博客网 时间:2024/05/21 06:43

QT的信号与槽的三种实现方式

3种方式:

1:直接在设计选项卡中拖动连接控件,然后选择控件间的关联函数

2:头文件mainwindows.h中:

#ifndef MAINWINDOW_H#define MAINWINDOW_H#include <QMainWindow>#include <QMessageBox>namespace Ui {class MainWindow;}class MainWindow : public QMainWindow{    Q_OBJECTpublic:    explicit MainWindow(QWidget *parent = 0);    ~MainWindow();private slots:    void on_calButton_clicked();private:    Ui::MainWindow *ui;};#endif // MAINWINDOW_H

其中

private slots:    void on_calButton_clicked();

就是使用“元对象系统(meta-object system)”自动进行创建信号与槽的关联性动作,on表示动作,calButton是空间类名,clicked是绑定的信号事件。这种情况我们只需要在涉及窗口手动添加>

我们只需要在mainwindows.cpp中实现对应控件中,右键选择转到槽,即可自动帮你创建好上面的函数,我们只需要实现内容即可。

void MainWindow::on_calButton_clicked(){    int fNumInt = ui->firstLineEdit->text().toInt();    int sNumInt = ui->secondLineEdit->text().toInt();    ui->resultLineEdit->setText(QString::number(rNum));}

3:使用代码手动关联信号与槽系统

首先需要在头文件mainwindows.h中添加自己的solt:

#ifndef MAINWINDOW_H#define MAINWINDOW_H#include <QMainWindow>#include <QMessageBox>namespace Ui {class MainWindow;}class MainWindow : public QMainWindow{    Q_OBJECTpublic:    explicit MainWindow(QWidget *parent = 0);    ~MainWindow();private slots:    void calSlot(); //名字可以随意取private:    Ui::MainWindow *ui;};#endif // MAINWINDOW_H

然后在mainwindows.cpp中加入对应的槽方法:

void MainWindow::calSlot(){    int fNumInt = ui->firstLineEdit->text().toInt();    int sNumInt = ui->secondLineEdit->text().toInt();    ui->resultLineEdit->setText(QString::number(rNum));}

最后,我们需要关联控件的点击事件和槽方法:

mainwindows.cpp中添加

MainWindow::MainWindow(QWidget *parent) :    QMainWindow(parent),    ui(new Ui::MainWindow){    ui->setupUi(this);  //------新加入部分----//   QObject::connect(ui-callButton,SIGNAL(clicked()),this,SLOT(calSlot()));//关联信号与槽  }  

这三种办法均可。

0 0