×
Namespaces

Variants
Actions

Opening a network connection in Qt

From Nokia Developer Wiki
Jump to: navigation, search

This code snippet demonstrates how to open a network connection in Qt using the Bearer Management module. In Symbian this will prevent the native IAP dialog from opening every time an application does a network request.

In Qt 4.7, the Bearer API has been migrated to the QtNetwork library. For Qt earlier than 4.7, the Bearer API is part of Qt Mobility.

Article Metadata
Tested with
Devices(s): Nokia N97, Nokia N900
Compatibility
Platform(s): S60 5th Edition
Maemo 5
Symbian
S60 5th Edition
Article
Keywords: QNetworkConfigManager, QNetworkSession
Created: tepaa (21 May 2010)
Last edited: hamishwillee (18 Oct 2012)

Contents

Qt project file

# Qt libraries
QT += core gui network
 
# Link Bearer Qt Mobility module into project, for Qt earlien than 4.7. If the Qt version is 4.7, this step is not necessary.
CONFIG += mobility
MOBILITY = bearer
symbian: {
TARGET.CAPABILITY = NetworkServices ReadUserData
}

Header

#include <QtGui/QMainWindow>
#include <QPointer>
#include <qnetworkinterface.h> // have to be "QT += network" in pro file
 
#include <QTimer>
#include <QMessageBox>
 
// QtMobility
#include <qnetworkconfigmanager.h>
#include <qnetworksession.h>
 
// this is not necessary for Qt 4.7
QTM_USE_NAMESPACE
 
class qtSnippets : public QMainWindow
{
Q_OBJECT
 
public:
qtSnippets(QWidget *parent = 0);
~qtSnippets();
 
private slots:
// Open network connection
void openConnection();
 
private:
// Session of the connection
QPointer<QNetworkSession> m_session;
};

Source

#include <QTimer>
#include <QMessageBox>
 
qtSnippets::qtSnippets(QWidget *parent)
: QMainWindow(parent)
{
// Let application to startup fully and then
// open connection to the network
QTimer::singleShot(0, this, SLOT(openConnection()));
}
 
qtSnippets::~qtSnippets()
{
// Remeber to close connection
if (m_session)
m_session->close();
}
 
void qtSnippets::openConnection()
{
// Set Internet Access Point
QNetworkConfigurationManager manager;
 
const bool canStartIAP = (manager.capabilities()
& QNetworkConfigurationManager::CanStartAndStopInterfaces);
 
// Is there default access point, use it
QNetworkConfiguration cfg = manager.defaultConfiguration();
if (!cfg.isValid() || !canStartIAP) {
// Available Access Points not found
QMessageBox::information(this,"Bearer","Available Access Points not found");
return;
}
 
// Open session
m_session = new QNetworkSession(cfg);
m_session->open();
// Waits for session to be open and continues after that
m_session->waitForOpened();
 
// Show interface name to the user
QNetworkInterface iff = m_session->interface();
QMessageBox::information(this,"Network opened",iff.humanReadableName());
}

Postconditions

A network connection has been opened.

See also

This page was last modified on 18 October 2012, at 01:06.
84 page views in the last 30 days.