Sunday, 18 August 2013

Centering widgets in a dynamic layout?

Centering widgets in a dynamic layout?

I'm using the answer to this SO question here to make a custom image
widget which automatically scales correctly. It works fine but now I am
trying to center the image widget instance at the center of my main
window.
My idea was to create a QHBoxLayout, add the image widget to that, set the
alignment and then add the hBox instance to the ui->verticalLayout.
Doesn't work. The image still displays flush left with the error message:
QLayout: Attempting to add QLayout "" to MainWindow "MainWindow", which
already has a layout
I've tried a few variations on 'setAlignment` but then the image doesn't
appear at all. My simple test code is below.
What am I missing here?
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QPixmap pix;
pix.load("/Users/rise/Desktop/test.jpg");
ImageLabel2* image = new ImageLabel2(this);
image->setPixmap(pix);
QHBoxLayout* hbox = new QHBoxLayout(this);
hbox->addWidget(image);
// hbox->setAlignment(image,Qt::AlignCenter);
hbox->setAlignment(Qt::AlignHCenter);
// ui->verticalLayout->addLayout(hbox);
ui->verticalLayout->addLayout(hbox);
// ui->verticalLayout->addWidget(image);
// ui->verticalLayout->setAlignment(image,Qt::AlignCenter);
// ui->verticalLayout->setAlignment(Qt::AlignHCenter);
}

No comments:

Post a Comment