• 3、信号与槽


    connect(&对象,&对象类型::信号,&对象,&对象类型::槽函数)

    如:connect(&b1,&QPushButton::pressed,this,&MyWidget::close); //都是取地址,this是指针,直接指向地址

    1、信号:signals关键字。

    2、槽函数:类中任意成员函数,静态函数、全局函数、lambda表达式等。

    3、信号、槽,没有返回值,可以有参数。参数列表顺序必须一致,信号参数个数≥槽参数个数。

    4、信号、槽连接,可以一对一、一对多、多对一。信号也可以连接信号。连接成功后,可以断开disconnect。

    5、一个信号连接多个槽函数时,槽函数的执行顺序随机不可控。

    举例:按钮b1,关闭窗体。按钮b2,改变自身文本、隐藏b1

    新建项目,QWidget类,不勾选ui

    头文件:

    #ifndef MYWIDGET_H
    #define MYWIDGET_H
    
    #include <QWidget>
    #include <QPushButton> //引入按钮
    
    class MyWidget : public QWidget
    {
        Q_OBJECT
    
    public:
        MyWidget(QWidget *parent = 0);
        ~MyWidget();
        void mySlot(); //自定义的槽函数
    private:
        QPushButton b1; //创建对象
        QPushButton *b2;
    };
    
    #endif // MYWIDGET_H

    源文件:

    #include "mywidget.h"
    
    MyWidget::MyWidget(QWidget *parent)
        : QWidget(parent)
    {
        b1.setParent(this);//指定父对象,方法一
        b1.setText("按钮1");
        b1.move(100,100);
        //指定父对象,方法二
        b2=new QPushButton(this); //指针需要动态分配空间
        b2->setText("按钮2");
        //信号、槽(系统再带的函数)
        connect(&b1,&QPushButton::pressed,this,&MyWidget::close);//b1按下,关闭窗体
        //信号、槽(自定义的函数)
        connect(b2,&QPushButton::pressed,this,&MyWidget::mySlot);//b2按下,b2内容改变
        connect(b2,&QPushButton::released,&b1,&QPushButton::hide);//b2抬起,b1隐藏
    }
    
    void MyWidget::mySlot()//自定义的槽函数
    {
        b2->setText("被更改");
    }
    
    MyWidget::~MyWidget()
    {
    
    }

    主程序:

    #include "mywidget.h"
    #include <QApplication>
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        MyWidget w;//执行MyWidget类内的程序
        w.show();
    
        return a.exec();
    }
  • 相关阅读:
    VisionPro CogCreateCircleTool工具
    VisionPro CogPDF417Tool工具
    VisionPro CogBarcodeTool工具
    VisionPro Cog2DSymbolVerifyTool工具
    VisionPro Cog2DSymbolTool工具 读码工具
    VisionPro CogToolBlock输入输出终端
    VisionPro CogCompositeColorMatchTool
    VisionPro CogColorSegmenterTool
    VisionPro CogColorMatchTool
    VisionPro CogColorExtractorTool工具功能
  • 原文地址:https://www.cnblogs.com/xixixing/p/10897376.html
Copyright © 2020-2023  润新知