How can I set a layout to a tab in QTabWidget?

KelvinS picture KelvinS · Mar 29, 2017 · Viewed 10k times · Source

I have created a QTabWidget (with no tabs) using the Qt Design tool, and now I need to create tabs and add widgets dynamically.

I can create the tab and add the widget using the following code:

MyCustomWidget *myCustomWidget = new MyCustomWidget(this);
ui->myTabWidget->addTab(myCustomWidget, "New Tab");

The problem is that the widget stays in the top left corner of my QTabWidget but I need to align it in the center (horizontally) of my QTabWidget.

How can I set a horizontal layout to this new tab created?

Note 1: My widget (MyCustomWidget) has a fixed size.

Note 2: I'm using Qt 5.3.

Answer

Rinat Veliakhmedov picture Rinat Veliakhmedov · Mar 29, 2017

It will always be in the top left corner. You can either add another widget on top of yours and them put your widget in the middle of that widget, or make your widget the size of the tab and position its content in the middle. You can use setLayout method of QWidget to set your widget layout.