Reputation: 23
I am trying to print a QLabel from a combobox in QT. Code looks like this:
QApplication a(argc, argv);
QWidget w;
QVBoxLayout *layout = new QVBoxLayout(&w);
QLabel *label = new QLabel("Here you will see the selected text from ComboBox", &w);
QComboBox *combo = new QComboBox(&w);
layout->addWidget(label);
layout->addWidget(combo);
Q_FOREACH(QSerialPortInfo port, QSerialPortInfo::availablePorts()) {
combo->addItem(port.portName());
QObject::connect(combo, SIGNAL(currentIndexChanged(QString)), label, (SLOT(setText(QString))));
How do i print the label via cout?
Upvotes: 0
Views: 1331
Reputation: 2398
Your code seems to be using Qt4, let's port that to Qt5 and a newer C++, shall we?
#include <QtWidgets>
#include <QtSerialPort>
int main(int argc, char ** argv) {
QApplication app(argc, argv);
QWidget w;
auto layout = new QVBoxLayout(&w);
auto label = new QLabel("Here you will see the selected text from ComboBox");
auto combo = new QComboBox;
layout->addWidget(label);
layout->addWidget(combo);
for (auto port : QSerialPortInfo::availablePorts())
combo->addItem(port.portName());
QObject::connect(combo, &QComboBox::currentTextChanged, [label, combo](){
label->setText(combo->currentText());
qDebug() << combo->currentText();
});
w.show();
return app.exec();
}
Try to not use Q_FOREACH in new code, it will probably be removed in the future,
Use auto
when the type will be already specified by the new operator, this simplifies code,
Use qDebug
to output debug information to the terminal,
Use lambdas in connections when the invoked code is short,
Use the new style connections for connections, because they will guarantee that your code actually works, the old style has runtime checks, and the new has build time checks.
Upvotes: 1