Make QPushButton invisible yet still work?

mrg95 picture mrg95 · Jul 15, 2013 · Viewed 10.6k times · Source

In my project, I have some pushbuttons that change between visible and invisible using this:

ui->button->setVisible(true);
//or
ui->button->setVisible(false);

However, it seems that when they are invisible, they also do not work? How can I get around this?

I have already tried this:

ui->button->setEnabled(true);

for all of them but nothing changes.

Answer

Fred picture Fred · Jul 15, 2013

When you call QWidget::setVisible(false), you not only hide it from view, but also logically remove it from the layout, so it is no longer there to respond to key presses or mouse clicks. What you want is to keep the widget there while not displaying it. What I would try in your situation is changing the QPalette associated with your QPushButton to make it transparent (i.e. invisible)

// Make the button "invisible"
QBrush tb(Qt::transparent); // Transparent brush, solid pattern
ui->button->setPalette(QPalette(tb, tb, tb, tb, tb, tb, tb, tb, tb)); // Set every color roles to the transparent brush

// Make the button "visible"
ui->button->setPalette(QPalette()); // Back to the default palette

That way, the button is still logically in the layout (and take up the appropriate space), but it does not show up because it's completely displayed with a transparent color.