多个信号对应单个槽的实现

      利用多个信号对应一个槽函数,这样就不用每一个信号都设一个槽函数那么麻烦了。

       假设定义个多个QLineEdit,要读其中的数字:

首先在头文件中定义一个槽函数:

private slots:
     void on_val_returnPressed();

在相应的源文件中连接信号与槽函数:

    connect(val_v,SIGNAL(returnPressed()),this,SLOT(on_val_returnPressed()));
    connect(val_w,SIGNAL(returnPressed()),this,SLOT(on_val_returnPressed()));
    connect(ia1,SIGNAL(returnPressed()),this,SLOT(on_val_returnPressed()));
    connect(ia2,SIGNAL(returnPressed()),this,SLOT(on_val_returnPressed()));
    connect(ia3,SIGNAL(returnPressed()),this,SLOT(on_val_returnPressed()));
    connect(ia4,SIGNAL(returnPressed()),this,SLOT(on_val_returnPressed()));
    connect(ia5,SIGNAL(returnPressed()),this,SLOT(on_val_returnPressed()));
    connect(ia6,SIGNAL(returnPressed()),this,SLOT(on_val_returnPressed()));
    connect(val_Sr,SIGNAL(returnPressed()),this,SLOT(on_val_returnPressed()));
    connect(val_Spr,SIGNAL(returnPressed()),this,SLOT(on_val_returnPressed()));

都对应的是on_val_returnPressed()函数。

重点时在槽函数中怎么识别是哪个控件发出的信号:

void ProRobotics::on_val_returnPressed()
{
    QLineEdit *lEdit = dynamic_cast<QLineEdit*>(sender());//这里dynamic_cast,用qobject_cast,static_cast都可,具体区别以后在说
    if(lEdit == val_v)
    {
        QString sVd = val_v->text();
        Vd          = sVd.toFloat();
    }
    if(lEdit == val_w)
    {
        QString sWd = val_w->text();
        Wd          = sWd.toFloat();
    }
    if(lEdit == ia1)
    {
        QString sa1 = ia1->text();
        a1          = sa1.toFloat();
    }
    if(lEdit == ia2)
    {
        QString sa2 = ia2->text();
        a2          = sa2.toFloat();
    }
    if(lEdit == ia3)
    {
        QString sa3 = ia3->text();
        a1          = sa3.toFloat();
    }
    if(lEdit == ia4)
    {
        QString sa4 = ia4->text();
        a4          = sa4.toFloat();
    }
    if(lEdit == ia5)
    {
        QString sa5 = ia5->text();
        a5          = sa5.toFloat();
    }
    if(lEdit == ia6)
    {
        QString sa6 = ia6->text();
        a6          = sa6.toFloat();
    }
    if(lEdit == val_Sr)
    {
        QString ssigma_r   = val_Sr->text();
        sigma_r            = ssigma_r.toFloat();
    }
    if(lEdit == val_Spr)
    {
        QString ssigma_phi  = val_Spr->text();
        sigma_phi           = ssigma_phi.toFloat();
    }

}




你可能感兴趣的:(qt,多个信号,槽函数)