C++&qt Day10

1.制作闹钟

头文件

#include 
#include 
#include 
#include 
#include 
#include 

QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();

    void timerEvent(QTimerEvent *e) override;       //定时器事件处理函数

private slots:

    void on_startBtn_clicked();

    void on_stopBtn_clicked();

private:
    Ui::Widget *ui;

    QTextToSpeech *speecher;

    int timer_id;
};
#endif // WIDGET_H

源函数

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    speecher = new QTextToSpeech(this);
}

Widget::~Widget()
{
    delete ui;
}


//开始按钮对应的槽函数
void Widget::on_startBtn_clicked()
{
    timer_id = this->startTimer(1000);
}

//停止按钮
void Widget::on_stopBtn_clicked()
{
    //this->killTimer(timer_id);
    speecher->stop();
    ui->lineEdit->clear();
}

void Widget::timerEvent(QTimerEvent *e)
 {
     if(e->timerId() == timer_id)
     {
         QTime sys_t = QTime::currentTime();    //获取系统时间

         QString t = sys_t.toString("hh:mm:ss");    //将QTime类对象转换为字符串

         ui->nowtimeLeb->setText(t);        //展示到ui界面

         if(t == ui->lineEdit->text())
         {
             speecher->say(ui->textEdit->toPlainText());
         }
     }
 }

主函数

#include "widget.h"

#include 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();
    return a.exec();
}

2.保存文件

头文件

#ifndef WIDGET_H
#define WIDGET_H

#include 
#include 
#include 
#include 

QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();

private slots:
    void on_pushButton_clicked();

private:
    Ui::Widget *ui;
};
#endif // WIDGET_H

源文件

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_clicked()
{
    QString fileName =  QFileDialog::getSaveFileName(this,
                                                     "保存文件",
                                                     "./",
                                                     "Text file(*.txt)");

    if(fileName.isNull())
    {
        QMessageBox::information(this, "提示", "用户取消了保存文件");
        return ;
    }

    QFile file(fileName);
    if(!file.isOpen())
    {
        if(!file.open(QFile::ReadWrite))
        {
            QMessageBox::critical(this, "失败", "文件打开失败");
            return;
        }
    }

    QString msg = ui->textEdit->toPlainText();
    file.write(msg.toUtf8());

    file.close();
}

主函数

#include "widget.h"

#include 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();
    return a.exec();
}

你可能感兴趣的:(c++,qt,开发语言)