Important: Please read the Qt Code of Conduct -

Automatically connect to serial port

  • I have simple Qt app that talks to a micro-controller over the serial port using QSerailPort. In my source I open up the port automatically when the application is launched. Right now I open a specific comport as shown on the code below. What I'm trying to do is have the Qt app find the port automatically. The reason is that when I connect to a different computer or change USB port etc, I have to either change the Qt app to call out the correct port or change port name in device manager. What is the method to deal with this?

    void MainWindow::openSerialPort()
        QString status_msg;
        if (serial->open(QIODevice::ReadWrite))
            qDebug() << "Serial Port :" << serial->portName() << "Open";
            QTextStream(&status_msg)<< serial->portName()<< " OPEN ";
        else {
                ui->statusBar->showMessage(tr("PORT NOT OPENED !!! ERROR !!!"));
    //            QMessageBox::critical(this, tr("Error"), serial->errorString());
                //showStatusMessage(tr("Open error"));
                qDebug() << "Name :" << serial->portName();

  • Lifetime Qt Champion

    @valerio-j said in Automatically connect to serial port:

    What is the method to deal with this?

    To make it configurable in the app. You can use QSettings to store and read your app settings.

    You also can use to iterate over all found ports and try to connect to each of them. But if more than one device is connected you still need a way to tell the app which one to use.

  • Ok thanks.
    I've done it using the prouct id and vendor id of the usb-to-serial device. It works pretty well. I might also include a search through the ports available, send a data and wait for some type of acknowledgement in the reply to verify the port selected.

Log in to reply