遍历QObject
static void printName(QObject *obj)
{
if(obj)
{
cout << obj->objectName().toStdString(); //获取QObject的名称
const QMetaObject *meta = obj->metaObject(); //获取QObject的类型
cout << " : " << meta->className() << endl;
if(obj->objectName() == "lineEdit")
{
QLineEdit *le = qobject_cast<QLineEdit *>(obj); //QObject类型转换
le->setText("你好");
}
QObjectList cl = obj->children(); //获取QObject的子节点
if(cl.size())
{
for(int i = 0; i < cl.size(); ++i)
{
printName(cl[i]);
}
}
}
}
QV/HBoxLayout
QLayout提供了四种布局:QVBoxLayout、QHBoxLayout、QGridLayout、QFormLayout
sizeHint() 获取推荐尺寸(在layout中才生效)
setSizePolicy() 设置尺寸策略,可设置为fixed推荐大小、Expanding尽量缩放,最小值是推荐值、Ignored忽略推荐大小,尽量缩放
setMinimumSize() 设置最小尺寸
setMaximumSize() 设置最大尺寸
setContentsMargins() 设置边框
setSpacing() 设置元素间距
QGridLayout
addWidget(QObject, 行, 列)
setHorizontalSpacing() 设置水平间距
setVerticalSpacing() 设置垂直间距
QFormLayout
TestQFormLayout::TestQFormLayout(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
QFormLayout *lay = new QFormLayout(this);
QLineEdit *name = new QLineEdit();
lay->addRow("name", name); //label对象只能为const QString,field对象为QWidget
QLineEdit *age = new QLineEdit();
lay->addRow("age", age);
QLineEdit *email = new QLineEdit();
lay->addRow("email", email);
QLabel *info = new QLabel();
info->setText("info");
info->setStyleSheet("color:rgb(255, 0, 0)");
lay->insertRow(0, "", info); //插入第1行
QPushButton *save = new QPushButton("Save");
QPushButton *clear = new QPushButton("Clear");
QObject::connect(save, SIGNAL(clicked()), this, SLOT(Save()));
QObject::connect(clear, SIGNAL(clicked()), this, SLOT(Clear()));
QHBoxLayout *hlay = new QHBoxLayout();
hlay->addWidget(save);
hlay->addWidget(clear);
lay->addRow(hlay);
}
void TestQFormLayout::Save()
{
QFormLayout *lay = (QFormLayout *)this->layout(); //获取this的布局对象
QLabel *label = (QLabel *)lay->itemAt(0, QFormLayout::FieldRole)->widget(); //获取第一行布局中的field对象
QString info = "";
for (int i = 0; i < lay->rowCount(); ++i) //获取行数
{
QLineEdit *e = (QLineEdit *)lay->itemAt(i, QFormLayout::FieldRole)->widget();
if (e)
{
QLayoutItem *itemLabel = lay->itemAt(i, QFormLayout::LabelRole);
if(itemLabel)
{
QLabel *labelTitle = (QLabel *)itemLabel->widget();
if (labelTitle)
{
if (e->metaObject()->className() == QStringLiteral("QLineEdit"))
{
if(e->text().trimmed() == "") //去除头尾空格
{
e->setFocus(); //设为焦点
info += labelTitle->text();
info += " is empty!\n";
}
}
}
}
}
}
label->setText(info);
}
void TestQFormLayout::Clear()
{
QFormLayout *lay = (QFormLayout *)this->layout();
for (int i = 0; i < lay->rowCount(); ++i)
{
QLayoutItem *item = lay->itemAt(i, QFormLayout::FieldRole);
QLineEdit *e = (QLineEdit *)item->widget();
if (e)
{
if (e->metaObject()->className() == QStringLiteral("QLineEdit"))
{
e->setText("");
}
}
}
}