zoukankan      html  css  js  c++  java
  • qobject_cast<QPushButton*>(sender()) 简化信号与槽的编写(sender()取得发信号的对象后,就取得了它的全部信息,为所欲为)

    当你觉得写代码是一件重复性极高的工作时,这时你就应该考虑换个方式来实现了。

    提高代码效率,减少代码量。

    代码片:

    [cpp] view plain copy
     
     print?在CODE上查看代码片派生到我的代码片
    1. void Widget::onClicked()  
    2.  {  
    3.     QPushButton* button = qobject_cast<QPushButton*>(sender());  
    4.     QRadioButton* radio = qobject_cast<QRadioButton*>(sender());  
    5.   
    6.     if (button)  
    7.     {  
    8.         QString text = button->text();  
    9.         ui->label_2->setText(text);  
    10.     }  
    11.     else if(radio)  
    12.     {  
    13.         QString text = radio->text();  
    14.         ui->label_2->setText(text);  
    15.     }  
    16.  }  

    实例:

    1、在Qt creator中拖拽出如下界面:

    2、添加槽函数。

    [cpp] view plain copy
     
     print?在CODE上查看代码片派生到我的代码片
    1. private slots:  
    2.     void onClicked();  

    3、添加信号与槽的关联。

    [cpp] view plain copy
     
     print?在CODE上查看代码片派生到我的代码片
    1. connect(ui->pushButton,SIGNAL(clicked(bool)),this,SLOT(onClicked()));  
    2. connect(ui->pushButton_2,SIGNAL(clicked(bool)),this,SLOT(onClicked()));  
    3. connect(ui->pushButton_3,SIGNAL(clicked(bool)),this,SLOT(onClicked()));  
    4. connect(ui->pushButton_4,SIGNAL(clicked(bool)),this,SLOT(onClicked()));  
    5.   
    6. connect(ui->radioButton,SIGNAL(clicked(bool)),SLOT(onClicked()));  
    7. connect(ui->radioButton_2,SIGNAL(clicked(bool)),SLOT(onClicked()));  
    8. connect(ui->radioButton_3,SIGNAL(clicked(bool)),SLOT(onClicked()));  
    9. connect(ui->radioButton_4,SIGNAL(clicked(bool)),SLOT(onClicked()));  

    4、实现槽函数。

    [cpp] view plain copy
     
     print?在CODE上查看代码片派生到我的代码片
    1. void Widget::onClicked()  
    2.  {  
    3.     QPushButton* button = qobject_cast<QPushButton*>(sender());  
    4.     QRadioButton* radio = qobject_cast<QRadioButton*>(sender());  
    5.   
    6.     if (button)  
    7.     {  
    8.         QString text = button->text();  
    9.         ui->label_2->setText(text);  
    10.     }  
    11.     else if(radio)  
    12.     {  
    13.         QString text = radio->text();  
    14.         ui->label_2->setText(text);  
    15.     }  
    16.  }  

    5、运行截图:

    当然了,这里我只是举个例子,在实际的应用中大家可以扩展其功能的。

    http://blog.csdn.net/rl529014/article/details/52144009

  • 相关阅读:
    关于两次指针(struct型)传参数的问题
    git学习基础教程
    程序员恶性循环- 有感
    基于Tomcat 的WEB Project存在的安全漏洞总结
    使用Maven自动部署Java Web项目到Tomcat问题小记
    MyEclipse中Maven的配置
    mybatis处理集合、循环、数组和in查询等语句的使用
    JBOSS的启动和停止
    myeclipse越来越卡了怎么回事啊?
    linux shell 模拟post请求
  • 原文地址:https://www.cnblogs.com/findumars/p/5979098.html
Copyright © 2011-2022 走看看