简体   繁体   中英

How to align GUI elements like this? Qt, C++

I need to align elements on GUI: actually, a single label, but at the specific position. I know how to use QGridLayout, QHBoxLayout, I know how to change the font to have the specified size. However, I don't know how to align the label like on this picture below. Any advices?

在此处输入图片说明

Here is the most direct, but hardcoded way.

#include "widget.h"
#include <QLabel>
#include <QFont>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    QSize frameSize = this->frameGeometry().size() - this->geometry().size();

    this->resize(frameSize + QSize(250, 125));
    QLabel * label = new QLabel(this);// parenting instead of layouts
    label->resize(130, 32);
    label->move(60, 40);

    QFont f = label->font();
    f.setPointSize(16);
    label->setFont(f);

    label->setText("Sample");
    label->setFrameStyle(QFrame::Box);
}

Widget::~Widget()
{

}

Layouts and alignments are a much better solution, but if you really want to give numbers to everything... Also look into using forms. It makes "hardcoding" sizes and layouts a lot easier.

Hope that helps.

If you want the proportions, but have it resizeable, you can use QBoxLayouts and the addStretch() method. Roughly you have a 1/2/1 proportion, so you first add a stretch with stretch 1, then your widget with stretch 2 and then another stretch with stretch 1. That would be for the horizontal layout, you would then take that layout and put it in a vertical layout with 1/1/1 stretches.

If you know abut layouts and how to use them than great.

To tweak this after you have a layout you should use a style sheet . Here are some examples . You can set a style sheet on QApplication .

QPushButton#buttonName {
    margin-top: 30px;
    margin-bottom: 30px;
    margin-left: 60px;
    margin-right: 60px;
    min-width: 130px;
    min-height : 32px;
}

PS. I know this is student homework :P

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