[英]QSerialPort readings refresh too fast for the Qt widget
我正在使用 QSerialPort 从连接到我计算机上的 COM 端口的设备读取,它每半秒向我的计算机发送一次字符。 我可以从 qDebug 窗口读取它们,所以我知道连接有效并且 Qt 接收数据。
但是,我不断从串行端口读取数据并刷新 GUI 上的标签小部件。 运行app的时候label变成空白,我认为这个问题是label名称不断刷新引起的。
我的 QserialPort 在主窗口构造函数中管理,在析构函数中关闭,读数是在名为 serialReceived() 的函数中完成的,我认为它被调用(或导致标签刷新)过于频繁
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
serial = new QSerialPort(this);
qDebug() << "nb ports: " << QSerialPortInfo::availablePorts().length();
foreach(const QSerialPortInfo &serialPortInfo, QSerialPortInfo::availablePorts())
{
qDebug() << "name" << serialPortInfo.portName();
}
serial->setPortName("COM11");
serial->setBaudRate(QSerialPort::Baud9600);
serial->setDataBits(QSerialPort::Data8);
serial->setParity(QSerialPort::NoParity);
serial->setStopBits(QSerialPort::OneStop);
serial->setFlowControl(QSerialPort::NoFlowControl);
qDebug() << "is " << serial->open(QSerialPort::ReadOnly);
qDebug() << "err " << serial->error();
//serial->write("ok");
// Create the signal and slot
connect(serial, SIGNAL(readyRead()), this, SLOT(serialReceived()));
}
MainWindow::~MainWindow()
{
delete ui;
serial->close(); // instance is closed when mainwindow destroyed
}
void MainWindow::serialReceived()
{
QByteArray ba;
ba = serial->readAll();
ui->label->setText(serial->readAll());
qDebug()<<ba;
}
您可以随时读取数据,而不仅仅是通过readyRead
信号。 QSerialPort
类将缓冲所有接收到的数据,直到您读取它。
您还可以将每个接收到的数据部分附加到一些可滚动的QPlainTextEdit
。 我推荐这种方式。
void MainWindow::serialReceived()
{
QByteArray ba;
ba = serial->readAll();
ui->plainTextEdit->appendPlainText(ba);
}
使用定时器:
connect(&m_timer, &QTimer::timeout, this, &MyClass::onTimer);
...
m_timer->start(5000);
...
void MyClass::onTimer()
{
if(serial->bytesAvailable() > 0)
{
QByteArray ba;
ba = serial->readAll();
ui->label->setText(ba);
qDebug() << ba;
}
}
您还可以使用QWidget::setUpdatesEnabled()临时禁用小部件的视觉更新,但似乎您不应错过部分数据。
请注意, QIODevice
(以及QSerialPort
作为其子类)类不保证在readyRead
事件中一定量的数据可用。 例如,如果您一次向另一端的端口写入 10 个字节,在某些情况下,您将收到信号,这将允许在 monent 上(即在所有传输的字节到达之前)可用较少的数据。
void MainWindow::serialReceived()
{
QByteArray ba;
ba = serial->readAll();
ui->label->setText(serial->readAll());
qDebug()<<ba;
}
您首先将数据读入 ba,然后尝试再次读取,但由于 readAll() 已经读取了数据,因此什么也没有留下。 你要
void MainWindow::serialReceived()
{
QByteArray ba = serial->readAll();
ui->label->setText(ba);
qDebug() << ba;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.