QT基础
QWidget
- 空的父系窗口,可以包含QPushbutton、QLineEdit、Layout等部件
QWidget w;
w.setWindowTitle("zzz");
// 显示窗口
w.show();
QPushButton
- 按钮也是一个窗口 继承QWidget
QPushButton button;
button.setText("quit");
- 窗口之间存在父子关系,没有父子对象的窗口为主窗口
button.setParent(&w);
- setGeometry(x, y, l, w) 设置几何位置
button.setGeometry(20,20,100,30);
QLineEdit
- 文本输入框
QLineEdit edit;
edit.setParent(&w);
- 显示方式(输入密码那种样子)
edit.setEchoMode(QLineEdit::Password);
edit.text();
输入匹配
(1) 创建一个预期的QStringList
(2) 创建一个QCompleter completer(QStringList()<<””);
(3) 匹配模式
completer.setFilterMode(Qt::MatchContains)(4) 设置模式到QLineEdit
QCompleter completer(QStringList()<<"123" <<"abc");
completer.setFilterMode(Qt::MatchContains);
edit.setCompleter(&completer);
- 默认显示
edit.setPlaceholderText("gogogo");
edit.setParent(&w);
Layout
用QVBoxLayout、QHBoxLayout、QGridLayout 创建一个Layout
将按钮啥的放到 部件 里 layout.addWidget()
将Layout放到 QWidget 里 addWidget(& layout)
- 添加空位addSpacing
- addStretch 弹簧一样将layout中的 部件 压到一块 参数为比例
QHBoxLayout h_layout;
// addWidget 第二个参数是部件的长度比例
h_layout.addWidget(&button,1);
h_layout.addWidget(&edit,2);
h_layout.addStretch(2);
w.setLayout(&h_layout);
- QGridLayout 矩阵式多个部件
QGridLayout g_layout;
// QGridLayout 矩阵式多个部件
g_layout.addWidget(&button,0,0);
g_layout.addWidget(&edit,0,1);
g_layout.addWidget(new QPushButton("1, 0"),1,0);
g_layout.addWidget(new QPushButton("1, 1"),1,1);
g_layout.setColumnStretch(2,1);
g_layout.setRowStretch(2,1);
w.setLayout(&g_layout);
例子
// 登录界面
/* 1. 居中
* 2. 用户名 label edit
* 3. 密码 label edit
* 4. 确认 button
* */
QWidget *w = new QWidget;
QLabel *m_l_username = new QLabel;
QLabel *m_l_passwd = new QLabel;
QLineEdit *m_e_username = new QLineEdit;
QLineEdit *m_e_passwd = new QLineEdit;
QPushButton *m_login_bt = new QPushButton;
QGridLayout *m_login_glayout = new QGridLayout;
QHBoxLayout *m_login_bt_l = new QHBoxLayout;
m_l_username->setText("用户名:");
m_login_glayout->addWidget(m_l_username,1,1);
// m_login_glayout->setSpacing(10);
m_e_username->setMaxLength(8);
m_login_glayout->addWidget(m_e_username,1,2);
m_l_passwd->setText("密码:");
m_login_glayout->addWidget(m_l_passwd,2,1);
m_login_glayout->setSpacing(10);
m_e_passwd->setEchoMode(QLineEdit::Password);
m_login_glayout->addWidget(m_e_passwd,2,2);
m_login_glayout->setRowStretch(0,1);
m_login_glayout->setColumnStretch(0,1);
m_login_glayout->setRowStretch(4,1);
m_login_glayout->setColumnStretch(4,1);
m_login_bt->setText("登录");
m_login_bt_l->addStretch(1);
m_login_bt_l->addWidget(m_login_bt);
m_login_glayout->addLayout(m_login_bt_l,3,2);
// m_login_glayout->addWidget(m_login_bt,3,2);
w->setLayout(m_login_glayout);
// w->setLayout()
w->show();