[Qt-interest] Executing code after QApplication::exec() without user intervention

Mark Summerfield list at qtrac.plus.com
Tue Apr 27 09:15:56 CEST 2010


On 2010-04-27, Nikos Chantziaras wrote:
> I'm sure there's some obvious solution to this, but my brain seems stuck 
:P
> 
> How do have a method executed automatically after the main event loop
> (app->exec()) has started?  This is for the case where the application
> takes a command-line argument to open a file.  Right now, this is simply
> done the usual way, through the application's "File->Open" menu.  But
> providing a filename as a command-line arg means I need to open the file
> without user intervention.

The way I always do things like this is to get the filename from the
command line before the call to exec() and to pass it to the main
window, e.g., something like this:

	...
	QString filename;
	if (argc > 1)
	    filename = argv[1]; // Or: filename = QString(argv[1]);
	MainWindow mainWindow(filename); // filename might be empty
	mainWindow.show();
	return app.exec();
    }

Then in the main window's constructor, at the end I have something like:

	if (!filename.isEmpty())
	    QTimer::singleShot(0, this, SLOT(loadFile()));
	    // this assumes that filename is a member variable; if not
	    // use:
	    // QMetaObject::invokeMethod(this, "loadFile",
	    //	    Qt::QueuedConnection,
	    //	    Q_ARG(QString, filename));

This assumes you have a method with signature 
    void loadFile(); // if you use the timer, or
    void loadFile(const QString &filename); // if you use invokeMethod

Naturally, your fileOpen() method would end up calling loadFile().

BTW The reason for using a timer or queued connection is (1) to ensure
that the main window is fully constructed before the loading is
attempted, and (2) to ensure that the main window appears as quickly as
possible even if file loading is slow (e.g., due to a big file or
because you load many files).

-- 
Mark Summerfield, Qtrac Ltd, www.qtrac.eu
    C++, Python, Qt, PyQt - training and consultancy
        "Advanced Qt Programming" - ISBN 0321635906



More information about the Qt-interest-old mailing list