qt制作一个简易的听小说工具

其实qt有一个类:QTextToSpeech
基于这个类制作了一个听小说的工具:
有一个前提,你需要下载小说,并且转化为utf-8的编码格式
在pro文件中加入 QT += texttospeech
qt制作一个简易的听小说工具_第1张图片
然后看代码:
.h

#ifndef WIDGET_H
#define WIDGET_H

#include 
#include 
#include 
#include 

class Widget : public QWidget
{
    Q_OBJECT

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

private slots:
    void onChooseClicked();

private:
    QPushButton *m_pChooseBtn=nullptr;
    QLineEdit *m_pEdit=nullptr;
    QTextToSpeech *m_pTextSpeech=nullptr;
    QString m_readString="";
};
#endif // WIDGET_H

.cpp

#include "widget.h"
#include 
#include 

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    m_pChooseBtn=new QPushButton(tr("Choose"),this);
    m_pEdit=new QLineEdit(this);
    QHBoxLayout *mainLayout=new QHBoxLayout(this);
    mainLayout->addWidget(m_pEdit);
    mainLayout->addWidget(m_pChooseBtn);
    mainLayout->setMargin(5);
    mainLayout->setSpacing(0);
    this->setLayout(mainLayout);

    m_pTextSpeech=new QTextToSpeech(this);

    connect(m_pChooseBtn,&QPushButton::clicked,this,&Widget::onChooseClicked);
}

Widget::~Widget()
{
}

void Widget::onChooseClicked()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),
                                                    "/home",
                                                    tr("Txt (*.txt)"));
    if(fileName!="")
    {
        m_pEdit->setText(fileName);
        m_pTextSpeech->pause();
        m_pTextSpeech->stop();
        m_readString.clear();
        QFile file(fileName);
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
            return;

        while (!file.atEnd()) {
            QString line = file.readLine();
            if(line!="")
            {
                m_readString+=line;
            }
        }
        m_pTextSpeech->say(m_readString);
    }

}


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