当前位置: 首页 > article >正文

qt 重载信号,使用““方式进行connect()调用解决方案

问题

在Qt中,重载的信号默认是无法使用&这种方式调用的。
因为&只能绑定到一个具体的信号,而重载的信号名称相同,编译器无法确定要绑定哪一个信号。

解决方案

如果非要使用&绑定重载的信号,可以使用函数指针进行转换,指定参数类型和个数,例如:

signals:
    void sendMsg(int n);
    void sendMsg(QString str);

    connect(this, static_cast<void (MainWindow::*)(const int)>(&MainWindow::sendMsg), this, [=](int n){
        qDebug().noquote() << "[" << __FILE__ << __LINE__ << "]" << "n :" << n;
    });

    connect(this, static_cast<void (MainWindow::*)(const QString)>(&MainWindow::sendMsg), this, [=](QString str){
        qDebug().noquote() << "[" << __FILE__ << __LINE__ << "]" << "str :" << str;
    });

示例

.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

signals:
    void sendMsg(int n);
    void sendMsg(QString str);


private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QDebug>

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

    connect(this, static_cast<void (MainWindow::*)(const int)>(&MainWindow::sendMsg), this, [=](int n){
        qDebug().noquote() << "[" << __FILE__ << __LINE__ << "]" << "n :" << n;
    });

    connect(this, static_cast<void (MainWindow::*)(const QString)>(&MainWindow::sendMsg), this, [=](QString str){
        qDebug().noquote() << "[" << __FILE__ << __LINE__ << "]" << "str :" << str;
    });

    emit sendMsg(1);
    emit sendMsg("helloworld");
}

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

main.cpp

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

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

    return a.exec();
}

结果

在这里插入图片描述


http://www.kler.cn/news/134081.html

相关文章:

  • 【算法与数据结构】前言
  • WPF中如何在MVVM模式下关闭窗口
  • 【0到1学习Unity脚本编程】第一人称视角的角色控制器
  • 技术贴 | SQL 执行 - 执行器优化
  • 【六袆 - MySQL】SQL优化;Explain SQL执行计划分析;
  • WPF位图效果
  • 详解ssh远程登录服务
  • 基于卡尔曼滤波实现行人目标跟踪
  • 【广州华锐互动VRAR】VR元宇宙技术在气象卫星知识科普中的应用
  • 什么是AIGC
  • JS原生-弹框+阿里巴巴矢量图
  • 【论文阅读笔记】Supervised Contrastive Learning
  • 小迪笔记(1)——操作系统文件下载反弹SHELL防火墙绕过
  • 疑似openAI的BUG
  • 结构体——C语言初阶
  • 飞天使-django之数据库简介
  • 汽车 CAN\CANFD数据记录仪
  • 【LeetCode刷题-树】--1367.二叉树中的链表
  • 什么是PWA(Progressive Web App)?它有哪些特点和优势?
  • spark算子简单案例 - Python
  • 关于DBMS_STATS.GATHER_DATABASE_STATS_JOB_PROC的一些发现
  • 自学嵌入式,已经会用stm32做各种小东西了
  • 小米路由器AX1800降级后的SSH登录和关墙等命令
  • 【数据结构(二)】队列(2)
  • centos7安装mongodb
  • Cross-View Transformers for Real-Time Map-View Semantic Segmentation 论文阅读
  • 木子-前端-方法标签属性小记(普通jsp/html篇)2023~2024
  • Redis为什么是单线程的?Redis性能为什么很快?
  • psql 模式(SCHEMA)
  • ICCV 23丨3D-VisTA:用于 3D 视觉和文本对齐的预训练Transformer