QFile类
QFile类提供了一个可以读写文件的接口,用法如下:
//读取.txt文件中每一行信息并处理,读一般的二进制文件的话不需要QIODevice::Text
QFile file("in.txt");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
while (!file.atEnd()) {
QByteArray line = file.readLine();
process_line(line);
}
//判断文件是否存在
if (!QFile::exists(fildName))
{
....
}
QDataStream类
提供一个到QIODevice的二进制数据序列,QIODevice是Qt所有I/O设备的基础接口类。QDataStream既支持C++基本类型,也支持多种Qt类型。因C++基本类型在不同的平台上有不同的大小,所以把数据强制转换成quint8,quint16等是最安全的做法,也可以实现跨平台。QDataStream的二进制格式自Qt 1.0以来已经发展,并且可能会继续发展。 输入或输出复杂类型时,确保使用相同版本的流进行读写非常重要。 如果需要向前和向后兼容性,则可以在应用程序中指定版本号。它模仿标准C++的<iostream>中类的语法来使用,代码实例如下:
//QT帮助中的例子
//写入二进制数据到文件中
QFile file("file.dat");
file.open(QIODevice::WriteOnly);
QDataStream out(&file); // we will serialize the data into the file
out << QString("the answer is"); // serialize a string
out << (qint32)42; // serialize an integer
//从文件中读二进制数据
QFile file("file.dat");
file.open(QIODevice::ReadOnly);
QDataStream in(&file); // read the data serialized from the file
QString str;
qint32 a;
in >> str >> a; // extract "the answer is" and 42
....
//设置QDataStream的版本
QDataStream out(&file);
out.setVersion(QDataStream::Qt_4_3);
...
//判断IO设备是否已到结束位置(流或文件的结尾)
QDataStream in(&file);
while (!in.atEnd())
{
....
}
Q_PROPERTY
Q_PROPERTY宏的功能是声明属性,对于定义属性的类,Q_OBJECT宏是必须的。它的结构如下:
//type属性类型 name属性名 RREAD读取功能(必须要有) getFucntion读取功能函数
Q_PROPERTY(type name
READ getFunction
[WRITE setFunction]
[RESET resetFunction]
[NOTIFY notifySignal]
[REVISION int]
[DESIGNABLE bool]
[SCRIPTABLE bool]
[STORED bool]
[USER bool]
[CONSTANT]
[FINAL])
代码示例:
//在newWidget.h中声明属性,和相关功能函数
#ifndef NEWWIDGET_H
#define NEWWIDGET_H
#include <QWidget>
class NewWidget:public QWidget
{
Q_OBJECT
//声明newproperty属性
Q_PROPERTY(int newproperty READ newProperty WRITE setnewProperty)
public:
explicit NewWidget(QWidget *parent = 0);
int newProperty()const{return m_newproperty;}
void setnewProperty(const int newproperty);
private:
int m_newproperty;
};
#endif // NEWWIDGET_H
//在newWidget.cpp中定义
#include "newWidget.h"
NewWidget::NewWidget(QWidget *parent)
:QWidget(parent)
{
m_newproperty = 1;
}
void NewWidget::setnewProperty(const int newPro)
{
m_newproperty = newPro;
}
//在Maindow.cpp中使用
MainWindow::MaAinWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
new_widget = new NewWidget(this);
qDebug()<<"new_widget->property:"<<new_widget->property("newproperty");
new_widget->setProperty("newproperty",67);
qDebug()<<"new_widget->property:"<<new_widget->property("newproperty");
}
输出结果:
在Qt designer中使用自定义窗口部件的方法:
1、改进法(提升窗口部件),优点快捷简单,缺点是无法对自定义窗口部件中的特定属性进行访问,也无法对窗口部件自身进行绘制。
2、插件法(这个不太懂,之后慢慢研究)