How can I call paintEvent() on custom widget
-
I created 3 QPushButton and I want to call paintEvent for them. I add some shapes to QPushButton. How can I call paintEvent() for all custom QPushButtons.
for(int i=0; i<buttonCount; i++) { QPushButton *btn = new QPushButton(QString::number(i)+". button"); btn->setGeometry(10*i, 10, 50, 50); layout()->addWidget(btn); } void MainWindow::paintEvent(QPaintEvent * event) { //I want to catch all *btns in here. How can I do that? }
-
Hi
you can simply defineQPushButton *btn
as a global variable and make instance of it everywhere you need.EDIT : I forgot to mention. as @Chris-Kawa It's a bad habit to use global variables. they truly are mess! but it's the easiest way :D
-
Please don't create global variables. It's a mess from design point of view.
You shouldn't call paintEvent manually. It is called by Qt when a widget needs to be redrawn. You can call update() to ask Qt to schedule such event. But don't call it from
paintEvent()
of a parent because it can lead to recursion.To answer your question, although it is not appropriate to solve this problem, if you want to get all the children of specific type from a parent you can call findChildren() e.g.
void MainWindow::someMethod() { QList<QWidget*> buttons = findChildren<QPushButton*>(); //do stuff to buttons }
If you want to only get some subset of the buttons you can use the regular expression overload of
findChildren()
to match some particular names.