Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

c++ - QFileSystemWatcher working only in main()

I am trying to use QFileSystemWatcher like in the following example : How to use QFileSystemWatcher to monitor a folder for change My issue is that the watcher does work when I create it in the main() function like in the following :

#include "mainwindow.h"
#include <QApplication>

#include <QFileSystemWatcher>
#include <QDebug>
#include "systemfilewatcher.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QFileSystemWatcher watcher;
    watcher.addPath("C:/QtTest");
    SystemFileWatcher* mc = new SystemFileWatcher();
    QObject::connect(&watcher, SIGNAL(directoryChanged(QString)), mc, 
                     SLOT(showModified(QString)));
    MainWindow w(&watcher);
    w.show();
    return a.exec();
}

however when I try this exact same code in my ui like in the following, it doesn't work :

MainWindow::MainWindow(QFileSystemWatcher folder, QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
 {
    ui->setupUi(this);

    QFileSystemWatcher watcher;
    watcher.addPath("C:/QtTest");
    SystemFileWatcher* mc = new SystemFileWatcher();
    QObject::connect(&watcher, SIGNAL(directoryChanged(QString)), mc, SLOT(showModified(QString)));

this is my "systemfilewatcher.h" :

#ifndef SYSTEMFILEWATCHER
#define SYSTEMFILEWATCHER
#include <QWidget>
#include <QMessageBox>

class SystemFileWatcher : public QWidget
{
    Q_OBJECT

public:
    SystemFileWatcher(QWidget* parent=0)
        :QWidget(parent){}

    ~SystemFileWatcher(){}

public slots:
    void showModified(const QString& str)
    {
        QMessageBox::information(this,"Directory Modified", str);
    }
};
#endif // SYSTEMFILEWATCHER

     }

My goal is to detect when a file is created in a targeted directory and put its name in a QString stack. I don't know what I am doing wrong here, could someone help me please ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In the second case, your QFileSystemWatcher watcher is created on the stack and is destroyed as soon as the constructor ends. You have to keep a reference to it somewhere, possibly as an attribute of your SystemFileWatcher class


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...