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

  • 相关阅读:
    Safe3TV
    LINQ 對付 SQL Injection 的 "免費補洞策略"
    Sstart(一个批量运行的小工具)
    从CSDN 漏洞谈.NET 安全开发
    看大成天下网站安全
    discuz获取任意管理员密码漏洞利用工具vbs版
    Wfuzz(支持各种web漏洞扫描的工具)
    Apache Tomcat UTF8编码漏洞
    VS2010下如何调试Framework源代码(即FCL)
    《Practical Clojure》学习笔记[3] Clojure中程序流程控制
  • 原文地址:https://www.cnblogs.com/findumars/p/5979098.html
Copyright © 2011-2022 走看看