0

这是一个通过输入体重和身高来计算BMI的程序

#ifndef BMIVIEWER_H
#define BMIVIEWER_H
#include <QWidget>
#include <QGridLayout>
#include <QLineEdit>
#include <QLabel>
#include <QPushButton>
#include <QLCDNumber>
#include <QErrorMessage>
#include <QString>
#include <QMessageBox>

class BmiViewer : public QWidget {
   Q_OBJECT

public:

    BmiViewer();
    void calculateBmi();

private:
 QLineEdit* heightEntry;
 QLineEdit* weightEntry;
 QLCDNumber* result;
 QErrorMessage* error;
};

#endif // BMIVIEWER_H

bmiviewer.cpp

#include "bmiviewer.h"
BmiViewer::BmiViewer(){
setWindowTitle("MMI Calculator");
QGridLayout* layout = new QGridLayout;
QLabel* inputWeightRequest = new QLabel ("Enter weight in Kg:");
weightEntry = new QLineEdit;
QLabel* inputHeightRequest = new QLabel ("Enter height in meters:");
heightEntry = new QLineEdit;
QPushButton* calc = new QPushButton ("Calculate");
QLabel* labelbmi = new QLabel ("BMI");
result = new QLCDNumber;

result->setSegmentStyle(QLCDNumber::Flat);
result->setDigitCount(8);

layout->addWidget (inputWeightRequest, 0,0);
layout->addWidget (weightEntry, 0,1);
layout->addWidget (inputHeightRequest, 1,0);
layout->addWidget (heightEntry, 1,1);
layout->addWidget (calc, 2,1);
layout->addWidget (labelbmi, 3,0);
layout->addWidget (result, 3,1);

setLayout(layout);

//connect signals and slots

connect(calc,SIGNAL(clicked()),this, SLOT(calculateBmi()));

}

void BmiViewer::calculateBmi(){
int wanswer=0;
int hanswer=0;
double bmi;
QString iStr = weightEntry->text();
QString iStrh = heightEntry->text();
bool ok;
wanswer = iStr.toInt(&ok);
hanswer = iStrh.toInt(&ok);
if (!ok) {
 error = new QErrorMessage(this);
 error->showMessage("Please enter a valid integer");
 return;
}


    //calculate BMI

    bmi=wanswer/(hanswer*hanswer);
    result->display(bmi);

   }

主文件

#include <QApplication>
#include "bmiviewer.h"

int main(int argc, char *argv[]) {
    QApplication a(argc, argv);
    BmiViewer w;
    w.show();

    return a.exec();
}

当我编译它时它输出: Object::connect: No such slot BmiViewer::calculateBmi() in bmiviewer.cpp:29

它显示界面,但未进行任何计算。

4

1 回答 1

2

添加行

public slots:

void calculateBmi();

您从未将 bmi 函数声明为插槽,因此无法连接到它。

于 2012-05-14T04:49:40.567 回答