Qt实现计算器
程序员文章站
2024-03-22 19:04:16
...
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
int on_resultButton_clicked();
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QMessageBox>
#include<QString>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
int MainWindow::on_resultButton_clicked()
{
double first=ui->firstInput->text().toDouble();
double second=ui->secondInput->text().toDouble();
double result;
if(ui->comboBox->currentText()=="+")
{
result=first+second;
}
else if(ui->comboBox->currentText()=="-")
{
result=first-second;
}
else if(ui->comboBox->currentText()=="*")
{
result=first*second;
}
else if(ui->comboBox->currentText()=="/")
{
if(second==0)
{
QMessageBox::information(this,"Error","the second can not be 0");
return 0;
}
else
{
result=first/second;
}
}
QString string;
ui->resultLabel->setText(string.setNum(result));
return 0;
}
main.cpp
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}