Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

修复Config类成员修改后无法保存到config.json的问题 #865

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

skcjk
Copy link

@skcjk skcjk commented May 3, 2024

问题背景

在使用串口时,由于经常要插拔串口,导致串口数量总是不固定
在这个背景下,我需要使用ComboBoxSettingCard,并在下框被点击时重新获取所有串口
屏幕截图 2024-05-04 005655

业务代码

def __refreshSerialPort(self):
     if refreshSerialPort():  # 串口数量变化时返回true, #以下代码基本上是ComboBoxSettingCard中__init__的逻辑
         self.COMCard.configItem=cfg.port #COMCard是ComboBoxSettingCard类的对象
         self.COMCard.comboBox.clear() 

         self.COMCard.optionToText={o: t for o, t in zip(self.COMCard.configItem.options, cfg.portList)}
         for text, option in zip(cfg.portList, self.COMCard.configItem.options):
              self.COMCard.comboBox.addItem(text, userData=option)

         self.COMCard.comboBox.setCurrentText(self.COMCard.optionToText[cfg.get(cfg.port)])
         self.COMCard.comboBox.currentIndexChanged.connect(self.COMCard._onCurrentIndexChanged)
         self.COMCard.configItem.valueChanged.connect(self.COMCard.setValue)

def refreshSerialPort():
    cfg.availablPorts = QSerialPortInfo.availablePorts()
    portList = [port.portName() for port in cfg.availablPorts]
    if portList != cfg.portList:
        cfg.portList = portList
        cfg.port = OptionsConfigItem("Serial", "COM", "COM3", OptionsValidator(cfg.portList))
        return True
    else:
        return False

问题描述

当串口数量变化且用以上代码刷新后,之后再当COMCard下拉框选中的值改变时,不能将值保存到config.json

##原因分析

  • 刷新时调用cfg.port = OptionsConfigItem("Serial", "COM", "COM3", OptionsValidator(cfg.portList)),为cfg.port重新赋值
  • 保存为config.json时调用了qfluentwidgets\common\config.pyQConfig类的toDict方法,其中用以下代码读取类成员的值
for name in dir(self._cfg.__class__):
            item = getattr(self._cfg.__class__, name)
            if not isinstance(item, ConfigItem):
                continue
  • 关键字.__class__导致读取类成员的值时,读到的是cfg.port重新赋值之前的值,原因我不知道

解决方法

去掉.__class__
去掉后功能正常,但暂不清楚是否有其他影响

@zhiyiYo
Copy link
Owner

zhiyiYo commented Jul 22, 2024

之前设计这个类的时候希望配置是单例,所以用的 __class__

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants