04黑马QT笔记之标准信号和槽(系统自带的信号和槽函数)
1 同样的先创建基类是QWidget的基类。以后不说基本都是。
2 总结:书写connect函数的注意事项:
1)四个参数均为地址类型 。
2)系统信号与槽函数好像都不带"()"(记忆:函数名代表首地址)
3) 信号没有返回值。
3 代码实现:
1)项目文件:
#-------------------------------------------------
#
# Project created by QtCreator 2020-04-21T20:25:37
#
#-------------------------------------------------
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = 04_SignalAndSolt
TEMPLATE = app
# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += main.cpp\
mywidget.cpp
HEADERS += mywidget.h
2)头文件.h:
#ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>
#include<QPushButton>
class MyWidget : public QWidget
{
Q_OBJECT
public:
MyWidget(QWidget *parent = 0);
~MyWidget();
private:
QPushButton b1; //对象
QPushButton *b2; //指针需要new
};
#endif // MYWIDGET_H
3)类的.cpp文件:
#include "mywidget.h"
MyWidget::MyWidget(QWidget *parent): QWidget(parent)
{
/* 局部变量 当在主函数执行w.show()时是空白 因为被释放了 所以将其设为成员变量
QPushButton b1("close");
b1.setParent(this);
*/
//按钮1
b1.setParent(this);
b1.setText("close");
connect(&b1,&QPushButton::clicked,this,MyWidget::close);
//按钮2
b2=new QPushButton(this); //new一个按钮对象并指定父对象为当前窗口this 并且指定父对象的不用手动delete(系统做)
b2->setText("close2");
b2->move(100,100);
connect(b2,&QPushButton::clicked,this,&MyWidget::close);
}
//总结:书写connect函数的注意事项: 1)四个参数均为地址类型 2)系统信号与槽函数好像都不带"()"(记忆:函数名代表首地址) 3)信号没有返回值
MyWidget::~MyWidget()
{
}
4)主函数.cpp文件:
#include "mywidget.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MyWidget w; //程序从mian执行 肯定会执行到窗口对象的构造 为了避免主函数过多业务 所以将功能写在构造函数中
w.show();
return a.exec();
}