c++ - 如何在应用程序运行时修改 QSerialPort 名称
问题描述
当我在主窗口构造函数中设置实例的参数时,我使用 QSerialPort 从串行端口成功读取。但是,我希望我的 GUI 启用更改端口,但是在启动我的应用程序后更改我的 COM 端口时我似乎无法开始阅读(我使用设置我的 QSerialPort 实例的 COM 端口名称的 spinBox 这样做)。这是我的代码(mainwindow.cpp),我的问题是如果我不直接使用serial->setPortName(); 在我的构造函数中,我把它放在与我的 spinBox 信号链接的插槽中,我无法再使用 qDebug 读取从我的 com 端口接收到的数据。
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QDebug>
QSerialPort *serial;
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this); // Here by default. Takes a pointer to mainwindow as argument
serial = new QSerialPort(this);
qDebug() << "nb ports: " << QSerialPortInfo::availablePorts().length();
foreach(const QSerialPortInfo &serialPortInfo, QSerialPortInfo::availablePorts())
{
qDebug() << "name" << serialPortInfo.portName();
}
qDebug() << "is " << serial->open(QSerialPort::ReadOnly);
qDebug() << "err " << serial->error();
// Create the signal and slot for
connect(ui->com_spinBox, SIGNAL(valueChanged(const QString&)),
this, SLOT(setComPort(const QString&)));
// Create the signal and slot for receiving data from device
connect(serial, SIGNAL(readyRead()), this, SLOT(serialReceived()));
}
MainWindow::~MainWindow()
{
delete ui;
serial->close(); // instance is closed when mainwindow destroyed
}
// My 2 custom slots below!!!
void MainWindow::serialReceived()
{
QByteArray ba;
ba = serial->readAll();
ui->label->setText(serial->readAll());
qDebug()<<ba;
}
void MainWindow::setComPort(const QString& com)
{
serial->close();
serial = new QSerialPort(this); // this (mainwindow) is parent
qDebug() << serial->portName();
QString comPort = "COM" + com;
qDebug() << comPort;
serial->setPortName(comPort);
serial->setBaudRate(QSerialPort::Baud9600);
serial->setDataBits(QSerialPort::Data8);
serial->setParity(QSerialPort::NoParity);
serial->setStopBits(QSerialPort::OneStop);
serial->setFlowControl(QSerialPort::NoFlowControl);
serial->open(QSerialPort::ReadOnly);
}
在这里,我尝试将所有串行实例设置从构造函数移动到我的插槽,然后关闭并重新打开实例以查看它是否有帮助,但是在调整到正确的 COM 端口时,我仍然无法使用 serialReceived() 插槽读取任何内容。它如果我将所有内容都放在构造函数中,并且在程序开始时使用正确的端口号 setPortName() ,它确实可以工作。
谢谢!
解决方案
尝试删除并重新创建您的QSerialPort
之前setPortName()
serial->deletLater();
serial = new QSerialPort(this);
serial->setPortName("COM1");
推荐阅读
- python - 获取时间戳不是今天日期的记录
- c# - 如何使用无参数构造函数创建 .NET 结构?
- typescript - 在 MacO 上运行 Ionic 项目后出现大量 TypeScript 错误
- qt - QRadiobutton 如何支持富文本?
- python - 如何使用 selenium python 打印 PDF 横向
- ibm-midrange - 使用 IP 地址查找服务器名称
- javascript - 将数百张图像注入 div
- acl - 如何在运行时授予用户权限?
- c++ - 如何在 C++ 中将一个 tensorflow 线程固定到一个特定的 CPU?
- java - jersey 2 客户端的空响应