这里记录下Qt的学习过程:
先注明一下环境:Qt5.9.2+VS2015
在VS新建项目选择QT GUI Application 会自动生成三个文件 "main.cpp" 、“qtappliction.h”和”qtappliction.cpp”
以及ui文件 "QtGuiApplication1.ui" 和 ui头文件 "ui_QtGuiApplication.h"
用Qt_Designer打开ui文件可以发现里面已经包含了一个名为centralWidget的Widget对象。
而我们需要在“qtappliction.h”和”qtappliction.cpp”中添加我们需要的组件:QLabel和QPushButton以及QLineEdit
/*------------------------qtapplication.h-----------------------*/
#include "ui_QtGuiApplication.h"
#include <QLabel>
#include <QLineEdit>
#include <qpushbutton.h>
#include <QGridLayout>
/*宏定义*/
///
#define pi 3.1415926
class QtGuiApplication1 : public QMainWindow
{
Q_OBJECT
public:
QtGuiApplication1(QWidget *parent = Q_NULLPTR);
void InitConnect();
private:
QLabel *m_pLabel1, *m_pLabel2;
QLineEdit *m_pLineEdit1;
QPushButton * m_pPushbotton1;
bool m_bStartupIsOver;
private slots: //槽函数必须要注明,不然无法建立信号槽
void CalcArea();
private:
Ui::QtGuiApplication1Class ui;
};
/*----------------------------qtapplication.cpp-------------------*/
#include "qtapplication.h"
QtGuiApplication1::QtGuiApplication1(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this); //将ui跟我们的QtGuiApplication1对象关联
m_pLabel1 = new QLabel(this);
m_pLabel2 = new QLabel(this);
m_pLabel1->setText(tr("please write the radis"));
m_pLineEdit1 = new QLineEdit(this);
m_pPushbotton1 = new QPushButton(this);
m_pPushbotton1->setText(tr("build the area"));
QGridLayout *m_pGridLayout = new QGridLayout(this);
m_pGridLayout->addWidget(m_pLabel1, 0, 0);
m_pGridLayout->addWidget(m_pLabel2, 0, 1);
m_pGridLayout->addWidget(m_pLineEdit1, 1, 0);
m_pGridLayout->addWidget(m_pPushbotton1, 1, 1);
ui.centralWidget->setLayout(m_pGridLayout); //这里要注意必须将我们的控件加到ui的centralWidget,不然MainWindow是无法显示控件的
InitConnect(); //初始化信号槽配置
}
void QtGuiApplication1::InitConnect()
{
connect(m_pPushbotton1, SIGNAL(clicked()), this, SLOT(CalcArea())); //将按键的点击信号和面积计算函数建立信号槽
}
void QtGuiApplication1::CalcArea()
{
QString valueStr= m_pLineEdit1->text();
int valueInt = valueStr.toInt();
double area = valueInt*valueInt*pi;
QString tmpstr;
m_pLabel2->setText(tmpstr.setNum(area));
}
#include "QtGuiApplication1.h"
#include <QtWidgets/QApplication>
int main(int argc, char *argv[])
{
QApplication app(argc, argv); //创建qt应用
QtGuiApplication1 w; //创建窗口对象
w.show(); //显示窗口对象
return app.exec(); //执行应用消息循环
}
这是编译之后的运行结果:输入半径并点击按键会输出圆的面积