自学成才的新手程序员在这里,所以请原谅错误。我正在尝试使程序发送/读取串行数据,并且读取部分存在问题。我能够从下拉菜单中选择通信端口,并传输我需要的内容。当我开始使用大量在线示例对接收端进行编码时,它无法编译,我似乎无法弄清楚原因。如果我完全复制 QT 示例中的代码,它可能会起作用,但它不会做我想要它做的事情(即使用组合框下拉选项卡进行选择)
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QApplication>
#include <QWidget>
#include <QSerialPort>
#include <QSerialPortInfo>
QString commPort;
QSerialPort serial;
QByteArray charBuffer;
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
foreach (const QSerialPortInfo &serialPortInfo, QSerialPortInfo::availablePorts()) //populates the combo box with all availble comm ports.
{
ui->comboBox->addItem(serialPortInfo.portName());
commPort=serialPortInfo.portName();
}
}
MainWindow::~MainWindow()
{
delete ui;
serial.close();
}
void MainWindow::on_comboBox_activated(const QString &commPort) //selects the chosen comm port.
{
ui->report->setText(commPort);
}
void MainWindow::openSerialPort()
{
serial.setPortName(commPort);
if(serial.open(QIODevice::ReadWrite))
{
qDebug("Serial Opened");
ui->report->setStyleSheet("QLabel{background-color:'green';}");
serial.setBaudRate(QSerialPort::Baud9600);
serial.setDataBits(QSerialPort::Data8);
serial.setParity(QSerialPort::NoParity);
serial.setStopBits(QSerialPort::OneStop);
serial.setFlowControl(QSerialPort::NoFlowControl);
connect(serial, &QSerialPort::readyRead, this,&MainWindow::readSerial);
//^^That is the part that fails to compile
}
else
{
ui->report->setStyleSheet("QLabel{background-color:'red';}");
qDebug ("Serial NOT Opened");
qDebug() << serial.error();
qDebug() << serial.errorString();
}
}
void MainWindow::on_connectButton_pressed()
{
openSerialPort();
}
void MainWindow::readSerial()
{
qDebug()<<("serial works");
}
*more code follows, but not needed....
显示"connect(serial, &QSerialPort::readyRead, this,&MainWindow::readSerial);"的行 是给我错误的罪魁祸首:mainwindow.cpp:52: error: 没有匹配函数来调用 'MainWindow::connect(QSerialPort&, void (QIODevice::):), MainWindow const, void (MainWindow::*)())' connect(serial, &QSerialPort::readyRead, this, &MainWindow::readSerial);
我试图阅读QObject和QSerialPort库的帮助信息,但是SIGNAL和SLOT的东西对于这个amatuer来说太混乱了。我还在网上获取了部分示例并粘贴以尝试修复它,...没有骰子。
您必须传递发件人的指针。
connect(const QObject *sender, constchar *signal, const QObject *接收器,常量字符*方法,Qt::连接类型)
connect(const QObject *sender, const char *signal, const char *method, Qt::ConnectionType type)
connect(const QObject *sender, PointerToMemberFunctionsignal, const QObject *receiver, PointerToMemberFunction method, Qt::ConnectionType type)
connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
connect(const QObject *sender, PointerToMemberFunction signal, const QObject *context, Functor functor, Qt::ConnectionType type)
改变:
connect(serial, &QSerialPort::readyRead, this,&MainWindow::readSerial);
自
connect(&serial, &QSerialPort::readyRead, this,&MainWindow::readSerial);