ファイル操作がなければなりませんC++レベルで行わ。コードはQt
で、オープンを示す良い例も保存し、編集操作すれば、以下の通り。 これは、ウィジェットを使用していますので、.pro
ファイルに以下を追加します。
QT += widgets
qmlfile.h
//qmlfile.h
#ifndef QMLFILE_H
#define QMLFILE_H
#include <QObject>
class QMLFile : public QObject
{
Q_OBJECT
public:
explicit QMLFile(QObject *parent = 0);
Q_INVOKABLE QString getFileContents() const;
Q_INVOKABLE void saveFileContents(QString fileContents) const;
};
#endif
qmlfile.cpp
#include <QFileDialog>
#include <QTextStream>
#include <QDebug>
#include "qmlfile.h"
QMLFile::QMLFile(QObject *parent): QObject(parent)
{
}
QString QMLFile::getFileContents() const
{
QString fileName = QFileDialog::getOpenFileName(NULL, tr("Open File"), "/home", tr("Text Files (*.txt)"));
qDebug() << "fileName:" << fileName;
QFile file(fileName);
if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
return "";
QString content = file.readAll();
file.close();
return content;
}
void QMLFile::saveFileContents(QString fileContents) const
{
QString fileName = QFileDialog::getSaveFileName(NULL, tr("Save File"), "/home/ansh/data.txt", tr("Text Files (*.txt)"));
QFile file(fileName);
if(file.open(QIODevice::WriteOnly | QIODevice::Text))
{
qDebug() << "created file:" << fileName;
QTextStream stream(&file);
stream << fileContents << endl;
file.close();
return;
}
else
{
qDebug() << "could not create file:" << fileName;
return;
}
}
main.cppに
#include <QGuiApplication>
#include <QQuickView>
#include <QQmlContext>
#include <QApplication>
#include "qmlfile.h"
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QQuickView view;
QMLFile qmlFile;
view.rootContext()->setContextProperty("QMLFile", &qmlFile);
QObject::connect((QObject*)view.engine(), SIGNAL(quit()), QApplication::instance(), SLOT(quit()));
view.setSource(QUrl(QLatin1String("qrc:/main.qml")));
view.show();
return app.exec();
}
main.qml
import QtQuick 2.5
import QtQuick.Controls 2.0
Rectangle {
width: 360; height: 360
Rectangle{
id:buttons
height: 50; width: parent.width; anchors.top: parent.top
Row {
Button {
text: "open"
onClicked: txt.text = QMLFile.getFileContents();
}
Button {
text: "save"
onClicked: QMLFile.saveFileContents(txt.text);
}
Button {
text: "Abort"
onClicked: Qt.quit()
}
spacing: 5
}
}
Rectangle{
id:textHandle
width: parent.width; height: parent.height - buttons.height; anchors.bottom: parent.bottom
TextEdit{
id: txt; anchors.fill: parent
}
}
}
第2の質問では、設定は本質的に動的なので、毎回読む必要があります。
うわーありがとう私は家に帰るときにそれを試してみよう! – MilloMille
@MilloMille回答をアップしてください。 –