Qt输入与输出

Qt输入与输出
QSetting 使用
一、 在windows中修改注册表:
a) 写注册表,将程序信息保存到注册表的Software Inc. Spreadsheet下

QSettings settings("Software Inc.", "Spreadsheet");
settings.setValue("showGrid", showGridAction->isChecked());
settings.setValue("autoRecalc", autoRecalcAction->isChecked());

b) 读注册表

QSettings settings("Software Inc.", "Spreadsheet");
bool showGrid = settings.value("showGrid", true).toBool();
bool autoRecalc = settings.value("autoRecalc", true).toBool();

二、 读写文件

QSettings settings("./myapp.ini", QSettings::IniFormat);  // ./myapp.ini——同级目录下的myapp.ini文件
settings.setValue("name",1);

QSettings settings("../myapp.ini",QSettings::IniFormat); //../myapp.ini——上级目录下的myapp.ini文件
settings.setValue("name",1);

读写文件——QDataStream和QTextStream
QDataStream——读写二进制文件,读写二进制文件时需首先设置Qt的版本。

 bool Spreadsheet::writeFile(const QString &fileName)
  {
       QFile file(fileName); 
       if (!file.open(QIODevice::WriteOnly))	//打开失败警告 
       {
           QMessageBox::warning(this, tr("Spreadsheet"),
                                tr("Cannot write file %1:\n%2.")
                                .arg(file.fileName())
                                .arg(file.errorString()));
           return false;
       }
   
       QDataStream out(&file);
       out.setVersion(QDataStream::Qt_4_3);	//设置版本,保证读取写入格式的一致性
       out << quint32(MagicNumber);	//校准信息
       QApplication::setOverrideCursor(Qt::WaitCursor);	//鼠标等待
       //循环写入 for (int row = 0; row < RowCount; ++row) {
           for (int column = 0; column < ColumnCount; ++column) {
               QString str = formula(row, column);
               if (!str.isEmpty())
                   out << quint16(row) << quint16(column) << str;
           }
       }
       QApplication::restoreOverrideCursor();		//结束
       return true; 
       }
   
   
   bool Spreadsheet::readFile(const QString &fileName)
    {
       QFile file(fileName);
       if (!file.open(QIODevice::ReadOnly))
        {
           QMessageBox::warning(this, tr("Spreadsheet"),
                                tr("Cannot read file %1:\n%2.")
                                .arg(file.fileName())
                                .arg(file.errorString()));
           return false;
       }
   
       QDataStream in(&file);
       in.setVersion(QDataStream::Qt_4_3);
      
       //校准验证
       quint32 magic;
       in >> magic;
       if (magic != MagicNumber)
        {
           QMessageBox::warning(this, tr("Spreadsheet"),
                                tr("The file is not a Spreadsheet file."));
           return false;
       }
   
       quint16 row;
       quint16 column;
       QString str;
   
       QApplication::setOverrideCursor(Qt::WaitCursor);       //读取 
       while (!in.atEnd()) {
           in >> row >> column >> str;
           setFormula(row, column, str);
       }
       QApplication::restoreOverrideCursor();
       return true; 
       }

你可能感兴趣的:(Qt)