【问题标题】:How to modify a QSerialPort Name while application is running如何在应用程序运行时修改 QSerialPort 名称
【发布时间】:2020-07-16 18:02:03
【问题描述】:

当我在主窗口构造函数中设置实例的参数时,我使用 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(),它确实有效。

谢谢!

【问题讨论】:

  • 删除此行:serial = new QSerialPort(this); // this (mainwindow) is parent
  • 注意serialReceived方法包含一个错误,你试图读取相同的数据两次:ba = serial-&gt;readAll(); ui-&gt;label-&gt;setText(serial-&gt;readAll());

标签: c++ qt serial-port port


【解决方案1】:

尝试在setPortName()之前删除并重新创建您的QSerialPort

serial->deletLater();
serial = new QSerialPort(this);
serial->setPortName("COM1");

【讨论】:

    猜你喜欢
    • 2014-08-12
    • 2023-03-19
    • 2019-09-13
    • 1970-01-01
    • 2013-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多