开发者

Changing a label in Qt

I'm 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 whatever is in a QString variable inside the program. Here's my code so far:

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's the implementation of the Widget class:

#include "widget.h"
#in开发者_StackOverflowclude "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 runs but when the button is clicked, nothing happens. What am I doing wrong?

Edit: after i got it working, the text in the label was larger than the label itself, so the text got clipped. I fixed it by adding ui->label->adjustSize() to the definition of myclicked().


You are connecting the signal to the wrong object. myclicked() is not a slot of QLabel, 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. There should be an error message saying something like:

Error connecting clicked() to myclicked(): No such slot defined in QLabel

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜