View Full Version : How to change QLabel value after Pushbutton pressed?
rdelgado
16th August 2010, 20:12
Hello,
I need to know how to change the value or text displayed in a QLabel after a PushButton is pressed.
I have 2 buttons on my program. One PushButton is to trigger some math calculations. I want to display the result of the calculation after it is completed in a QLabel, but to display it only when I press the other PushButton. Then, if I do the math again, display the new result by pressing the other button and so on.
¿Can I use a PushButton clicked() signal to change a QLabel value?
Thank you very much!!!!
Lykurg
16th August 2010, 20:29
Yes, connect the clicked signal to a slot and in that slot you can set the text of your label.
rdelgado
16th August 2010, 20:56
Hi,
I did this:
main.cpp
#include <QApplication>
#include <QLabel>
#include <QPushButton>
#include <QVBoxLayout>
#include <QWidget>
#include <QString>
class MyWidget : public QWidget
{
public:
MyWidget(QWidget *parent = 0);
QLabel *label;
QString string;
signals:
public slots:
void setTextLabel();
};
void MyWidget::setTextLabel()
{
label->setText("Test");
}
MyWidget::MyWidget(QWidget *parent) :
QWidget(parent)
{
QPushButton *quit = new QPushButton("Quit");
QPushButton *showtext = new QPushButton("Show");
label = new QLabel;
QObject::connect(quit, SIGNAL(clicked()), qApp, SLOT(quit()));
QObject::connect(showtext, SIGNAL(clicked()), this, SLOT(setTextLabel()));
QVBoxLayout *layout = new QVBoxLayout;
layout->addWidget(label);
layout->addWidget(showtext);
layout->addWidget(quit);
setLayout(layout);
}
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MyWidget widget;
widget.show();
return app.exec();
}
But it gives me the following Application Output error:
Starting /home/simulab-3/Documentos/Qt/Training2010/Texto/Texto-build-desktop/Texto...
Object::connect: No such slot QWidget::setTextLabel() in ../Texto/main.cpp:37
So what is wrong?
Thank you very much!!!
Lykurg
16th August 2010, 20:57
Use the Q_OBJECT macro and put each class in a separate file or explicit include the moc file.
rdelgado
16th August 2010, 21:25
Hi,
Did the Q_OBJECT and the separate files and it worked! Thanks a lot!
Powered by vBulletin® Version 4.2.5 Copyright © 2024 vBulletin Solutions Inc. All rights reserved.