Qt中QObject::sender()的用法

qlonglong YHHttp::get(QString url, int timeout)
{
    QUrl u = QUrl::fromUserInput(url);
    if(u.path().isEmpty()){
        u.setPath("/");
    }
    QNetworkRequest request(u);
    setheader(&request);

    QNetworkReply *reply = d->manager.get(request);

    connect(reply, SIGNAL(finished()),
            this, SLOT(slotFinished()));

    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)),
            this, SLOT(slotError(QNetworkReply::NetworkError)));

    if(timeout!=0){
        QTimer* timer = new QTimer(reply);
        connect(timer,SIGNAL(timeout()),this,SLOT(slot_requestTimeout()));//超时信号
        timer->start(timeout);

    }
    return (qlonglong)reply;
}


void YHHttp::slot_requestTimeout()
{
    QNetworkReply *reply = static_cast<QNetworkReply*>(sender()->parent());
    emit_deviceevent("Timeout(qlonglong)", (qlonglong)(reply));
    reply->abort();
    reply->deleteLater();
    QNetworkSession(d->manager.configuration()).stop();
}
View Code

这里通过sender()获得了触发slot_reequestTimeout()槽函数信号的对象。

解释如下:

当某个Object,emit一个signal的时候,这个Object就是这个sender,系统会记录当前emit这个signal的Object。所以当你

在对应的slot中,通过sender()可以得到当前是谁触发了你的slot。

另外这里需要获取的是QNetworkReply对象,这个对象传给QTimer的时候变成了timer的parent。

 

posted @ 2019-10-31 10:32  蓦然而然  阅读(2314)  评论(0编辑  收藏  举报