简体   繁体   中英

Widget inside another widget Qt

I am trying to achieve this layout:

在此输入图像描述

where Widget1 is some widget (central widget of QMainWindow) and I want to add second widget Widget2 over it but it should be in left bottom corner of Widget1.


EDIT: my previous description wasn't very useful so I will try to describe it in more details.

I am inheriting QWidget class ( class MyClass : public QWidget ) and creating my own widget where I in void MyClass ::paintEvent(QPaintEvent *event) draw something on screen. MyClass is then centralWidget of my QMainWindow .

Now on top of that I want to add smaller widget (Widget2 in image) where I would display some video (here I am not asking how to display video only how to add this Widget2 to my view). Main thing here is that Widget2 is inside (floating in) Widget1.

EDIT2: Previous code I posted is rubbish.

Use QGridLayout to set the position of the widget:

QGridLayout* layout = new QGridLayout(this);
// 2x2 layout
QWidget* green = new QWidget(this);
green->setStyleSheet("background:green;");
QWidget* yellow = new QWidget(this);
yellow->setStyleSheet("background:yellow;");
QWidget* red = new QWidget(this);
red->setStyleSheet("background:red;");
QWidget* blue = new QWidget(this);
blue->setStyleSheet("background:blue;");
layout->addWidget(green, 0, 0); // Top-Left
layout->addWidget(yellow, 0, 1); // Top-Right
layout->addWidget(red, 1, 0); // Bottom-Left
layout->addWidget(blue, 1, 1); // Bottom-Right
ui->centralWidget->setLayout(layout);

Will give you something like that:

在此输入图像描述

So, custom your own widget using QGridLayout and set the position of your widget inside it.

Set another widget as parent with black background:

QGridLayout* layout = new QGridLayout(this);
// 2x2 layout
QWidget* green = new QWidget(this);
green->setStyleSheet("background:green;");
QWidget* yellow = new QWidget(this);
yellow->setStyleSheet("background:yellow;");
QWidget* red = new QWidget(this);
red->setStyleSheet("background:red;");
QWidget* blue = new QWidget(this);
blue->setStyleSheet("background:blue;");
layout->addWidget(green, 0, 0); // Top-Left
layout->addWidget(yellow, 0, 1); // Top-Right
layout->addWidget(red, 1, 0); // Bottom-Left
layout->addWidget(blue, 1, 1); // Bottom-Right

QWidget* mainWidget = new QWidget(this);
mainWidget->setStyleSheet("background:black;");
mainWidget->setLayout(layout);

QHBoxLayout* centralLayout = new QHBoxLayout(this);
centralLayout->addWidget(mainWidget);
ui->centralWidget->setLayout(centralLayout);

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM