Tuesday, 7 January 2014

QUrl and QFile

Recently I design one Qml file dialog to create a new file, then pass the file path to C++ extensionplugin to write a local file.
But the Qml file dialog makes a QUrl for me, format looks like so:

What I want is just C:/uuuu.a3, a local file path.
In C++ code, QUrl class can help to convert this.
Construct a QUrl object with url path, then call toLocalFile method to get a real local file path.
Example code is below:
void Test::setPath(QString const& path) {
  QUrl url(path);
  projectFilePath_ = url.toLocalFile();
  QFile file(projectFilePath_);
  if (!file.exists()) {
 if (!file.open(QIODevice::ReadWrite | QIODevice::Text)) {
 QString error_msg = file.errorString();
 QTextStream out(&file);
 out << "test" << "\n";

Also, the above snippet shows how to create and write a text file on local disk using QFile & QIODevice & QTextStream.

No comments: