QSignalMapper的使用

QSignalMapper的使用

1. 可以把无参数的信号转换为带int参数、带QString参数、带QObject参数、带QWidget参数的信号,

假如Qwidget上有许多Button,如果一一建立信号槽,显得繁琐,这时我们可以使用QSignalMapper

[cpp]  view plain  copy
  1. #include "MainWindow.h"  
  2. #include "ui_MainWindow.h"  
  3. #include <QHBoxLayout>  
  4. #include <QVBoxLayout>  
  5. #include <QString>  
  6. #include <QStringList>  
  7. #include <QGridLayout>  
  8. #include <QPushButton>  
  9. #include <QLineEdit>  
  10. #include <QSignalMapper>  
  11.   
  12. MainWindow::MainWindow(QWidget *parent) :  
  13.     QMainWindow(parent),  
  14.     ui(new Ui::MainWindow)  
  15. {  
  16.     ui->setupUi(this);  
  17.     init();  
  18. }  
  19.   
  20. MainWindow::~MainWindow()  
  21. {  
  22.     delete ui;  
  23. }  
  24.   
  25. void MainWindow::init()  
  26. {  
  27.     QGridLayout *pLayout = new QGridLayout();  
  28.     this->centralWidget()->setLayout(pLayout);  
  29.   
  30.     QString str = "Button1,Button2,Button3,Button4,Button5,Button6,Button7,Button8";  
  31.     QStringList strList = str.split(",");  
  32.     QSignalMapper *pMapper = new QSignalMapper();  
  33.   
  34.     for (int i = 0; i < strList.length(); ++i)  
  35.     {  
  36.         QPushButton *pBtn = new QPushButton;  
  37.         pBtn->setText(strList.at(i));  
  38.   
  39.         connect(pBtn, SIGNAL(clicked()), pMapper, SLOT(map()));   
  40.         pMapper->setMapping(pBtn, pBtn->text());  
  41.   
  42.   
  43.         pLayout->addWidget(pBtn, i, 0);  
  44.   
  45.     }  
  46.     QLineEdit *pEdit = new QLineEdit();  
  47.     connect(pMapper, SIGNAL(mapped(QString)), pEdit, SLOT(setText(QString)));  
  48.     pLayout->addWidget(pEdit, 0, 1);  
  49.   
  50. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值