我提前道歉,我是 QT 的新手(而且是 C++ 的新手)
我正在尝试设置一个程序,该程序将在特定文件发生更改时执行某个功能。尽管在谷歌上花了几个小时并阅读了 QT 上提供的文档,但我无法找到一种方法让 myfunction() 在编辑 SSOpen_Log 时执行
目前我的代码看起来像这样(SOpen_Log 是一个在 .h 中声明的 QString):
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
QFileSystemWatcher watcher;
watcher.addPath(SOpen_Log);
MainWindow::connect(&watcher, SIGNAL(fileChanged(QString)), this, SLOT(myfunction()));
}
MainWindow::myfunction()
{
//mycode executes here
}
最佳答案
您在堆栈上分配了您的实例,因此在构造函数结束时它会被销毁。我建议您为该实例创建一个类成员,以便它在整个类中保持有效。
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
m_watcher.addPath(SOpen_Log);
MainWindow::connect(&m_watcher, SIGNAL(fileChanged(QString)), this, SLOT(myfunction()));
}
没有必要通过将它放在堆上来使它复杂化,有效地使用指针,尽管这也是一个需要考虑的选项。
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
QFileSystemWatcher *watcher = new QFileSystemWatcher(this);
watcher->addPath(SOpen_Log);
MainWindow::connect(watcher, SIGNAL(fileChanged(QString)), this, SLOT(myfunction()));
}
虽然我们正在这样做,但我还想提一下使用新的信号槽语法风格而不是旧的。旧的在运行时检查,新的在编译时检查。因此,您可以在编译期间而不是在运行时发现它的任何问题。
关于c++ - QFileSystemWatcher 不发送 fileChanged() 信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72947048/