05黑马QT笔记之自定义槽函数

05黑马QT笔记之自定义槽函数

1 自定义槽函数其实不难,没什么好说的,注意以下几点便可。
自定义参函数注意事项(Qt5):
* 1)自定义槽函数可以是类成员函数(用得最多)、全局普通函数、静态函数。
* 2)槽函数返回值、参数类型要与信号一致(槽函数的尾部可以少于信号 但前面的必须相同)。
* 3)由于信号返回值为空void,所以槽函数也肯定没有返回值。

例子:需要实现:按下close按钮,执行自定义槽函数将按钮的close文本换成hello。released信号表示按钮释放时发送信号。

2 代码实现:
1)项目文件(基本一样):

#-------------------------------------------------
#
# Project created by QtCreator 2020-04-21T21:25:36
#
#-------------------------------------------------

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = 05_SelfDefine_SignalSolt
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)类的头文件:

#ifndef MYWIDGET_H
#define MYWIDGET_H

#include <QWidget>
#include<QPushButton>

class MyWidget : public QWidget
{
    Q_OBJECT

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

    void mySolt();

private:
    QPushButton *b1;
};

#endif // MYWIDGET_H

3)类的实现.cpp文件:

#include "mywidget.h"

MyWidget::MyWidget(QWidget *parent)
    : QWidget(parent)
{
    b1=new QPushButton(this);
    b1->setText("close");

    /*自定义参函数注意事项(Qt5):
     * 1)自定义槽函数可以是类成员函数(用得最多)、全局普通函数、静态函数。
     * 2)槽函数返回值、参数类型要与信号一致(槽函数的尾部可以少于信号 但前面的必须相同)。
     * 3)由于信号返回值为空void,所以槽函数也肯定没有返回值。
    */

    //需要实现:按下close按钮 执行自定义槽函数将close换成hello released信号表示按钮释放时发送信号
    connect(b1,&QPushButton::released,this,&MyWidget::mySolt);

}

//自定义槽函数
void MyWidget::mySolt(){
   b1->setText("hello");
}

MyWidget::~MyWidget()
{

}

4)主函数:

#include "mywidget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MyWidget w;
    w.show();

    return a.exec();
}

发布了54 篇原创文章 · 获赞 1 · 访问量 692

猜你喜欢

转载自blog.csdn.net/weixin_44517656/article/details/105668476
今日推荐