1: 写一个 close 按钮当单击此按钮时就执行槽函数, 而关闭窗口.
- 1 #include "slot.h"
- 2 #include <QApplication>
- 3 #include<QPushButton>
- 4 #include
- 5 #ifndef SLOT_H
- 6 #define SLOT_H
- 7 #include <QMainWindow>
- 8 #include <QObject>
- 9 #include <QWidget>
- 10 class Slot : public QWidget
- 11 {
- 12 Q_OBJECT
- 13 public:
- 14 explicit Slot(QWidget *parent = nullptr);
- 15 Slot(const Slot &);
- 16 Slot &operator=(const Slot &);
- 17 ~Slot();
- 19 signals:
- 21 public slots:
- 23 private:
- 24 QSharedDataPointer<SlotData> data;
- 25 };
- 26 class SlotData : public QSharedData
- 27 {
- 28 public:
- 30 };
- 31 Slot::Slot(QWidget *parent) : QWidget(parent), data(new SlotData) //Slot 的构造函数.
- 32 {
- 33 QPushButton *btn = new QPushButton; //new 关键字是 c++ 动态分配那一节讲的.
- 34 btn->setParent(this); //this 代表 QWidget 对象.
- 35 btn->setText("close");
- 36 QPushButton *btn1;
- 37 connect(&btn,&QPushButton::pressed,this,&Slot::close);
- 38 /*
- 39 * &btn: 信号发出者.
- 40 * &QPushButton::pressed: 指明 btn 在遇到用户给的 presses 的信号时才给 this(Slot 类的对象) 发出信号让 this 执行槽函数.
- 41 * this: 信号的承受者也就是被执行者.
- 42 * close: 为槽函数,
- 43 */
- 44 /*
- 45 * 自定义信号和槽, 普通函数的用法
- 46 * Qt: 任意的成员函数, 普通全局函数, 静态函数.
- 47 * 槽函数需要和信号一致 (参数, 返回值)
- 48 * 由于信号都是没有返回值, 使用槽函数一定没有返回值.
- 49 *
- 50 */
- 51 }
- 52 Slot::~Slot() //Slot 的析构函数.
- 53 {
- 55 }
来源: http://www.bubuko.com/infodetail-3409500.html