这是一个通过输入体重和身高来计算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);
}
的main.cpp
#include <QApplication>
#include "bmiviewer.h"
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
BmiViewer w;
w.show();
return a.exec();
}
当我编译它时,它输出:Object :: connect:bmiviewer.cpp中没有这样的插槽BmiViewer :: calculateBmi():29
显示界面但未进行任何计算。
答案 0 :(得分:2)
添加行
public slots:
之前
void calculateBmi();
您从未将bmi函数声明为插槽,因此无法连接到。