C++ 在 Qt 中更改标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2207527/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Changing a label in Qt
提问by liewl
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:
我正在尝试制作一个由按钮和标签组成的简单程序。当按钮被按下时,它应该将标签文本更改为程序内 QString 变量中的任何内容。到目前为止,这是我的代码:
This is my widget.h file:
这是我的 widget.h 文件:
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:
这是 Widget 类的实现:
#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 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().
编辑:在我让它工作后,标签中的文本比标签本身大,所以文本被剪掉了。我通过添加ui->label->adjustSize()
到 myclicked() 的定义来修复它。
回答by erelender
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:
您将信号连接到错误的对象。myclicked() 不是 QLabel 的插槽,它是您的 Widget 类的插槽。连接字符串应该是:
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
将 clicked() 连接到 myclicked() 时出错:QLabel 中没有定义这样的插槽