但是如果没有列出我们用到的波特率,那么就需要实现自定义波特率(比如我以前参与的一个项目就要求串口使用500000bps波特率)。实现方式就是将波特率QComboBox列表最后一项设置为自定义波特率,当使用自定义波特率时则获取填写的自定义值并转换为qint32类型数值,然后将该参数设置为波特率,如下:
时间: 2025-05-22 12:53:56 浏览: 20
### Qt 中通过串口实现自定义波特率
在 Qt 的 `QSerialPort` 类中,默认支持一组标准的波特率选项,但如果需要设置非标准的波特率(如 500000 bps),可以通过调用 `setBaudRate()` 方法并传递自定义值来完成此操作[^1]。
以下是具体实现方法:
#### 使用 QComboBox 获取用户输入
为了允许用户选择或输入自定义波特率,可以使用 `QComboBox` 控件。该控件既可以显示预设项列表,也可以接受用户的自由文本输入。如果希望用户能够手动输入数值,则需将组合框模式设置为可编辑状态。
```cpp
ui->comboBox_BaudRate->setEditable(true); // 启用可编辑功能
QStringList baudRates;
baudRates << "9600" << "19200" << "38400" << "57600" << "115200"; // 添加默认波特率选项
ui->comboBox_BaudRate->addItems(baudRates);
```
#### 将用户输入转换为 qint32 并应用到串口中
当用户选择了某个波特率或者输入了一个新的值时,可以从 `QComboBox` 提取当前选中的字符串,并将其解析为整数形式以便于后续处理。
```cpp
QString selectedBaudRateStr = ui->comboBox_BaudRate->currentText(); // 获取当前选定/输入的内容
bool ok;
qint32 customBaudRate = selectedBaudRateStr.toInt(&ok, 10);
if (ok && customBaudRate > 0) {
serialPort->setBaudRate(customBaudRate, QSerialPort::AllDirections); // 应用自定义波特率
} else {
qDebug() << "Invalid or unsupported baud rate!";
}
```
上述代码片段展示了如何读取来自界面组件的数据,并验证其有效性之后再尝试配置实际硬件设备上的参数设置过程[^2]。
#### 完整示例程序
下面给出一个完整的例子用于演示整个流程:
```cpp
#include <QApplication>
#include <QWidget>
#include <QVBoxLayout>
#include <QLabel>
#include <QComboBox>
#include <QPushButton>
#include <QDebug>
#include <QSerialPort>
class SerialWidget : public QWidget {
public:
SerialWidget(QWidget *parent = nullptr): QWidget(parent), serial(new QSerialPort(this)) {
QVBoxLayout* layout = new QVBoxLayout;
QLabel* label = new QLabel("Select Baud Rate:");
comboBox = new QComboBox;
comboBox->setEditable(true);
QStringList bauds {"9600", "19200", "38400", "57600", "115200"};
comboBox->addItems(bauds);
QPushButton* button = new QPushButton("Apply");
connect(button, &QPushButton::clicked, this, &SerialWidget::applySettings);
layout->addWidget(label);
layout->addWidget(comboBox);
layout->addWidget(button);
setLayout(layout);
}
private slots:
void applySettings(){
QString str = comboBox->currentText();
bool success;
int baudrate = str.toInt(&success);
if(success){
serial->setBaudRate(baudrate,QSerialPort::AllDirections);
qDebug()<<"Set baudrate to:"<<baudrate;
}else{
qWarning()<<"Failed to parse baudrate.";
}
}
private:
QComboBox* comboBox;
QSerialPort* serial;
};
int main(int argc, char **argv){
QApplication app(argc, argv);
SerialWidget window;
window.resize(300,200);
window.show();
return app.exec();
}
#include "main.moc"
```
注意,在某些操作系统上可能还需要额外权限才能成功更改非标准速率下的通讯条件[^3]。
阅读全文
相关推荐


















