【发布时间】:2021-08-30 20:44:41
【问题描述】:
我有一个使用 Q_PROPERTY 设置的 QML 上下文来读取、写入和通知带有更新的 COM 端口列表的组合框。但是,函数根本没有被调用,我有 qDebugs 来指定函数是否被调用。
*.cpp
#include "input.h"
#include <QDebug>
void Input::setComPorts(QList<QString> comPortsList)
{
if (comPortsList != ports)
{
ports = comPortsList;
emit comPortsChanged();
}
}
Input::Input()
{
}
void Input::updatePortList()
{
qDebug() << "-------------";
QList<QString> comPortsList;
Q_FOREACH(QSerialPortInfo port, QSerialPortInfo::availablePorts()) {
comPortsList.push_back(port.portName());
qDebug() << port.portName();
}
setComPorts(comPortsList);
}
QList<QString> Input::comPorts(){
Q_FOREACH(QSerialPortInfo port, QSerialPortInfo::availablePorts()) {
ports.push_back(port.portName());
}
return ports;
}
*.h
#ifndef INPUT_H
#define INPUT_H
#include <QObject>
#include <QtSerialPort/QSerialPortInfo>
class Input : public QObject
{
Q_OBJECT
Q_PROPERTY(QList<QString> comPorts READ comPorts WRITE setComPorts NOTIFY comPortsChanged);
signals:
void comPortsChanged();
public slots:
void setComPorts(QList<QString>);
public:
Input();
void updatePortList();
private:
QList<QString> comPorts();
QList<QString> ports;
QList<QString> updatePorts;
};
#endif // INPUT_H
*.qml
import QtQuick 2.12
import QtQuick.Window 2.14
import QtQuick.Controls 2.15
import QtLocation 5.6
import QtPositioning 5.6
import QtQuick.Controls.Material 2.12
import QtQuick.Layouts 1.12
import Qt.labs.location 1.0
import Input 1.0
Page {
visible: true
height: Screen.height / 2
width: Screen.width / 2
Input {
id: input
}
ComboBox {
id: dropDown
model: input.comPorts
x:150
}
Button{
id:refresh
anchors.centerIn: parent
text: "Refresh"
onClicked :
{
console.log("test")
input.updatePortList
}
}
}
未被调用的函数是按钮中的input.updatePortList。
【问题讨论】:
-
错字:将
input.updatePortList更改为input.updatePortList()。也使用QStringList而不是QList<QString>。还将updatePortList声明为插槽或Q_INVOKABLE。