手工布局

  • 类名的命名除Q外开头首字母大写;
  • 函数命名,开头首字母小写;
  • 单个部件有setText()函数为设置部件表面文字;
  • 布局HBoxLayoutVBoxLayout可以添加窗口部件,也可以添加子布局
xxLayout->addWidget(B);
xxLayout->addLayout(C);
  • 主窗口QWidget有设置总体布局函数setLayout();还有添加命名函数setWindowTitle();显示主窗口函数show();
示例代码如下:
#include <QApplication> //***固定***
#include <QWidget> //窗口
#include <QLineEdit> //单行编辑器
#include <QLabel> //标签,可以是文字和图片
#include <QPushButton> //按钮
#include <QHBoxLayout> //水平布局
#include <QVBoxLayout> //垂直布局

int main(int argc, char** argv)// ***固定***
  QApplication app(argc,argv) //***固定***
  //新建主窗口
  QWidget *window = new QWidget;

  //新建标签
  QLabel *infoLabel=new QLabel;
  QLabel *cmdLabel=new QLabel;

  //新建单行编辑器
  QLineEdit *cmdLineEdit=new QLineEdit;

  //新建三个按钮
  QPushButton *button1=new QPushButton;
  QPushButton *button2=new QPushButton;
  QPushButton *button3=new QPushButton;

  //依次给各元素赋值
  infoLabel->setText("This is information");
  cmdLabel->setText("Print:");
  cmdLineEdit->clear(); //启动就清空
  button1->setText("One");
  button2->setText("Two");
  button3->setText("Three");

  //新建布局
  QHBoxLayout *qh1=new QHBoxLayout;
  QHBoxLayout *qh2=new QHBoxLayout;

  QVBoxLayout *mainLayout=new QVBoxLayout;
  /*
  布局类可以新加窗口子类的任何部件,如按钮,标签;也可以加已经子布局,层层包含。  
  */
  //编辑器和标签之间布局
  qh1->addWidget(cmdLabel);
  qh1->addWidget(cmdLineEdit);

  //按钮之间布局
  qh2->addWidget(button1);
  qh2->addWidget(button2);
  qh2->addWidget(button3);

 //整体布局
  mainLayout->addWidget(infoLabel);
  mainLayout->addLayout(qh1);
  mainLayout->addLayout(qh2);  

  //窗口赋值+显示
  window->setLayout(mainLayout);
  window->setWindowTitle("Hello");//主窗口设置名字
  window->show();//显示主窗口

  return app.exec();//***固定***
}
  • ui 文件里右键Chang objectName 可以用来修改文件在代码里的命名。
  • Ctrl+H为水平布局快捷键;Ctrl+V为垂直布局快捷键,Alt+Shift+R为预览窗口效果。
  • 文本右键Change rich Text,可以常规快速修改文本属性
  • 修改布局的时候,可以选中窗口右侧的文件列表,然后利用快捷键进行操作。
  • 主窗口进行垂直布局设置,可以使窗口在调整大小使保持部件一同增大和变小;
  • 对于想设置水平布局空隙,可以用Vertical spacerHorizontal spacer.
Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐