如何从另一个页面访问主窗口串口信息并替换固定串口号?
解决方案
方法一:构造函数传参(最直接易用)
在主窗口打开第二个窗口时,直接将选中的串口名传递过去:
- 主窗口代码修改:
// 假设第二个窗口类名为SecondWindow SecondWindow *secondWin = new SecondWindow(this); // 获取当前选中的串口名 QString parsedPortName = QSerialPortInfo::availablePorts().at(ui->comboBoxDevices->currentIndex()).portName(); // 通过构造函数直接传参 SecondWindow *secondWin = new SecondWindow(parsedPortName, this); secondWin->show();
- 第二个窗口头文件声明:
class SecondWindow : public QWidget { Q_OBJECT public: explicit SecondWindow(const QString &portName, QWidget *parent = nullptr); private: QString m_portName; // 存储串口名 };
- 第二个窗口实现代码:
SecondWindow::SecondWindow(const QString &portName, QWidget *parent) : QWidget(parent), m_portName(portName) { // 窗口初始化逻辑 } // 替换原固定串口号 if (serialStartStop.begin(m_portName, 9600, 8, 0, 1, 0, false)) { serialStartStop.send("B" + ui->baslatmaedit->text().toLatin1() + "D"+ ui->durdurmaedit->text().toLatin1()); }
方法二:信号槽传递(支持动态更新)
如果主窗口的串口选择发生变化时,需要同步更新第二个窗口的串口名,用信号槽机制:
- 主窗口头文件添加信号:
class MainWindow : public QMainWindow { Q_OBJECT signals: void portNameUpdated(const QString &newPortName); private slots: void onComboDeviceIndexChanged(int index); // 绑定下拉框索引变化信号 };
- 主窗口实现代码:
void MainWindow::onComboDeviceIndexChanged(int index) { QString parsedPortName = QSerialPortInfo::availablePorts().at(index).portName(); emit portNameUpdated(parsedPortName); } // 打开第二个窗口时连接信号槽 SecondWindow *secondWin = new SecondWindow(this); connect(this, &MainWindow::portNameUpdated, secondWin, &SecondWindow::updatePortName); secondWin->show();
- 第二个窗口头文件添加槽函数:
class SecondWindow : public QWidget { Q_OBJECT public slots: void updatePortName(const QString &newPortName); private: QString m_portName; };
- 第二个窗口实现代码:
void SecondWindow::updatePortName(const QString &newPortName) { m_portName = newPortName; } // 使用串口时替换为动态获取的名称 if (serialStartStop.begin(m_portName, 9600, 8, 0, 1, 0, false)) { serialStartStop.send("B" + ui->baslatmaedit->text().toLatin1() + "D"+ ui->durdurmaedit->text().toLatin1()); }
方法三:全局变量(不推荐,耦合性高)
仅适合小型项目快速实现,大型项目不建议使用:
- 在公共头文件定义全局变量:
extern QString g_selectedPort;
- 主窗口中赋值:
QString g_selectedPort; // 定义全局变量 // 选中串口时更新全局变量 g_selectedPort = QSerialPortInfo::availablePorts().at(ui->comboBoxDevices->currentIndex()).portName();
- 第二个窗口直接使用:
if (serialStartStop.begin(g_selectedPort, 9600, 8, 0, 1, 0, false)) { serialStartStop.send("B" + ui->baslatmaedit->text().toLatin1() + "D"+ ui->durdurmaedit->text().toLatin1()); }
内容的提问来源于stack exchange,提问作者ysncck
相关产品推荐
相关产品推荐

