要保存位置,只要在组件退出时记录下组件的几何属性,在组件创建时读入就可以了.
我借用kdevelop自己生成的Qt单文档程序实现了这个功能,具体操作如下:
1.重载RecordPosApp类的closeEvent虚函数.
protected:
virtual void closeEvent(QCloseEvent* e);
2.实现closeEvent函数.
void RecordPosApp::closeEvent(QCloseEvent* e)
{
//创建文件
QFile f("Pos.txt");
if ( !f.open( IO_WriteOnly) )
return;
QTextStream t( &f );
QString strPos[4];
//记录组件的几何坐标
strPos[0].setNum(this->x());
strPos[1].setNum(this->y());
strPos[2].setNum(this->width());
strPos[3].setNum(this->height());
//将组件的几何坐标写入文件
t <<strPos[0]<< "\n";
t <<strPos[1]<< "\n";
t <<strPos[2]<< "\n";
t <<strPos[3]<< "\n";
f.close();
//退出整个程序
qApp->quit();
}
到这里,记录部分就写完了.下面是读入部分.
3.读入组件的几何位置.
这段代码书写具体函数不限,只要被RecordPosApp的构造函数调用的就可以了,我写在了
RecordPosApp::initView()中.
具体如下:
void RecordPosApp::initView()
{
////////////////////////////////////////////////////////////////////
// set the main widget here
view=new RecordPosView(this, doc);
setCentralWidget(view);//这里以上是原有的代码
//打开文件
QFile f("Pos.txt");
if ( !f.open( IO_ReadOnly ) )//打不开的话不进行操作
return;
QTextStream t( &f );
QString strPos[4];
//从文件中读入位置的值放入字符数组
strPos[0]=t.readLine();
strPos[1]=t.readLine();
strPos[2]=t.readLine();
strPos[3]=t.readLine();
//设置本组件的几何位置
this->setGeometry(
strPos[0].toInt(),//x
strPos[1].toInt(),//y
strPos[2].toInt(),//width
strPos[3].toInt());//height
f.close();
}
这样,在程序开启时就被重新设置了一次几何位置了.
junglesong 原创
2004-3-17AM |