[英]Little issue with 'this' (invalid use of 'this' in a non-member function)
When I have solved this I am finally done with my prog :D As always, a model of the problem is below.当我解决了这个问题后,我终于完成了我的编 :D 一如既往,问题的模型如下。 I get the invalid use of 'this' in a non-member function
error.我invalid use of 'this' in a non-member function
错误中得到了invalid use of 'this' in a non-member function
的invalid use of 'this' in a non-member function
。 It seems to me I have done everything correctly: I have moved the class outside the main
function and I have also not forgotten the Q_OBJECT
macro... Could anybody please help me here and please mind that I am new to OOP.在我看来,我所做的一切都是正确的:我已经将类移到了main
函数之外,而且我也没有忘记Q_OBJECT
宏......有人可以在这里帮助我,请注意我是 OOP 的新手。 Thank you!谢谢!
#include <QtGui>
#include <QtCore>
class MyObject : public QObject
{
Q_OBJECT
public:
QTextEdit text;
QString a;
public slots:
void onClicked() {
text.setText(a);
}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QWidget mw;
mw.setWindowTitle("Main Window");
mw.resize(400, 400);
mw.show();
QLabel label ("Enter something:", &mw);
label.setAlignment(Qt::AlignHCenter);
label.show();
QLineEdit line (&mw);
line.show();
QString a = line.text();
QTextEdit text (&mw);
text.show();
QPushButton btn ("Convert", &mw);
QObject::connect(
&btn,
SIGNAL(clicked()),
this, /* the compiler keeps complaining... */
SLOT(onClicked()));
btn.show();
QVBoxLayout layout_mw;
layout_mw.addWidget(&label);
layout_mw.addWidget(&line);
layout_mw.addWidget(&btn);
layout_mw.addWidget(&text);
mw.setLayout(&layout_mw);
return app.exec();
}
You can't use this
outside a non-static member function.您不能在非静态成员函数之外使用this
。
It seems you want to connect the clicked()
signal to the onClicked()
function on an instance of MyObject
.您似乎想将clicked()
信号连接到MyObject
实例上的onClicked()
函数。 That means you need to first of all create an instance of the MyObject
class.这意味着您首先需要创建MyObject
类的一个实例。 Then use a pointer to that object as the receiver of the signal:然后使用指向该对象的指针作为信号的接收者:
MyObject my_object;
QObject::connect(
&btn,
SIGNAL(clicked()),
&my_object,
SLOT(onClicked()));
Be careful though, because the member variables in MyObject
have nothing related with the local variables with the same name in the main
function.不过要小心,因为MyObject
的成员变量与main
函数中的同名局部变量没有任何关系。
From my example code above, my_object.text
is a totally different variable from text
.从我上面的示例代码来看, my_object.text
是一个与text
完全不同的变量。 The same with my_object.a
and a
, of course.当然, my_object.a
和a
也是如此。
As shown in a comment to your question , there are better ways to do what you want, without the need to create the MyObject
class.如对您的问题的评论所示,有更好的方法可以做您想做的事,而无需创建MyObject
类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.