QFileSystemWatcher working only in main()

家住魔仙堡 提交于 2019-12-25 18:20:06

问题


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 ?


回答1:


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



来源:https://stackoverflow.com/questions/28467830/qfilesystemwatcher-working-only-in-main

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!