Thursday, May 6, 2010

Kode Recursive untuk mendaftarkan semua file dalam sebuah direktori dengan Library Qt

Akhirnya dapat juga kode yang dapat melakukan pencarian semua file yang bertipe dekstop yang kemudian di catat ke dalam file /tmp/application.list. Saya patut berterima kasih kepada Milot Shala yang telah memberikan contoh kode qt nya pada website ini.

Ini hasil editan saya dari kode Milot Shala tersebut:


recursive.cpp


#include

#include "recursive.h"

MusicWidget::MusicWidget(QWidget *parent)

:QDialog(parent), ui(new Ui::MusicWidget) // call the base class constructor also

{

ui->setupUi(this);

connect(ui->buttonGetFiles, SIGNAL(clicked()), this, SLOT(selectDirAndGetFiles()));

}

void MusicWidget::selectDirAndGetFiles()

{

// Display a dialog to the user to choose his music directory

// QString directory_path = QFileDialog::getExistingDirectory(this, tr("Select your music directory"), QDir::currentPath());

QString directory_path = "/usr/share/applications";

// Then create an instance of our QDirIterator, which takes as parameters

// the directory, a QDir filter and an option flag which the QDirIterator is told

// to go on the subdirectories also.

// I have combined the QDir filters to list files and not to get the symbolic links (shortcuts in Windows).

QDirIterator directory_walker(directory_path, QDir::Files | QDir::NoSymLinks, QDirIterator::Subdirectories);

// QDirIterator object has a boolean method called hasNext() which returns true

// if the directory have more files, false otherwise and based on that information,

// we can write a while loop like the one below

while(directory_walker.hasNext())

{

QFile logs("/tmp/application.list");

// then we tell our directory_walker object to explicitly take next element until the loop finishes

directory_walker.next();

// I want to list just mp3 files!

if(directory_walker.fileInfo().completeSuffix() == "desktop") {

// then we take a filename and display it to a listWidget like the code below:

ui->musicListWidget->addItem(directory_walker.fileInfo().baseName());

if (!logs.open(QIODevice::WriteOnly | QIODevice::Text))

return;

output +=directory_walker.fileInfo().baseName() + "\n";

QTextStream out(&logs);

out <<>

}

}

}



recursive.h


#ifndef RECURSIVE_H

#define RECURSIVE_H

#include

#include "ui_recursive.h"

class MusicWidget : public QDialog, private Ui::MusicWidget

{

Q_OBJECT

public:

MusicWidget(QWidget *parent = 0);

private slots:

void selectDirAndGetFiles();

private:

Ui::MusicWidget *ui;

QString output;

QString directory_path;

};

#endif // RECURSIVE_H




Untuk kode lengkapnya dapat didownload disini.



Happy Programming,



Juan Rio Sipayung

0 komentar: