一、说明
向百度发送请求,判断是否连接网络,使用定时器,每五秒检测一次,由于会影响主界面,将其添加进子线程
二、代码
代码如下(示例):
//NetworkTester.h #pragma once #include <QtCore> #include <QtNetwork> class NetworkTester : public QObject { Q_OBJECT public: NetworkTester(QObject *parent = nullptr) : QObject(parent) { testNetworkStatus(); } public slots: void testNetworkStatus() { QNetworkAccessManager *manager = new QNetworkAccessManager(this); QNetworkRequest request(QUrl("http://www.baidu.com/")); QNetworkReply *reply = manager->get(request); QObject::connect(reply, &QNetworkReply::finished, [this, reply, manager]() { bool status = false; if (reply->error() == QNetworkReply::NoError) { status = true; } emit networkStatusChanged(status); reply->deleteLater(); manager->deleteLater(); }); } signals: void networkStatusChanged(bool status); };
//NetWorkCheck.h #pragma once #include <QtWidgets/QMainWindow> #include "ui_NetWorkCheck.h" #include "NetworkTester.h" #include <QDebug> #include <QTimer> class NetWorkCheck : public QMainWindow { Q_OBJECT public: NetWorkCheck(QWidget *parent = nullptr); ~NetWorkCheck(); private: Ui::NetWorkCheckClass ui; NetworkTester *tester; QTimer *timer; };
//NetWorkCheck.cpp #include "NetWorkCheck.h" NetWorkCheck::NetWorkCheck(QWidget *parent) : QMainWindow(parent) { ui.setupUi(this); tester = new NetworkTester(this); QThread *thread = new QThread; tester->moveToThread(thread); thread->start(); timer = new QTimer(this); QObject::connect(timer, &QTimer::timeout, tester, &NetworkTester::testNetworkStatus); QObject::connect(tester, &NetworkTester::networkStatusChanged, [](bool status) { if (status) { qDebug() << "Network is available."; } else { qDebug() << "Network is not available."; } }); timer->start(5000); } NetWorkCheck::~NetWorkCheck() {}
//main.cpp #include "NetWorkCheck.h" #include <QtWidgets/QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); NetWorkCheck w; w.show(); return a.exec(); }
推荐一个零声学院项目课,个人觉得老师讲得不错,分享给大家:
零声白金学习卡(含基础架构/高性能存储/golang云原生/音视频/Linux内核)
https://xxetb.xet.tech/s/VsFMs