qt输入生日输出年龄代码
时间: 2023-05-30 13:04:20 浏览: 146
以下是一个基本的Qt代码示例,用于输入生日并计算年龄:
```c++
#include <QtWidgets/QApplication>
#include <QtWidgets/QWidget>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QHBoxLayout>
#include <QDate>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QWidget *window = new QWidget;
window->setWindowTitle("Age Calculator");
QLabel *birthLabel = new QLabel("Enter your birth date:");
QLineEdit *birthLineEdit = new QLineEdit;
QPushButton *calculateButton = new QPushButton("Calculate");
QLabel *ageLabel = new QLabel("Your age is:");
QHBoxLayout *layout = new QHBoxLayout;
layout->addWidget(birthLabel);
layout->addWidget(birthLineEdit);
layout->addWidget(calculateButton);
layout->addWidget(ageLabel);
window->setLayout(layout);
QObject::connect(calculateButton, &QPushButton::clicked, [=]() {
QDate birthDate = QDate::fromString(birthLineEdit->text(), "yyyy-MM-dd");
QDate currentDate = QDate::currentDate();
int age = birthDate.daysTo(currentDate) / 365;
ageLabel->setText(QString("Your age is: %1").arg(age));
});
window->show();
return app.exec();
}
```
该代码使用Qt的基本部件(QApplication,QWidget,QLabel,QLineEdit,QPushButton和QHBoxLayout)创建了一个简单的窗口,其中用户可以输入他们的生日,并在点击“Calculate”按钮后计算他们的年龄。该代码使用QDate类来计算年龄,然后将结果显示在标签中。
相关推荐
















