文章目录
- 完成效果图
- ui界面
- ui样图
- main函数
- 窗口文件
- 头文件
- cpp文件
引言
一般定时关机采用命令行模式,还需要我们计算在多久后关机,我们可以做一个小程序来定时关机
完成效果图
ui界面
MainWindow 00330240 330240 330240 10 关机 取消 62 22 62 22 false 0 0 时 Qt::Horizontal 40 20 62 22 62 22 false 分 Qt::Vertical 20 30 Qt::Horizontal 4020 Qt::Vertical 2040 Qt::Vertical 2040 Qt::Horizontal 4020 18630 18630 设置关机时间 Qt::Vertical 2030
ui样图
main函数
#include "mainwindow.h"#include int main(int argc, char *argv[]){QApplication a(argc, argv);MainWindow w;w.show();return a.exec();}
窗口文件
核心逻辑
采用信号和槽,完成事件链接
QProcess::startDetached("shutdown", QStringList() << "/s" << "/t" << QString::number(timeSeconds));
QProcess::execute("shutdown", QStringList() << "/a");
头文件
// mainwindow.h#ifndef MAINWINDOW_H#define MAINWINDOW_H#include #include #include #include #include #include #include namespace Ui {class MainWindow;}class MainWindow : public QMainWindow{Q_OBJECTpublic:explicit MainWindow(QWidget *parent = nullptr);~MainWindow();private slots:void onShutdownButtonClicked();void onCancelShutdownButtonClicked();private:Ui::MainWindow *ui;QTimer *shutdownTimer;};#endif // MAINWINDOW_H
cpp文件
// mainwindow.cpp#include "mainwindow.h"#include "ui_mainwindow.h"MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent),ui(new Ui::MainWindow){ui->setupUi(this);// 获取当前时间QTime currentTime = QTime::currentTime();// 设置小时下拉框ui->hourComboBox->setEditable(false);for (int i = 0; i < 24; ++i) {// 比较当前时间与选项时间if (currentTime.hour() <= i) {ui->hourComboBox->addItem(QString::number(i));}}// 选择当前小时作为已选中项ui->hourComboBox->setCurrentIndex(ui->hourComboBox->findText(QString::number(currentTime.hour())));// 设置分钟下拉框ui->minuteComboBox->setEditable(false);for (int i = 0; i < 60; ++i) {// 比较当前时间与选项时间if (currentTime.minute() <= i) {ui->minuteComboBox->addItem(QString::number(i));}}// 选择当前分钟作为已选中项ui->minuteComboBox->setCurrentIndex(ui->minuteComboBox->findText(QString::number(currentTime.minute())));// 连接按钮点击事件到槽函数connect(ui->shutdownButton, &QPushButton::clicked, this, &MainWindow::onShutdownButtonClicked);connect(ui->cancelShutdownButton, &QPushButton::clicked, this, &MainWindow::onCancelShutdownButtonClicked);}MainWindow::~MainWindow(){delete ui;}void MainWindow::onShutdownButtonClicked(){// 获取用户选择的小时和分钟int selectedHour = ui->hourComboBox->currentText().toInt();int selectedMinute = ui->minuteComboBox->currentText().toInt();// 获取当前时间QDateTime currentTime = QDateTime::currentDateTime();// 获取用户选择的时间QDateTime shutdownTime = QDateTime(currentTime.date(), QTime(selectedHour, selectedMinute));// 计算时间差qint64 timeDifference = currentTime.msecsTo(shutdownTime);int timeSeconds=int(timeDifference/1000);// 设置定时器的超时时间//shutdownTimer->start(timeDifference);QProcess::startDetached("shutdown", QStringList() << "/s" << "/t" << QString::number(timeSeconds));// 提示用户关机已设置QMessageBox::information(this, "关机设置", "关机已设置,将在选择的时间执行!");}void MainWindow::onCancelShutdownButtonClicked(){// 取消关机QProcess::execute("shutdown", QStringList() << "/a");QMessageBox::information(this, "取消关机", "已取消关机操作!");}