1

I have a label:

self.label = QtLabel(self)

that is inside of a VBoxLayout.

That I want to set in the center of a QWizardPage, no matter what size the window becomes. I managed to get it centered horizontally with:

self.label.setAlignment(QtCore.Qt.AlignCenter)  

but I cannot seem to get it to center vertically too. I've tried

self.label.setAlignment(QtCore.Qt.AlignVCenter)

and:

self.label.setAlignment(QtCore.Qt.AlignCenter | AlignVCenter)  

and a couple of other things that I cannot remember at this moment (I'll edit if I do). After reading this answer it seemed the problem had something to do with setting a min and max size. I tried that, setting MinimumHeight and MaximumHeight to 200. That roughly centered the label but it doesn't adapt to changes in the window's height, only its width.

How can I center this label directly in the middle of my page?

Community
  • 1
  • 1
Seth
  • 528
  • 3
  • 16
  • 32

2 Answers2

1

Add your label in between two spacer items. Your vertical layout should also be laid out in its parent widget so it takes full size of the parent.

QSpacerItem* verticalSpacer1 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
label = new QLabel(Form);
label->setAlignment(Qt::AlignCenter);
QSpacerItem* verticalSpacer2 = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);

verticalLayout->addItem(verticalSpacer1);
verticalLayout->addWidget(label);
verticalLayout->addItem(verticalSpacer2);
Lahiru Chandima
  • 22,324
  • 22
  • 103
  • 179
1

If you don't want to set a minimum size policy you could use QWidgets to do something like this:

QWizardPage.__init__(self)

    intro_text = "Some text that needs to be centered..."

    self.introVBox = QVBoxLayout(self)

    self.sizer_top = QWidget()
    self.sizer_top.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
    self.sizer_bottom = QWidget()
    self.sizer_bottom.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

    self.label = QLabel(self)
    self.label.setText(intro_text)
    self.label.setAlignment(QtCore.Qt.AlignCenter)
    self.introVBox.addWidget(self.sizer_top)
    self.introVBox.addWidget(self.label)
    self.introVBox.addWidget(self.sizer_bottom)
    self.setLayout(self.introVBox);
joshumax
  • 212
  • 2
  • 10