You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

QML按钮点击时Input类的updatePortList函数未触发问题求助

问题修复方案

1. 首要错误:QML函数调用缺少括号

你在QML的onClicked事件中写的input.updatePortList只是引用了函数对象,没有执行调用,补全括号即可:

onClicked :
{
    console.log("test")
    input.updatePortList() // 加括号执行函数
}

2. 修复C++类方法的QML调用权限

QML只能直接调用两类C++类方法:标记为Q_INVOKABLE的公共方法、公共槽函数。你当前的updatePortList只是普通公共方法,需要修改input.h:

// 方式1:添加Q_INVOKABLE修饰
public:
    Input();
    Q_INVOKABLE void updatePortList(); // 加Q_INVOKABLE宏
    QList<QString> comPorts(); // 同时要把READ方法从private移到public
private:
    QList<QString> ports;
    QList<QString> updatePorts;
// 方式2:放到public slots块
public slots:
    void setComPorts(QList<QString>);
    void updatePortList(); // 移到槽函数块
public:
    Input();
    QList<QString> comPorts(); // 同时要把READ方法从private移到public

3. 修复comPorts读取方法的逻辑问题

你当前comPorts()的实现每次调用都会往ports里追加端口,不会清空旧数据,会导致列表重复,修改input.cpp中的实现:

QList<QString> Input::comPorts(){
    ports.clear(); // 先清空旧列表
    Q_FOREACH(QSerialPortInfo port, QSerialPortInfo::availablePorts()) {
        ports.push_back(port.portName());
    }
    return ports;
}

4. 可选优化

你当前updatePortList已经生成了最新的端口列表调用了setComPorts,comPorts()方法其实不需要每次读取都重新扫描端口,直接返回ports即可,减少冗余扫描:

QList<QString> Input::comPorts(){
    return ports;
}

内容的提问来源于stack exchange,提问作者unity123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 18:45:03