Is it possible to have a QWidget as a child to a QObject?
Asked Answered
B

2

5

My main application object is a QObject, that juggles a QSystemTrayIcon, a QDialog, a QWindow and a few other components. The app mostly sits in the tray, with some options dialogs etc etc.

Now, I'd like to use QMetaObject::connectSlotsByName() to connect signals from these objects to slots in the main object. It's 10-15 of them, so writing them by hand doesn't seem efficient, right, professional, modern, etc etc.

However, I can't use my QObject as parent to the QWidget based objects, nor can I change the object to inherit QWidget, as they will not show up, since the main object isn't visible.

Ideas?

Breechblock answered 18/10, 2009 at 20:50 Comment(1)
Related question (not a duplicate): https://mcmap.net/q/929286/-what-are-consequences-of-forcing-qobject-as-a-parent-of-qwidget/1329652Triolet
F
2

Connecting signals to slots manually is perfectly fine. Qt itself is doing that, most Qt applications are doing that.

I'm afraid you can't use connectSlotsByName for the parent-child issues with QWidget, but if you really want it, you have all the metadata available in QMetaObject, so you can write a function that works like connectSlotsByName on any pair/set of QObjects.

Fcc answered 18/10, 2009 at 21:23 Comment(1)
I connect some slots too, it's just a bother to do it with 10-20 of them. :) .. Writing my own function sounds like a good plan though. Thanks!Breechblock
C
3

You could promote the QObject to a hidden QWidget, see this answer. In a nutshell:

#include <QtWidgets>

int main(int argc, char ** argv) {
   QApplication app{argc, argv};
   QWidget parent;
   QLabel l1{"Close me to quit!"}, l2{"Hello!"};
   for (auto label : {&l1, &l2}) {
      label->setMinimumSize(200, 100);
      label->setParent(&parent);
      label->setWindowFlags(Qt::Window);
      label->setText(QString("%1 Parent: %2.").
                     arg(label->text()).arg((quintptr)label->parent(), 0, 16));
      label->show();
   }
   l2.setAttribute(Qt::WA_QuitOnClose, false);
   return app.exec();
}
Corticosteroid answered 3/3, 2017 at 20:11 Comment(0)
F
2

Connecting signals to slots manually is perfectly fine. Qt itself is doing that, most Qt applications are doing that.

I'm afraid you can't use connectSlotsByName for the parent-child issues with QWidget, but if you really want it, you have all the metadata available in QMetaObject, so you can write a function that works like connectSlotsByName on any pair/set of QObjects.

Fcc answered 18/10, 2009 at 21:23 Comment(1)
I connect some slots too, it's just a bother to do it with 10-20 of them. :) .. Writing my own function sounds like a good plan though. Thanks!Breechblock

© 2022 - 2024 — McMap. All rights reserved.