添加小部件并将它们排列到Qt上的屏幕角落

时间:2018-08-01 13:01:50

标签: c++ qt user-interface layout qt5

我试图安排一些小部件,其中包括两个标签和一个图像在屏幕的右上方。我正在使用HBoxlayout。当我尝试将小部件添加到HBoxlayout的屏幕上时,所有小部件都没有布置在我希望它们放置的位置。因此,如何将它们排列在屏幕顶部。这是我尝试过的代码

#include "screen.h"
#include "ui_screen.h"
#include<QGridLayout>
#include<QLabel>
#include<QBitmap>

screen::screen(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::screen)
{
    ui->setupUi(this);
    QGridLayout *g=new QGridLayout();
    QHBoxLayout *h=new QHBoxLayout();
    QLabel *l=new QLabel();
    QLabel *l2=new QLabel();
    QLabel *l3=new QLabel();
    QPixmap p(":/img/img/user.jpg");
    l->setPixmap(p);
    l->setMask(p.mask());
    l->show();
    l->setStyleSheet("QLabel { background-color : red; color : blue; }");
    l2->setText("User");
    l3->setText("Value");
    h->addWidget(l,0,Qt::AlignRight);
    h->addWidget(l2,0,Qt::AlignRight);
    h->addWidget(l3,0,Qt::AlignRight);
    g->addLayout(h,0,0,1,1,Qt::AlignTop);
    this->setLayout(g);
    this->showFullScreen();
}

screen::~screen()
{
    delete ui;
}

我试图制作Sample layout

的布局

enter image description here

现在我还没有在代码中添加左侧标签。在此先感谢:)

1 个答案:

答案 0 :(得分:1)

试一下这样的布局:

#include "screen.h"
#include <QVBoxLayout>
#include <QLabel>
#include <QBitmap>
#include <QFrame>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    auto *widget = new QWidget(this);
    auto *frmLogin = new QFrame(this);
    auto *layoutMain = new QVBoxLayout(widget);
    auto *layoutTitle = new QHBoxLayout();
    auto *layoutLogin = new QHBoxLayout(frmLogin);
    auto *layoutInfo = new QVBoxLayout();
    auto *labTitle = new QLabel(tr("Some other stuff you want in the title"), this);
    auto *labBody = new QLabel(tr("Some other stuff you want in the body"), this);
    auto *labAvatar = new QLabel(this);
    auto *labUser = new QLabel(tr("User"), this);
    auto *labValue = new QLabel(tr("Value"), this);
    QPixmap p(":/pix/images/avatars/user.png");

    labTitle->setAlignment(Qt::AlignCenter);
    labTitle->setStyleSheet(".QLabel { background-color: white; }");

    labBody->setAlignment(Qt::AlignCenter);

    labAvatar->setPixmap(p);
    labAvatar->setMask(p.mask());

    layoutInfo->addWidget(labUser);
    layoutInfo->addWidget(labValue);

    layoutLogin->addWidget(labAvatar);
    layoutLogin->addLayout(layoutInfo);

    frmLogin->setStyleSheet(".QFrame { background-color : orange; }");
    frmLogin->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    layoutTitle->addWidget(labTitle);
    layoutTitle->addWidget(frmLogin);

    layoutMain->addLayout(layoutTitle);
    layoutMain->addWidget(labBody);
    layoutMain->setContentsMargins(0, 0, 0, 0);
    layoutMain->setSpacing(0);

    setCentralWidget(widget);
    showFullScreen();
}

上面的代码导致以下布局:

enter image description here