feat: 活动接口选择持久化到配置文件

- 构造函数从 ~/.config/jnetapplet/settings.ini 读取上次保存的 activeInterface
- setActiveInterface 切换接口时写入配置,弹窗 chip 和设置窗口统一持久化
- 保存的接口已不存在时(如 USB 网卡拔出)清空回退到自动选择
- 下次启动插件自动恢复用户上次选择的网卡
This commit is contained in:
2026-07-22 22:42:35 +08:00
parent 7f7ab2d737
commit b9b5232d5f
2 changed files with 23 additions and 0 deletions
+21
View File
@@ -44,6 +44,13 @@ NetworkMonitorApplet::NetworkMonitorApplet(QObject *parent)
}
// 若校验失败则保持空串默认值(跟随系统),不抛出也不记录
}
// 从配置文件读取持久化的活动接口,启动时自动恢复用户上次选择
// 设计原因:用户手动选择的网卡应跨重启保持,而非每次启动重新自动检测;
// 若保存的接口已不存在(如 USB 网卡拔出),readNetworkStats 会清空并回退到自动选择
if (settings.contains(QStringLiteral("activeInterface"))) {
m_activeInterface = settings.value(QStringLiteral("activeInterface")).toString();
}
}
NetworkMonitorApplet::~NetworkMonitorApplet()
@@ -222,6 +229,15 @@ void NetworkMonitorApplet::setActiveInterface(const QString &interface)
if (m_activeInterface != interface) {
m_activeInterface = interface;
m_firstUpdate = true;
// 持久化到配置文件,下次启动自动加载用户选择的网卡
// 设计原因:弹窗 chip 和设置窗口都调用此方法,统一持久化保证两处选择一致
const QString configPath = QStandardPaths::writableLocation(QStandardPaths::ConfigLocation)
+ QStringLiteral("/jnetapplet/settings.ini");
QSettings settings(configPath, QSettings::IniFormat);
settings.setValue(QStringLiteral("activeInterface"), m_activeInterface);
settings.sync();
emit activeInterfaceChanged();
// 接口切换后通知 QML 趋势图切换显示新接口的历史数据
emit speedHistoryChanged();
@@ -287,6 +303,11 @@ void NetworkMonitorApplet::readNetworkStats()
}
}
// 保存的接口已不在当前列表中(如 USB 网卡拔出),清空让自动选择接管
if (!m_activeInterface.isEmpty() && !m_interfaceList.contains(m_activeInterface)) {
m_activeInterface.clear();
}
// 自动选择活动接口
if (m_activeInterface.isEmpty() && !m_interfaceList.isEmpty()) {
// 优先选择物理网卡(wlp/wlan/enp/eth)中有流量的接口,
+2
View File
@@ -51,6 +51,8 @@ class NetworkMonitorApplet : public DApplet
Q_PROPERTY(QStringList networkInterfaces READ networkInterfaces NOTIFY interfacesChanged)
Q_PROPERTY(QStringList interfaceStats READ interfaceStats NOTIFY statsChanged)
Q_PROPERTY(bool ready READ ready NOTIFY readyChanged)
// 当前活动接口,用户在弹窗或设置窗口选择后持久化到 ~/.config/jnetapplet/settings.ini
// 下次启动自动恢复;若保存的接口已不存在则回退到自动选择
Q_PROPERTY(QString activeInterface READ activeInterface NOTIFY activeInterfaceChanged)
// 活动接口的 IPv4 地址,供 QML 在弹出面板和 tooltip 中显示
Q_PROPERTY(QString ipAddress READ ipAddress NOTIFY ipAddressChanged)