第二种方法,你在运行后,弹出的textedit中最初并没有任何内容,程序在执行mystream << medit->text();这条语句的时候textedit没有内容,所以文件为空。当你之后编辑输入内容的时候,你并没有写程序来实现你输入内容之后,加写入的内容加入到文件中。
这里应该加入信号和槽,也就是你输出内容的同时,QTextEdit发出textChanged()的信号,你应该写一个槽函数textChangedSlot(),在这个函数中完成写文件的操作。然后将textChanged()信号和这个槽连接。这样,每次你编辑内容发生变化的时候,textChanged()信号发出,触发槽,开始写文件。
下面是实现代码
1.main.cpp
#include "mw.h"
#include <qapplication.h>
int main( int argc, char **argv )
{
QApplication a(argc,argv);
Medit *medit = new Medit();
a.setMainWidget(medit);
medit->show();
return a.exec();
}
2.mw.h
#include <qtextedit.h>
class Medit;
class Medit : public QTextEdit
{
Q_OBJECT
public:
Medit( QWidget * parent = 0, const char * name = 0 );
~Medit();
protected slots:
void textChangedSlot();
};
3.mw.cpp
#include <qfile.h>
#include <qtextstream.h>
#include "mw.h"
Medit::Medit( QWidget *parent, const char *name)
:QTextEdit(parent,name)
{
connect( this,SIGNAL( textChanged() ),
this,SLOT( textChangedSlot() ) ) ;
}
Medit::~Medit()
{
}
//protected slots
void Medit::textChangedSlot()
{
QFile myFile ("source.txt");
if (myFile.open(IO_WriteOnly ))
{
//Creat a text stream for the Qfile object
QTextStream mystream (&myFile);
mystream << this->text();
this->setModified(FALSE );
}
myFile.close();
}
我测试过了,希望对你有帮助