Qt getSaveFileName Qt date 获取显示当前时间和日期 文件

本文介绍在Qt中如何使用QFileDialog进行文件保存,包括设置默认文件名和过滤器,以及如何利用QDataStream将数据写入文件。同时,详细讲解了如何使用QDateTime获取并格式化当前时间和日期。

保存文件
getSaveFileName

    QString strSaveName = QFileDialog::getSaveFileName(
                                                            this,
                                                            tr("保存的文件"),
                                                            tr("demo.a.txt"),
                                                            tr("Items files(*.items)")
                                                        );

在这里插入图片描述

//保存所有条目到文件
void MainWindow::on_pushButtonSave_clicked()
{
    QString strSaveName = QFileDialog::getSaveFileName(
                                                            this,
                                                            tr("保存的文件"),
                                                            tr("."),
                                                            tr("Items files(*.items)")
                                                        );
    myDebug("strSaveName",strSaveName);

    //判断文件名
   if( strSaveName.isEmpty() )
   {
       return;
   }

   //打开要写入的文件
   QFile fileSave(strSaveName);
   myDebug("strSaveName",strSaveName);
   if( ! fileSave.open( QIODevice::WriteOnly ))
   {
       //无法打开要写入的文件
       QMessageBox::warning(this, tr("打开写入文件"),
                            tr("打开要写入的文件失败,请检查文件名和是否具有写入权限!"));
       return;
   }


   //创建数据流
   QDataStream dsOut(&fileSave);
   //先写入列表条目计数
   qint32 nCount = ui->listWidget->count();
   myDebug("nCount",nCount);
   dsOut << nCount; //没有回车
   //dsOut << nCount << endl;//有回车
   //逐个写入条目
   for(qint32 i=0; i < nCount; i++)
   {
       QListWidgetItem *theItem = ui->listWidget->item(i);
       dsOut<< *theItem;   //把条目对象写入数据流,不是写指针数值
       //数据流仅写入条目通用数据,条目的非通用数据不写入,比如条目的标志位不写
   }
   //写入完毕



}

Qt QTextEdit获取输入框内容

QString name = ui->tbxName->toPlainText();

在这里插入图片描述

//导出信息到
void MainWindow::on_pushButton_clicked()
{
    QDateTime dateTime;
    dateTime = QDateTime::currentDateTime();
    qDebug() << dateTime.toString("yyyy-MM-dd-hh:mm:ss");
    QString dateTimeStr = dateTime.toString("yyyy-MM-dd-hh_mm_ss");
    QString fileStr = dateTimeStr + ".txt";
    const char *fileStrInfo = fileStr.toLatin1().constData(); //toUtf8()

    QString strSaveName = QFileDialog::getSaveFileName(
                                                            this,
                                                            tr("保存的文件"),
                                                            tr(fileStrInfo),
                                                            tr("Items files(*.items)")
                                                        );

    //打开要写入的文件
    QFile fileSave(strSaveName);

    qDebug() << "strSaveName:" << strSaveName;

    if( ! fileSave.open( QIODevice::WriteOnly ))
    {
        //无法打开要写入的文件
        QMessageBox::warning(this, tr("打开写入文件"),
                             tr("打开要写入的文件失败,请检查文件名和是否具有写入权限!"));
        return;
    }

     QString fileName=strSaveName;
     qDebug() << "fileName:" << fileName;
     QFile f(fileName);

     if(!f.open(QIODevice::WriteOnly | QIODevice::Text))
     {
         qDebug()  << "Open failed.";
         QMessageBox::warning(this,"file error","can't open",QMessageBox::Yes);
     }

     QTextStream in(&f);
     QString test_info = ui->textConsole->toPlainText();
     qDebug() << "test_info:" << test_info;
     //in << textConsole;//没有回车
     in << test_info << endl;//有回车
     f.close();

}



QT获取显示当前时间和日期

https://blog.youkuaiyun.com/qq_33249042/article/details/124534926

QDateTime类
QDateTime类是 QDate 和 QTime 的组合,提供一系列时间和日期相关的函数。

通过调用 QDateTime 类中的 currentDateTime() 方法可以获取到当前系统时间和日期:


QDateTime dateTime;
dateTime = QDateTime::currentDateTime();
qDebug()<<dateTime;
qDebug() << dateTime.toString("yyyy-MM-dd hh:mm:ss ddd");

输出结果:
QDateTime(2022-04-29 15:22:23.615 中国标准时间 Qt::TimeSpec(LocalTime))
"2022-04-29 15:22:23 周五"

------------------------------------------------------------------------------------------

QDate date = QDate::currentDate();
qDebug() << date;
qDebug() << date.toString("yyyy-MM-dd ddd");
qDebug() << date.toString("yyyy-MM-dd dddd");

输出结果:
"2022-04-29 周五"
"2022-04-29 星期五"


------------------------------------------------------------------------------------------


QDate date = QDate::currentDate();
qDebug() << date;
qDebug() << date.toString("yyyy-MM-dd");

输出结果:
QDate("2022-04-29")
"2022-04-29"

------------------------------------------------------------------------------------------



我不知道您需要的是什么样的考勤表,但是以下是一个简单的示例,它创建一个基本的考勤表,并允许用户添加、删除编辑条目。 mainwindow.h: ```c++ #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QStandardItemModel> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = nullptr); ~MainWindow(); private slots: void on_addButton_clicked(); void on_deleteButton_clicked(); void on_saveButton_clicked(); void on_loadButton_clicked(); void on_tableView_doubleClicked(const QModelIndex &index); private: Ui::MainWindow *ui; QStandardItemModel *model; }; #endif // MAINWINDOW_H ``` mainwindow.cpp: ```c++ #include "mainwindow.h" #include "ui_mainwindow.h" #include <QStandardItem> #include <QFileDialog> #include <QMessageBox> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); // Create the model and set it on the table view model = new QStandardItemModel(this); model->setColumnCount(3); model->setHorizontalHeaderLabels(QStringList() << "Name" << "Date" << "Status"); ui->tableView->setModel(model); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_addButton_clicked() { // Create a new row and add it to the model QList<QStandardItem*> row; row.append(new QStandardItem("New Person")); row.append(new QStandardItem(QDate::currentDate().toString(Qt::ISODate))); row.append(new QStandardItem("Absent")); model->appendRow(row); } void MainWindow::on_deleteButton_clicked() { // Get the selected row and remove it from the model QModelIndexList indexes = ui->tableView->selectionModel()->selectedRows(); if (indexes.size() == 1) { int row = indexes.first().row(); model->removeRow(row); } } void MainWindow::on_saveButton_clicked() { // Open a dialog to choose the file to save to QString fileName = QFileDialog::getSaveFileName(this, "Save File", "", "CSV Files (*.csv)"); if (fileName.isEmpty()) { return; } // Open the file for writing QFile file(fileName); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { QMessageBox::critical(this, "Error", "Could not save file."); return; } // Write the data to the file QTextStream out(&file); out << "Name,Date,Status\n"; for (int row = 0; row < model->rowCount(); ++row) { QString name = model->item(row, 0)->text(); QString date = model->item(row, 1)->text(); QString status = model->item(row, 2)->text(); out << name << "," << date << "," << status << "\n"; } // Close the file file.close(); } void MainWindow::on_loadButton_clicked() { // Open a dialog to choose the file to load from QString fileName = QFileDialog::getOpenFileName(this, "Load File", "", "CSV Files (*.csv)"); if (fileName.isEmpty()) { return; } // Open the file for reading QFile file(fileName); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { QMessageBox::critical(this, "Error", "Could not load file."); return; } // Clear the current model and read the data from the file model->clear(); model->setColumnCount(3); model->setHorizontalHeaderLabels(QStringList() << "Name" << "Date" << "Status"); QTextStream in(&file); in.readLine(); // Skip the header line while (!in.atEnd()) { QString line = in.readLine(); QStringList fields = line.split(","); QList<QStandardItem*> row; row.append(new QStandardItem(fields.at(0))); row.append(new QStandardItem(fields.at(1))); row.append(new QStandardItem(fields.at(2))); model->appendRow(row); } // Close the file file.close(); } void MainWindow::on_tableView_doubleClicked(const QModelIndex &index) { // Allow the user to edit the status field by double-clicking on it if (index.column() == 2) { ui->tableView->edit(index); } } ``` 这个示例使用一个QStandardItemModel来存储考勤表的数据,并将其设置为QTableView的模型。它包括按钮双击编辑功能,以便用户可以添加、删除编辑条目。它还包括保存加载功能,允许用户将考勤表保存为CSV文件并从CSV文件加载。请注意,这个示例假定CSV文件格式为“Name,Date,Status”。如果您需要不同的格式,请相应地修改代码。
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值