简体   繁体   中英

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. I get the invalid use of 'this' in a non-member function error. 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. 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.

It seems you want to connect the clicked() signal to the onClicked() function on an instance of MyObject . That means you need to first of all create an instance of the MyObject class. 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.

From my example code above, my_object.text is a totally different variable from text . The same with my_object.a and a , of course.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM