我很难对齐多个qt小部件(标签和按钮)。我想要小部件(分别用绿色和红色)排成一行。有什么建议?
#include <QVBoxLayout>
#include <QLabel>
#include <QPushButton>
#include "ui_dialog.h"
Dialog::Dialog(QWidget *parent)
: QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
QVBoxLayout * const layout = new QVBoxLayout(ui->scrollAreaWidgetContents);
for(int i=0; i!=100; ++i)
{
QLabel *label = new QLabel();
layout->addWidget(label);
label->setText(QString::number(i));
label->setStyleSheet("background-color: red");
label->setFixedWidth(100);
QPushButton *pushButton = new QPushButton();
layout ->addWidget(pushButton);
int menu_x_pos = label->pos().x();
int menu_y_pos = label->pos().y();
pushButton->setGeometry(menu_x_pos+120, menu_y_pos,10,20);
pushButton->setText(QString::number(i));
pushButton->setStyleSheet("background-color: green");
}
}
Dialog::~Dialog()
{
delete ui;
}
答案 0 :(得分:2)
使用QVBoxLayout
会垂直排序小部件。要水平排列2个小部件,可以使用QFormLayout
:
#include <QLabel>
#include <QPushButton>
#include <QFormLayout>
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
QFormLayout * const formlayout = new QFormLayout(ui->scrollAreaWidgetContents);
for(int i=0; i!=100; ++i)
{
QLabel *label = new QLabel();
label->setText(QString::number(i));
label->setStyleSheet("background-color: red");
label->setFixedWidth(100);
QPushButton *pushButton = new QPushButton();
int menu_x_pos = label->pos().x();
int menu_y_pos = label->pos().y();
pushButton->setGeometry(menu_x_pos+120, menu_y_pos,10,20);
pushButton->setText(QString::number(i));
pushButton->setStyleSheet("background-color: green");
formlayout->insertRow(i,label,pushButton);
}
}
这就是它的样子:
现在,对于连续更多的小部件,它们略有不同,您可以使用QHBoxLayout
布局以及表单布局,将所有小部件排列在一个水平布局中,然后将该布局添加为row
到您的表单布局:
#include <QLabel>
#include <QPushButton>
#include <QFormLayout>
#include <QCheckBox>
#include <QHBoxLayout>
#include <QLineEdit>
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
QFormLayout * const formlayout = new QFormLayout(ui->scrollAreaWidgetContents);
QHBoxLayout* hlayout[100];
QLineEdit* lineEdit[100];
for(int i=0; i!=100; ++i)
{
hlayout[i] = new QHBoxLayout();
QLabel *label = new QLabel();
label->setText(QString::number(i));
label->setStyleSheet("background-color: red");
label->setFixedWidth(100);
hlayout[i]->addWidget(label);
//
QPushButton *pushButton = new QPushButton();
int menu_x_pos = label->pos().x();
int menu_y_pos = label->pos().y();
pushButton->setGeometry(menu_x_pos+120, menu_y_pos,10,20);
pushButton->setText(QString::number(i));
pushButton->setStyleSheet("background-color: green");
hlayout[i]->addWidget(pushButton);
//
QCheckBox *checkbox = new QCheckBox();
checkbox->setText("CheckB:");
hlayout[i]->addWidget(checkbox);
//
lineEdit[i] = new QLineEdit;
lineEdit[i]->setText("Text");
hlayout[i]->addWidget(lineEdit[i]);
// now line up all widgets in a row
formlayout->insertRow(i,hlayout[i]);
}
}