qt 之簡單計算器
阿新 • • 發佈:2018-11-23
在這裡插入圖片描述
工程檔案,的說明如上圖,
設計的視窗和計算演示如下:
其中test.h的程式碼如下:
#ifndef TEST1_H #define TEST1_H #include <QtWidgets/QMainWindow> #include "ui_test1.h" class test1 : public QMainWindow { Q_OBJECT public: test1(QWidget *parent = 0); ~test1(); //新增這一段程式碼 public slots://槽函式宣告標誌 void caculate(); private: Ui::calculator ui; }; #endif // TEST1_H
視窗類test1,繼承QMainWindow,同時要有Q_OBJECT,它的定義如下:
#define Q_OBJECT \ public: \ Q_OBJECT_CHECK \ QT_WARNING_PUSH \ Q_OBJECT_NO_OVERRIDE_WARNING \ static const QMetaObject staticMetaObject; \ virtual const QMetaObject *metaObject() const; \ virtual void *qt_metacast(const char *); \ virtual int qt_metacall(QMetaObject::Call, int, void **); \ QT_TR_FUNCTIONS \ private: \ Q_OBJECT_NO_ATTRIBUTES_WARNING \ Q_DECL_HIDDEN_STATIC_METACALL static void qt_static_metacall(QObject *, QMetaObject::Call, int, void **); \ QT_WARNING_POP \ struct QPrivateSignal {}; \ QT_ANNOTATE_CLASS(qt_qobject, "") /* qmake ignore Q_OBJECT */ 接下來是類的建構函式的宣告和解構函式的宣告,建構函式和解構函式的定義在test1.cpp裡,如下: `test1::test1(QWidget *parent) : QMainWindow(parent) { ui.setupUi(this); //新增關聯程式碼,必須放在 setupUi 函式之後,訊號與槽機制 connect(ui.cal, SIGNAL(clicked()), this, SLOT(caculate())); } test1::~test1() { }` 可以看到,建構函式裡包含兩個東西,第一個是啟動Ui函式,第二個是connect函式,將訊號SIGNAL(clicked())和槽SLOT(caculate())連線起來,其中ui.cal,cal是click的物件。 其中caculate()函式的定義在test1.cpp中,宣告在test1.h中,定義如下:
void test1::caculate()
{
QString estr1 = “can not devide 0!”;
QString estr2 = “please choose caculate option!”;
double n1 = ui.num1->text().toDouble(); double n2 = ui.num2->text().toDouble(); double out = 0; if (ui.plus->isChecked()) { out = n1 + n2; } else if (ui.minus->isChecked()) { out = n1 - n2; } else if (ui.mutiply->isChecked()) { out = n1 * n2; } else if (ui.div->isChecked()) { out = n1 / n2; } else { ui.result->setText(estr2); return; } ui.result->setText(QString::number(out, 'f', 10));
}
main.cpp函式主要執行視窗,
`#include "test1.h"
#include <QtWidgets/QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
test1 w;
w.show();
return a.exec();
}`