写一个QT程序:点击按纽开始计时,2分钟次数加一,20分钟后停止
时间: 2023-12-19 09:05:04 浏览: 29
以下是一个简单的QT程序,实现了点击按钮开始计时,每2分钟次数加一,20分钟后自动停止计时的功能:
```cpp
#include <QtWidgets/QApplication>
#include <QtWidgets/QWidget>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QLabel>
#include <QtCore/QTimer>
class MainWindow : public QWidget {
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr) : QWidget(parent) {
// 创建计时器
timer = new QTimer(this);
// 设置计时间隔为2分钟
timer->setInterval(2 * 60 * 1000);
// 创建按钮和标签
startButton = new QPushButton("开始计时", this);
countLabel = new QLabel("0", this);
// 设置按钮和标签的位置和大小
startButton->setGeometry(100, 50, 100, 30);
countLabel->setGeometry(100, 100, 100, 30);
// 连接按钮的clicked()信号和自定义的startTimer()槽函数
connect(startButton, &QPushButton::clicked, this, &MainWindow::startTimer);
// 连接计时器的timeout()信号和自定义的updateCount()槽函数
connect(timer, &QTimer::timeout, this, &MainWindow::updateCount);
// 设置窗口的大小和标题
setFixedSize(300, 200);
setWindowTitle("计时器");
}
private:
QPushButton *startButton; // 开始按钮
QLabel *countLabel; // 次数标签
QTimer *timer; // 计时器
int count = 0; // 次数计数器
private slots:
void startTimer() {
// 启动计时器
timer->start();
// 20分钟后停止计时器
QTimer::singleShot(20 * 60 * 1000, [this]() {
timer->stop();
});
}
void updateCount() {
// 次数加一,并更新标签
count++;
countLabel->setText(QString::number(count));
}
};
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
MainWindow window;
window.show();
return app.exec();
}
#include "main.moc"
```
在这个程序中,我们创建了一个 `MainWindow` 类,继承自 `QWidget`。在构造函数中,我们创建了一个计时器 `timer`,一个按钮 `startButton` 和一个标签 `countLabel`,并设置它们的位置和大小。然后,我们连接了按钮的 `clicked()` 信号和自定义的 `startTimer()` 槽函数,以及计时器的 `timeout()` 信号和自定义的 `updateCount()` 槽函数。在 `startTimer()` 函数中,我们启动了计时器,并通过 `QTimer::singleShot()` 函数设置了一个20分钟后的单次定时器,用于停止计时器。在 `updateCount()` 函数中,我们将计数器 `count` 加一,并更新标签 `countLabel` 的文本。
最后,我们在 `main()` 函数中创建了一个 `QApplication` 对象和一个 `MainWindow` 对象,显示窗口,并启动事件循环。