1.一个简单的QT程序(QPushButton)
/* 应用程序抽象类 */ #include <QApplication> /*窗口类*/ #include <QWidget> /* 按钮 */ #include <QPushButton> int main(int argc, char* argv[]) { QApplication app(argc, argv); /* 构造一个窗口*/ QWidget w; /*显示窗口*/ w.show(); /* 按钮也是个窗口 */ QPushButton button; button.setText("Button"); /* 窗口对象的父子关系,影响显示位置 */ /* 没有父窗口的窗口,我们称之为主窗口 */ button.setParent(&w); button.show(); /* 设置按钮的坐标位置 */ button.setGeometry(30, 30, 100, 30); /* QT对C++的拓展 */ // std::bind std::function QObject::connect(&button, SIGNAL(clicked()), &w, SLOT(close())); w.setWindowTitle("Hello World"); /*在exec中有一个消息循环*/ return app.exec(); }
PS:需要在.pro文件中声明
SOURCES += qgridlayoutdemo.cpp QT += gui widgets
才能正常运行。
运行结果:
2.QLineEdit, QLabel, QGridLayout, QHBoxLayout的用法
#include <QApplication> #include <QWidget> #include <QGridLayout> #include <QLabel> #include <QLineEdit> #include <QTextEdit> #include <QHBoxLayout> #include <QPushButton> int main(int argc, char *argv[]) { QApplication app(argc, argv); QWidget w; QGridLayout *layout = new QGridLayout; layout->setColumnStretch(0, 1); layout->setColumnStretch(1, 4); layout->setColumnStretch(2, 1); layout->setColumnStretch(3, 1); layout->setColumnStretch(4, 4); QLabel *lb_first_name = new QLabel("First Name:"); QLineEdit *ed_first_name = new QLineEdit; QLabel *lb_last_name = new QLabel("Last Name:"); QLineEdit *et_last_name = new QLineEdit; QLabel *lb_sex = new QLabel("Sex:"); QLineEdit *et_sex = new QLineEdit; QLabel *lb_birthday = new QLabel("Birthday:"); QLineEdit *et_birthday = new QLineEdit; QLabel *lb_address = new QLabel("Address:"); QTextEdit *te_edit = new QTextEdit; layout->addWidget(lb_first_name, 0, 0); layout->addWidget(ed_first_name, 0, 1); layout->addWidget(lb_last_name, 0, 3); layout->addWidget(et_last_name, 0, 4); layout->addWidget(lb_sex, 1, 0); layout->addWidget(et_sex, 1, 1); layout->addWidget(lb_birthday, 1, 3); layout->addWidget(et_birthday, 1, 4); layout->addWidget(lb_address, 2, 0); layout->addWidget(te_edit, 3, 0, 1, 5); // QGridLayout layout; // QLineEdit *pwd; // layout.setColumnStretch(0, 1); // layout.setColumnStretch(3, 1); // layout.setRowStretch(0, 1); // layout.setRowStretch(4, 1); // layout.addWidget(new QLabel("UserName:"), 1, 1); // layout.addWidget(new QLineEdit(), 1, 2); // layout.addWidget(new QLabel("Password"), 2, 1); // layout.addWidget(pwd = new QLineEdit(), 2, 2); // QHBoxLayout *hBoxLayout; // layout.addLayout(hBoxLayout = new QHBoxLayout(), 3, 2); // hBoxLayout->addStretch(1); // hBoxLayout->addWidget(new QPushButton("Login")); // pwd->setEchoMode(QLineEdit::Password); w.setLayout(layout); w.setWindowTitle("QGridLayoutDemo"); w.show(); return app.exec(); }
运行结果: