Change label in Qt

I am trying to make a simple program consisting of a button and a label. When the button is pressed, it should change the label text to everything that is in the QString variable inside the program. Here is my code:

This is my widget.h file:

class Widget : public QWidget { Q_OBJECT public: Widget(QWidget *parent = 0); ~Widget(); private: Ui::WidgetClass *ui; QString test; private slots: void myclicked(); }; 

And here is the implementation of the Widget class:

 #include "widget.h" #include "ui_widget.h" Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::WidgetClass) { ui->setupUi(this); test = "hello world"; connect(ui->pushButton, SIGNAL(clicked()), ui->label, SLOT(myclicked())); } Widget::~Widget() { delete ui; } void Widget::myclicked(){ ui->label->setText(test); } 

It starts, but when the button is pressed, nothing happens. What am I doing wrong?

Edit: after I received it, the text in the label was larger than the label itself, so the text was cut off. I fixed it by adding ui->label->adjustSize() to myclicked () definition.

+4
source share
1 answer

You are connecting a signal to the wrong object. myclicked () is not a QLabel slot, it is a slot of your Widget class. The connection string should be:

 connect(ui->pushButton, SIGNAL(clicked()), this, SLOT(myclicked())); 

Take a look at the console output of your program. You should receive an error message:

Error connecting clicked () to myclicked (): such a slot is not defined in QLabel

+8
source

Source: https://habr.com/ru/post/1300421/


All Articles