C

Getting Started with B2Qt.Wifi in C++

Preparing the Application

Use the following include statement to access the C++ classes:

#include <B2QtWifi>

Before building your application, add the following statement to your .pro file to link against the B2Qt.Wifi library:

QT += b2qtwifi

This guide will demonstrate how to create a Qt Widget-based application that utilizes the B2Qt.Wifi API to set up a wifi network connection. We will start by looking at how to scan for wifi access points, and how to display and process this data in the application. At the end of the guide we will show how to connect directly to a known wifi network configuration.

Listing Wifi Networks

First we need to set up QListView widget which we will use to list wifi networks that can be detected by the device. The detected network access points are packed as a list-based data model and can be retrieved using QWifiManager::networks. Here we also set a custom item delegate and connect to two QWifiManager signals.

WifiSettings(QWidget *parent = 0)
    : QWidget(parent)
    , m_listView(new QListView(this))
    , m_networkDelegate(new NetworkDelegate(this))
{
    m_wifiManager = QWifiManager::instance();
    m_listView->setModel(m_wifiManager->networks());
    m_listView->setItemDelegate(m_networkDelegate);

    connect(m_wifiManager, &QWifiManager::backendStateChanged,
            this, &WifiSettings::handleBackendStateChanged);
    connect(m_wifiManager, &QWifiManager::networkStateChanged,
            this, &WifiSettings::handleNetworkStateChanged);

    setupWidgets();
}

Creating a Delegate

The Wifi network model has many data roles that describe the different properties of Wifi network. This data can be used by an application to list detailed network information and/or to create QWifiConfiguration objects. In this example we are interested in the network name. In the paint() method we check if the network name is equal to the currently active network connection, and append appropriate network state information.

public:
    NetworkDelegate(QObject *parent = 0)
        : QStyledItemDelegate(parent)
    {
        m_wifiManager = QWifiManager::instance();
    }

    void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
    {
        QStyledItemDelegate::paint(painter, option, index);
        painter->save();
        QString ssid = qvariant_cast<QString>(index.data(QWifiManager::SSID));
        if (ssid == m_wifiManager->currentSSID())
            ssid += networkStateText();
        painter->drawText(option.rect, Qt::AlignVCenter, ssid);
        painter->restore();
    }

    QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
    {
        QFont font = QApplication::font();
        QFontMetrics fm(font);
        return QSize(option.rect.width(), fm.height() * 2);
    }

protected:
    QString networkStateText() const
    {
        QWifiManager::NetworkState networkState = m_wifiManager->networkState();
        switch (networkState) {
        case QWifiManager::Disconnected:
            return QStringLiteral("");
            break;
        case QWifiManager::Authenticating:
            return QStringLiteral(" (authenticating)");
            break;
        case QWifiManager::HandshakeFailed:
            return QStringLiteral(" (handshake failed)");
            break;
        case QWifiManager::ObtainingIPAddress:
            return QStringLiteral(" (obtaining IP address)");
            break;
        case QWifiManager::DhcpRequestFailed:
            return QStringLiteral(" (dhcp request failed)");
            break;
        case QWifiManager::Connected:
            return QStringLiteral(" (connected)");
            break;
        }
    }

Connecting to a Selected Network

On press of the Connect button, connetToNetwork() slot gets invoked. In this slot we query network properties for the selected network and create a QWifiConfiguration object, which we later pass to the QWifiManager::connect function to set up a connection. During this operation any changes in the network state is reported by QWifiManager asynchronously.

void connectToNetwork()
{
    QModelIndex index = m_listView->currentIndex();
    QWifiConfiguration config;
    if (index.isValid()) {
        QString ssid = qvariant_cast<QString>(index.data(QWifiManager::SSID));
        config.setSsid(ssid);
        config.setPassphrase(m_passwordInput->text());
        m_wifiManager->connect(&config);
    }
}

We use QWifiManager::NetworkState change event handler to trigger the repainting of the delegate. This way, we can present a current network state to the user.

void handleNetworkStateChanged(QWifiManager::NetworkState state)
{
    m_listView->viewport()->repaint();
}

Connecting To a Known Network

If you already know the network configuration beforehand, you can skip the network scanning, listing and selection steps. This can be a valid use-case for devices that do not change their physical location.

QWifiManager::BackendState change events are reported asynchronously, so we must connect the signal to a slot that connects to the network access point after the backend initialization is complete.

class WifiConnectionHandler : public QObject
{
    Q_OBJECT
public:
    WifiConnectionHandler()
    {
        // replace with a valid network configuration
        m_config.setSsid("my-local-wifi");
        m_config.setPassphrase("helloworld123");
        m_config.setProtocol("WPA");
        m_manager = QWifiManager::instance();
        if (m_manager->backendState() == QWifiManager::Running) {
            m_manager->connect(&m_config);
        } else {
            connect(m_manager, &QWifiManager::backendStateChanged,
                    this, &WifiConnectionHandler::connectToNetwork);
            m_manager->start();
        }
    }

protected slots:
    void connectToNetwork(QWifiManager::BackendState state)
    {
        if (state == QWifiManager::Running)
            m_manager->connect(&m_config);
    }

private:
    QWifiManager *m_manager;
    QWifiConfiguration m_config;
};

Files:

Available under certain Qt licenses.
Find out more.