简单QT应用到通过手写布局实现QT应用
新建QT項目
項目結(jié)構(gòu):
2.打開QT圖形編輯界面,通過拖動組件的方式生成如下界面:
3.為確定按鈕添加事件。選中按鈕à轉(zhuǎn)到槽,截圖如下:
點擊clicked按鈕,添加事件代碼如下:
?
4下面是手動編寫一個QT案例:
5.新建QT項目
項目結(jié)構(gòu):
?
編寫widget.h頭文件
#ifndef WIDGET_H
#define WIDGET_H
?
#include <QWidget>
#include <QPushButton>? //按鈕對應(yīng)的頭文件
#include <QVBoxLayout>? //布局,這個中布局讓組件上下顯示
#include <QHBoxLayout>? //這個布局讓組件水平顯示
#include <QGridLayout>? //Grid表格布局的頭文件
#include <QLineEdit>??? //單行文本框?qū)?yīng)的頭文件
#include <QLabel>??????//Label對應(yīng)的頭文件
?
class Widget : public QWidget
{
??? Q_OBJECT
?
public:
??? Widget(QWidget *parent= 0);
??? ~Widget();
private:
??? QPushButton *btn1;?? //定義一個按鈕
??? QHBoxLayout *layout1, *layout2;? //兩個布局
??? QVBoxLayout *layout3;
??? QGridLayout *layout4;
??? QLineEdit *edit1,*edit2,*edit3;
??? QLabel *label1;
??? QLabel *label2;
?
private slots:? //這里表示的是事件
??? void on_clicked();
};
?
#endif // WIDGET_H
?
6.編寫widget.cpp文件
#include "widget.h" ? Widget::Widget(QWidget *parent) ??? : QWidget(parent) { ??? layout1 = new QHBoxLayout; ??? layout2 = new QHBoxLayout; ??? //layout3 = new QVBoxLayout(this); ??? layout4 = new QGridLayout(this); ??? btn1 = new QPushButton; ??? edit1 = new QLineEdit; ??? edit2 = new QLineEdit; ??? edit3 = new QLineEdit; ??? label1 = new QLabel; ??? label2 = new QLabel;//這個控件沒有任何父控件 ? ??? //第一種布局方式 //??? layout1->addWidget(btn1); //??? layout1->addWidget(edit1); //??? layout1->addWidget(edit2); //??? layout1->addWidget(edit3); //??? layout2->addWidget(label1); //??? layout3->addLayout(layout1); //??? layout3->addLayout(layout2); ? ??? layout4->addWidget(btn1, 0, 0); ??? layout4->addWidget(edit1, 0, 1); ??? layout4->addWidget(edit2, 0, 2); ??? layout4->addWidget(edit3, 1, 0); ??? layout4->addWidget(label1, 1, 1); ??? btn1->setText("確定"); ? ??? //當點擊了btn1的時候就調(diào)用on_clicked()這個函數(shù) ??? //實現(xiàn)控件與具體的槽函數(shù)關(guān)聯(lián) ??? connect(btn1, SIGNAL(clicked()), this, SLOT(on_clicked())); } ? Widget::~Widget() { ??? //delete layout1;在QT內(nèi)部,不需要單獨delete一個控件的指針 ??? //QT的窗口在退出的時候會自動delete他相關(guān)的子控件 ??? delete label2; } ? void Widget::on_clicked() { ??? int a = edit1->text().toInt(); ??? int b = edit3->text().toInt(); ??? if (edit2->text() == "+") ??????? label1->setText(QString::number(a + b)); ??? if (edit2->text() == "-") ??????? label1->setText(QString::number(a - b)); ??? if (edit2->text() == "*") ??????? label1->setText(QString::number(a * b)); ??? if (edit2->text() == "/") ??? { ??????? if (b != 0) ??????????? label1->setText(QString::number(a / b)); ??? } } 7.main.cpp文件 #include "widget.h" #include <QApplication> ? int main(int argc, char *argv[]) { ??? QApplication a(argc, argv); ??? Widget w; ??? w.show(); ? ??? return a.exec(); } 8.窗口的效果: 與50位技術(shù)專家面對面20年技術(shù)見證,附贈技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的简单QT应用到通过手写布局实现QT应用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 台式华硕怎么进入bois模式 如何进入华
- 下一篇: C++中 auto自动变量,命名空间,u