From 54f5097ff4506a0d44321795748e1b3c1d89b65d Mon Sep 17 00:00:00 2001 From: Carl Schwan Date: Wed, 30 Jun 2021 11:23:00 +0200 Subject: [PATCH] Don't assume there is an active connection when loading devices list Instead listen to Controller::activeConnectionChanged and reset model when the active connection is changed. Fix #413 --- src/devicesmodel.cpp | 30 +++++++++++++++++++++--------- src/devicesmodel.h | 1 + 2 files changed, 22 insertions(+), 9 deletions(-) diff --git a/src/devicesmodel.cpp b/src/devicesmodel.cpp index 65b3662c4..a829cf141 100644 --- a/src/devicesmodel.cpp +++ b/src/devicesmodel.cpp @@ -10,18 +10,30 @@ DevicesModel::DevicesModel(QObject *parent) : QAbstractListModel(parent) { - GetDevicesJob *job = Controller::instance().activeConnection()->callApi(); - connect(job, &BaseJob::success, this, [this, job]() { - beginResetModel(); - m_devices = job->devices(); - endResetModel(); - }); + connect(&Controller::instance(), &Controller::activeConnectionChanged, + this, &DevicesModel::fetchDevices); + + fetchDevices(); +} + +void DevicesModel::fetchDevices() +{ + if (Controller::instance().activeConnection()) { + auto job = Controller::instance().activeConnection()->callApi(); + connect(job, &BaseJob::success, this, [this, job]() { + beginResetModel(); + m_devices = job->devices(); + endResetModel(); + }); + } } QVariant DevicesModel::data(const QModelIndex &index, int role) const { - if (index.row() < 0 || index.row() >= rowCount(QModelIndex())) - return QVariant(); + if (index.row() < 0 || index.row() >= rowCount(QModelIndex())) { + return {}; + } + switch (role) { case Id: return m_devices[index.row()].deviceId; @@ -33,7 +45,7 @@ QVariant DevicesModel::data(const QModelIndex &index, int role) const if (m_devices[index.row()].lastSeenTs) return *m_devices[index.row()].lastSeenTs; } - return QVariant(); + return {}; } int DevicesModel::rowCount(const QModelIndex &parent) const diff --git a/src/devicesmodel.h b/src/devicesmodel.h index 061e6180d..6d0f7a031 100644 --- a/src/devicesmodel.h +++ b/src/devicesmodel.h @@ -32,5 +32,6 @@ public: Q_INVOKABLE void setName(int index, const QString &name); private: + void fetchDevices(); QVector m_devices; };