[英]How do I print a QLabel?
I am trying to print a QLabel from a combobox in QT. 我正在尝试从QT的组合框中打印QLabel。 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? 如何通过cout打印标签?
Your code seems to be using Qt4, let's port that to Qt5 and a newer C++, shall we? 您的代码似乎正在使用Qt4,让我们将其移植到Qt5和更新的C ++中,对吧?
#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 , 尝试不要在新代码中使用Q_FOREACH,将来可能会删除它,
Use auto
when the type will be already specified by the new operator, this simplifies code, 当新运算符已经指定类型时,请使用
auto
,这可以简化代码,
Use qDebug
to output debug information to the terminal, 使用
qDebug
将调试信息输出到终端,
Use lambdas in connections when the invoked code is short, 当调用的代码很短时,请在连接中使用lambda,
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. 对连接使用新样式的连接,因为它们将保证您的代码实际可用,旧样式具有运行时检查,而新样式具有构建时间检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.