C++ 如何打印QLabel?
我正在尝试从QT中的组合框打印QLabel。代码如下所示:C++ 如何打印QLabel?,c++,qt,C++,Qt,我正在尝试从QT中的组合框打印QLabel。代码如下所示: 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); la
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))));
我如何通过CUT打印标签?< /P> < P>你的代码似乎是使用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();
}
#包括
#包括
int main(int argc,字符**argv){
QApplication应用程序(argc、argv);
qw;
自动布局=新的QVBoxLayout(&w);
auto-label=new-QLabel(“在这里您将看到ComboBox中选择的文本”);
自动组合=新的QComboBox;
布局->添加小部件(标签);
布局->添加小部件(组合);
对于(自动端口:QSerialPortInfo::availablePorts())
组合->添加项(port.portName());
QObject::connect(组合框和QComboBox::currentTextChanged,[标签,组合框](){
标签->设置文本(组合->当前文本());
qDebug()currentText();
});
w、 show();
返回app.exec();
}
- 尽量不要在新代码中使用Q_FOREACH,它会
- 当新操作员已经指定了类型时,使用
,这将简化代码auto
- 使用
将调试信息输出到终端qDebug
- 当调用的代码较短时,在连接中使用lambda
- 使用for connections,因为它们将保证您的代码实际工作,旧样式具有运行时检查,而新样式具有构建时检查
std::cout text().toStdString()代码>?正是这样-现在我只需要知道,每次我在列表中选择另一项时如何使其打印?将信号连接到打印文本的函数/lambda/插槽。连接到函数/lambda无法使用旧的宏信号和插槽,您需要使用它。我不能只将标签保存为字符串并打印它?您可以打印标签文本,但这不适用于“每次我在列表中选择另一项”部分。