mainwindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFormLayout>
#include <QLabel>
#include <QLineEdit>
#include <QFrame>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
QFrame* loginForm = new QFrame(this);
QFormLayout* loginFormLayout = new QFormLayout(loginForm);
QLabel* LogInLabel = new QLabel("<h1> Login </h1>", this);
QLabel* UsernameLabel = new QLabel("Username: ", this);
QLabel* PasswordLabel = new QLabel("Password: ", this);
QLineEdit* usernameLineEdit = new QLineEdit();
QLineEdit* passwordLineEdit = new QLineEdit();
usernameLineEdit -> setFrame(false);
usernameLineEdit -> setMaxLength(30);
passwordLineEdit -> setFrame(false);
passwordLineEdit -> setMaxLength(30);
LogInLabel -> setStyleSheet("QLabel { font-family: Arial font-weight: bold }");
loginFormLayout -> setHorizontalSpacing(0);
loginFormLayout -> setVerticalSpacing(0);
loginFormLayout -> addRow(UsernameLabel, usernameLineEdit);
loginFormLayout -> addRow(PasswordLabel, passwordLineEdit);
loginFormLayout -> setFieldGrowthPolicy(QFormLayout::FieldsStayAtSizeHint);
loginFormLayout -> setFormAlignment(Qt::AlignHCenter | Qt::AlignTop);
loginForm -> setLayout(loginFormLayout);
loginForm -> setFrameStyle(QFrame::Panel | QFrame::Plain);
loginForm -> setFrameRect(QRect(440, 134, 400, 300));
loginForm -> setLineWidth(20);
this -> setCentralWidget(loginForm);
}
MainWindow::~MainWindow()
{
delete ui;
}
我没有在mainwindow.h
中改变任何东西.我想要一个QFrame,里面有QFormLayout,由两行QLabel-QLineEdit对组成。我希望整个东西是 400px 宽和 300px 高,QFrame的左上角在 (440, 134(。你能帮我找出为什么我没有达到所描述的结果吗?
使用QMainWindow::setCentralWidget
会使作为参数传递的小部件成为QMainWindow布局的主题,因此从此时开始,它的大小由布局管理。要获得所需的结果,请执行以下操作:
- 而不是
QFrame::setFrameRect
使用QFrame::setGeometry
- 注释掉
this -> setCentralWidget(loginForm)