Nominate our 2022 Qt Champions!

parent-child communication

  • hi.
    i have myScreen and myButton, both subclasses of QWidget. the button is a child of the screen. they need to exchange information. how can i get them to communicate?
    i'm thinking something like this:

    screen: i want you to be color number 2.
    button: ok.

    button: erm, what is color number 2?
    screen: green.
    button: ok, got it.

    IOW. the button needs to be able to request info from the screen. but how the **** do i do that? every approach i tried has resulted in error messages.

  • Moderators

    Usually it's done along the lines of:

    class IInfoProvider {
       virtual QColor getColor(int idx) = 0;
    class Button {
       void setColor(int idx, IInfoProvider* ip) { setColorSomehow(ip->getColor(idx));  }
    class Screen : public IInfoProvider {
       Button myButton;
       QColor getColor(int idx) override {  return colorFromIndexSomehow(idx);   }
       void doStuff() { myButton.setColor(2, this);  }
    Screen myScreen;

Log in to reply