当前位置:   article > 正文

Qt Creator:初识信号与槽_qtcreator 槽函数 接受者

qtcreator 槽函数 接受者

Qt使用信号和槽机制来完成对象之间的协同操作,说白了就是这边发射一个信号(操作),那边接受信号,并完成操作。好比我让你干什么事,你接到命令后就去干这个事。我们需要做以下几步。**首先头文件中声明这个槽函数,然后在.cpp文件中定义这个槽函数,也就是把需要做什么事这个活动内容写下来,最后在.cpp文件中的构造函数里面连接信号与槽,用connect()函数。**下面粘贴两端代码:

自动连接,不需要connect(),但是槽函数名需要设置成,举例:on_函数名_clicked
.h

#ifndef MYWIDGET_H
#define MYWIDGET_H


#include <QWidget>


namespace Ui {
class MyWidget;
}


class MyWidget : public QWidget
{
    Q_OBJECT


public:
    explicit MyWidget(QWidget *parent = 0);
    ~MyWidget();


private:
    Ui::MyWidget *ui;


public slots:
    void on_showChildButton_clicked();


};


#endif // MYWIDGET_H

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35

.cpp

#include "mywidget.h"
#include "ui_mywidget.h"
#include <QDialog>


MyWidget::MyWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MyWidget)
{
    ui->setupUi(this);
}


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


void MyWidget::on_showChildButton_clicked()
{
    QDialog *dialog = new QDialog(this);
    dialog->show();
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

手动连接:需要connect()
.h

#ifndef MYWIDGET_H
#define MYWIDGET_H


#include <QWidget>


namespace Ui {
class MyWidget;
}


class MyWidget : public QWidget
{
    Q_OBJECT


public:
    explicit MyWidget(QWidget *parent = 0);
    ~MyWidget();


private:
    Ui::MyWidget *ui;
//声明槽
public slots:
    void showChildDialog();


};


#endif // MYWIDGET_H

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34

.cpp

#include "mywidget.h"
#include "ui_mywidget.h"
#include <QDialog>


MyWidget::MyWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MyWidget)
{//构造函数
    ui->setupUi(this);
    connect(ui->showChildButton, &QPushButton::clicked,
            this, &MyWidget::showChildDialog);//信号和槽连接
}


MyWidget::~MyWidget()
{//析构函数
    delete ui;//释放
}


void MyWidget::showChildDialog()
{//函数内容
    QDialog *dialog = new QDialog(this);
    dialog->show();
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/一键难忘520/article/detail/786274
推荐阅读
相关标签
  

闽ICP备14008679号