Search code examples
c++qtserial-portqtgui

Selecting from all available serial ports using Qt GUI


I could not find a conclusive answer to my issue so I decided to post my first question on this site. I'm fairly new to programming and have been using Qt for a couple of months now. My code communicates with a microcontroller via serial ports, however the available port differs from pc to pc. I'm displaying the number of ports available with the code;

qDebug() << "Number of serial ports:" << QSerialPortInfo::availablePorts().count(); 

My question is: how can I display the name of all the available ports eg "COM 10, 17. 22, etc" and then show them in my GUI. What I eventually hope to do is have a combo box that can be dynamically populated with the available ports, I have one that switches between a couple ports at the moment but these are fixed ports corresponding to particular computers.


Solution

  • Try something like this:

    #include <QApplication>
    #include <QWindow>
    #include <QSerialPortInfo>
    #include <QComboBox>
    
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
        QWidget w;
        w.resize(200,200);
        w.show();
    
        QComboBox box(&w);
        Q_FOREACH(QSerialPortInfo port, QSerialPortInfo::availablePorts()) {
            box.addItem(port.portName());
        }
        box.move(100 - box.width() / 2,100 - box.height() / 2);
        box.show();
    
        return a.exec();
    }
    

    The code is pretty self-explanatory.