Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to connection serialport outside 'mainwindow.cpp' ?



  • Hi,

    I created new MainWindow project. I don't want to do the serialport connection via mainwindow.cpp. But when I want to make a serialport connection over a different class, the project crashes.

    Example:
    cameramodel.h
    #include <QtSerialPort/QSerialPort>
    #include <QtSerialPort/QSerialPortInfo>
    class CameraModel : public QMainWindow
    {
    Q_OBJECT

    public:
    QSerialPort *serialCamera;
    bool isCameraSerial = false;

    }

    cameramodel.cpp:
    #include "cameramodel.h"
    #include "ui_cameramodel.h"

    CameraModel::CameraModel(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::CameraModel)
    {
    ui->setupUi(this);
    serialCamera = new QSerialPort(ui->cb_spCportName->currentText());
    serialCamera->setBaudRate(9600);
    serialCamera->setDataBits(QSerialPort::Data8);
    serialCamera->setParity(QSerialPort::NoParity);
    serialCamera->setStopBits(QSerialPort::OneStop);
    serialCamera->setFlowControl(QSerialPort::NoFlowControl);
    if (serialCamera->open(QIODevice::ReadWrite))
    {
    QMessageBox::information(this, tr("Connected"), "Serial Port Opened Successfully");
    }
    else{
    QMessageBox::critical(this, tr("Error"), serialCamera->errorString());
    }
    }
    Project crashed. How to solve ?

    Thanks,


  • Lifetime Qt Champion

    @bknhatice said in How to connection serialport outside 'mainwindow.cpp' ?:

    Project crashed

    Use a debugger and see where it crashes, fix the crash.



  • @bknhatice said in How to connection serialport outside 'mainwindow.cpp' ?:

    ui->cb_spCportName->currentText()

    What is the format of the port name?
    Are you using proper port name format?


Log in to reply