给我用qt写一段功能封装成类的代码
时间: 2024-05-11 14:16:45 浏览: 16
好的,以下是一个用Qt编写的功能类的示例代码:
```cpp
#include <QObject>
#include <QFile>
class FileHandler : public QObject
{
Q_OBJECT
public:
explicit FileHandler(QObject *parent = nullptr);
signals:
void fileOpened(QString);
void fileClosed();
void errorOccurred(QString);
public slots:
void openFile(QString filePath);
void closeFile();
void writeText(QString text);
private:
QFile* m_file;
};
FileHandler::FileHandler(QObject *parent)
: QObject(parent)
, m_file(nullptr)
{
}
void FileHandler::openFile(QString filePath)
{
if (m_file != nullptr) {
emit errorOccurred("File is already opened.");
return;
}
m_file = new QFile(filePath, this);
if (!m_file->open(QIODevice::WriteOnly | QIODevice::Text)) {
emit errorOccurred(QString("Failed to open file: %1").arg(m_file->errorString()));
delete m_file;
m_file = nullptr;
return;
}
emit fileOpened(filePath);
}
void FileHandler::closeFile()
{
if (m_file == nullptr) {
emit errorOccurred("File is not opened.");
return;
}
m_file->close();
delete m_file;
m_file = nullptr;
emit fileClosed();
}
void FileHandler::writeText(QString text)
{
if (m_file == nullptr) {
emit errorOccurred("File is not opened.");
return;
}
m_file->write(text.toUtf8());
}
```
这个类名为`FileHandler`,它可以打开、关闭和向文件写入文本。它有三个信号:`fileOpened`,`fileClosed`和`errorOccurred`,分别在文件被打开、关闭和错误发生时发出。它也有三个槽:`openFile`,`closeFile`和`writeText`,分别用于打开、关闭和写入文本。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)