该main
方法在每次应用程序启动时只执行一次,如果你想监视某些东西,你必须使用插槽和信号机制来完成。您可以通过定义一个自定义类(或者您可以继承 QApplication 本身)并将其连接到 QApplication::focusChanged 信号来实现这一点。每次应用程序焦点发生变化时,您都会收到一个信号。这是main.cpp
#include <QtGui>
#include <QDeclarativeView>
#include "main.h"
Watcher::Watcher(QObject *parent)
: QObject(parent)
{
}
void Watcher::onFocusChanged(QWidget * old, QWidget * now)
{
Q_UNUSED(old);
QWidget * window;
if (now == 0) {
window = 0;
} else {
window = now->window();
}
if (window != 0) {
qDebug() << window->windowTitle();
} else {
qDebug() << "No active window";
}
}
int main(int argc, char *argv[])
{
/* No need for scoped pointer */
QApplication app(argc, argv);
/* This object will be watching for QApplication::focusChanged signal
and report that to console */
Watcher watcher;
/* We connect QApplication::focusChanged signal to appropriate Watcher's slot */
QObject::connect(
&app, SIGNAL(focusChanged(QWidget*,QWidget*)),
&watcher, SLOT(onFocusChanged(QWidget*,QWidget*)));
/* Declarative view, it could be any other widget */
QDeclarativeView view;
view.setWindowTitle("Test QML Window");
view.setSource(QUrl::fromLocalFile("test.qml"));
view.show();
return app.exec();
}
main.h
看起来像这样
#ifndef MAIN_H
#define MAIN_H
#include <QtGui>
class Watcher : public QObject
{
Q_OBJECT
public:
Watcher(QObject *parent = 0);
public slots:
void onFocusChanged(QWidget * old, QWidget * now);
};
#endif // MAIN_H