Joe Carr Joe Carr - 11 days ago 5
C++ Question

Getting the value from combobox's in Qt for serial connection

I have this problem with Qt whenever I try to set up a connection it never actually takes my data (e.g port name and baud rate) from the combo boxes and apparently it is because I do not link them very well. This is how I did it so far and, well, it doesn't work...

void MainWindow::openSerialPort()
{
serial.setPortName(ui->portBox->itemData(ui->portBox->currentIndex()));
printf("%s \n", ui->portBox->itemData(ui->portBox->currentIndex()));
printf("\n ------------ \n");
serial.setBaudRate(ui->baudBox->currentIndex());
printf("%d \n", ui->baudBox->itemData(ui->baudBox->currentIndex()));
// serial.setDataBits();
...
}


Any suggestions?




Secondary question: Am I adding the items to the combo box correctly?

ui->baudBox->addItem(QStringLiteral("38400"), QSerialPort::Baud38400);
ui->baudBox->addItem(QStringLiteral("57600"), QSerialPort::Baud57600);
ui->baudBox->addItem(QStringLiteral("115200"), QSerialPort::Baud115200);

Answer

QComboBox::currentData() return the QVariant which you provided when adding the currently selected item into the widget. To get the user data from your combobox selection as your serial port baud rate, use

serial.setBaudRate(ui->baudBox->currentData().toInt());