Qt读取ini文件

主要用到QSettings类

我们下面用这个简单的例子来看看怎么使用QSettings类读取ini文件

首先新建一个QMainWindow项目

再在头文件中加入如下代码:

private:
    QGridLayout *gridLayout;
    QWidget *widget;
    QLabel *pathLabel;
    QLabel *nodeNameLabel;
    QLabel *keyLabel;
    QLabel *valueLabel;
    QLineEdit *pathLineEdit;
    QLineEdit *nodeLineEdit;
    QLineEdit *keyLineEdit;
    QLineEdit *valueLineEdit;
    QPushButton *readIniBtn;
    QWidget *mainWidget;

    QSettings *readIni;
private slots:
    void readFileSlot();

然后在构造函数中先布局

    gridLayout = new QGridLayout;

    pathLabel = new QLabel("ini file path:");
    nodeNameLabel = new QLabel("node Name:");
    keyLabel = new QLabel("key value:");
    valueLabel = new QLabel("value Label");

    pathLineEdit = new QLineEdit;
    pathLineEdit->setText("D:/a001.ini");
    nodeLineEdit = new QLineEdit;
    nodeLineEdit->setText("node");
    keyLineEdit = new QLineEdit;
    keyLineEdit->setText("ip");
    valueLineEdit = new QLineEdit;

    readIniBtn = new QPushButton("Read INI");

    gridLayout->addWidget(pathLabel, 0, 0, 1, 1);
    gridLayout->addWidget(pathLineEdit, 0, 1, 1, 4);
    gridLayout->addWidget(nodeNameLabel, 1, 0, 1, 1);
    gridLayout->addWidget(nodeLineEdit, 1, 1, 1, 1);
    gridLayout->addWidget(keyLabel, 2, 0, 1, 1);
    gridLayout->addWidget(keyLineEdit, 2, 1, 1, 1);
    gridLayout->addWidget(valueLabel, 2, 2, 1, 1);
    gridLayout->addWidget(valueLineEdit, 2, 3, 1, 1);
    gridLayout->addWidget(readIniBtn, 3, 3, 1, 1);

    mainWidget = new QWidget;
    this->setCentralWidget(mainWidget);
    mainWidget->setLayout(gridLayout);

布局好了之后关联信号槽:

    connect(readIniBtn, &QPushButton::clicked, this, &MainWindow::readFileSlot);

槽函数实现:

void MainWindow::readFileSlot()
{
    readIni = new QSettings(pathLineEdit->text(), QSettings::IniFormat);
    QString ipResult = readIni->value(nodeLineEdit->text() + "/" + keyLineEdit->text()).toString();
    valueLineEdit->setText(ipResult);
    delete readIni;
}

注意value的使用,这里贴上帮助文档中的内容:

QVariant QSettings::value(const QString & key, const QVariant & defaultValue = QVariant()) const
Returns the value for setting key. If the setting doesn't exist, returns defaultValue.

If no default value is specified, a default QVariant is returned.

Note that the Windows registry and INI files use case-insensitive keys, whereas the CFPreferences API on OS X and iOS uses case-sensitive keys. To avoid portability problems, see the Section and Key Syntax rules.

Example:

QSettings settings;
settings.setValue("animal/snake", 58);
settings.value("animal/snake", 1024).toInt();   // returns 58
settings.value("animal/zebra", 1024).toInt();   // returns 1024
settings.value("animal/zebra").toInt();         // returns 0

猜你喜欢

转载自blog.csdn.net/qiukapi/article/details/86552135