zsalzbank
zsalzbank

Reputation: 9867

Pointer to QMainWindow Changing

I am using Qt to create a window and I have the following code (this is somewhat in pseudo-code):

class MyInterface {
    virtual void doupdate() = 0;
}

class InterfaceHandler {
    InterfaceHandler(MyInterface *i) {
      the_int = i;

      start_thread(&mainloop);
    }

    void mainloop() {
        while(1) the_int->doupdate();
    }

    MyInterface *the_int;
}

class console : public QMainWindow, public MyInterface {
    console() {
            InterfaceHandler x(this);
    }

    void doupdate() {
        //code to modify the gui
    }
} 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    console w(argc, argv);
    w.show();
    return a.exec();
}

My issue is that when the_int->doupdate() is called in mainloop(), the reference to the_int is wrong. I think this has to do with the fact that console inherits QMainWindow, but I am not sure what the solution is.

MyInterface doesn't always get inherited by a QObject. I've tried to split the doupdate() from console into another class which gets passed the reference to console in the constructor, but get the same result.

Any ideas?

Upvotes: 0

Views: 153

Answers (1)

Mat
Mat

Reputation: 206869

Assuming your "pseudo-code" is close enough to your real code, the following is the problem:

console() {
  InterfaceHandler x(this);
}

Once the constructor is done, x, being a local (automatic) variable, gets destroyed. The InterfaceHandler instance you created no longer exists once the constructor returns.

You need to keep x as a member variable of that class, or create and store it from somewhere else. (But keeping it as a member makes sense since the lifetimes of the objects are tied.) You also need to be very careful with that thread, it needs to be stopped before console is destroyed.

Upvotes: 1

Related Questions