I want to set a widget as the background widget of a tab widget when there is no tab opened. I wish it will work in this way:
- Initially there is no tab in the tab widget, I want to add a widget as the background of the tab widget, the background widget will show some hint text as the placeholder.
- When the user opens any tab, the background will be hidden automatially, and the background widget won't handle any user events(clicks, double-clicked, keyboard events).
- When all tabs are closed, the background shows again.
Any ideas? Thanks.
CodePudding user response:
[Moved from comments]
From the requirements you outline it sounds as if you don't really need a separate widget. Something like the following should suffice...
#include <QApplication>
#include <QLabel>
#include <QPainter>
#include <QTabWidget>
namespace {
class tab_widget: public QTabWidget {
using super = QTabWidget;
public:
explicit tab_widget (QWidget *parent = nullptr)
: super(parent)
{}
protected:
virtual void paintEvent (QPaintEvent *event) override
{
super::paintEvent(event);
if (!count()) {
QPainter painter(this);
painter.drawText(rect(), Qt::AlignCenter, "Some informative text goes here...");
}
}
};
}
int
main (int argc, char **argv)
{
QApplication app(argc, argv);
tab_widget w;
for (int i = 0; i < 5; i) {
auto text = QString("Tab %1").arg(i);
w.addTab(new QLabel(text), text);
}
w.show();
return app.exec();
}