Layering components with QT
I am using QT Creator to develop a small GUI app. I have a GraphicsView component which spans the entire开发者_如何学C window. My question is, how can I place other widgets (such as transparent buttons) ontop of it in each of the four corners of the application. Also, how can I make sure that the lower right hand components get resized properly so that they stay in the lower right hand corner.
Ok, you can add a layout and QWidget
s to a QGraphicsView
so that they overlay the view underneath. You can't do this with QtDesigner (and I'm assuming QtCreator as well), so you'll have to do it in code. You can put the following code in the constructor of your window containing the QGraphicsView
(named view) and it will add two buttons to a layout that will keep them anchored at the bottom right of the view:
QGridLayout *gridLayout;
QSpacerItem *horizontalSpacer;
QSpacerItem *verticalSpacer;
QPushButton *button1;
QPushButton *button2;
gridLayout = new QGridLayout(view);
horizontalSpacer = new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Minimum);
verticalSpacer = new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding);
button1 = new QPushButton(view);
button1->setText("Button1");
button2 = new QPushButton(view);
button2->setText("Button2");
gridLayout->addWidget(button1, 1, 1, 1, 1);
gridLayout->addWidget(button2, 1, 2, 1, 1);
gridLayout->addItem(horizontalSpacer, 1, 0, 1, 1);
gridLayout->addItem(verticalSpacer, 0, 2, 1, 1);
It shouldn't be too much trouble to add two more buttons and two more spacers to achieve a button in each corner of the window.
Making standard QWidget
controls transparent can be a bit tricky, especially buttons. Labels are easy though. You can refer to my answer to another question here for some hints for making transparent QPushButtons
.
Ok I tried the thing with PySide now and it's not that bad.. Contrary to hacking the generated ui file, I'd suggest to do it afterwards! So I'm designing 2 cells in a QGridLayout and arrange everything side by side. have it compiled and when building the ui I:
# take 2nd item and add it back to 0, 0 cell in the grid layout
layer = self.ui.gridLayout.takeAt(1)
self.ui.gridLayout.addLayout(layer, 0, 0, 1, 1)
精彩评论