Nicholas Smith
Nicholas Smith

Reputation: 11754

QApplication Within A Shared Library Event Loop Issues

I'm trying to use QWebPage in a shared library, which means I have to have QApplication in there to get a GUI context for it to run in. I've built my code up to get this in place, however as soon as I run qApp->exec() the Event Loop completely blocks and prevents anything else from executing. This is with the shared library being ran on OS X, I've yet to try any other platforms.

I've tried adding a QTimer in to trigger every 100msecs but that doesn't ever get called, I'd assume to the event loop blocking. I've added my QApplication setup code below. I'd assume I either need to run it in a thread, or I've missed something trivial but I'm completely unsure what.

web_lib.cpp

WebLib::WebLib(int argc, char *argv[])
{
    QApplication a(argc, argv, false);
    connect(&m_eventTimer, SIGNAL(timeout()), this, SLOT(handleEvents()));
    m_eventTimer.start(100);

    a.exec();
}
void WebLib::renderFile(QString file
{
    ...some connection code that's boring here
    m_page = new QWebPage;
    m_page->mainFrame()->load(file);
}
void WebLib::handleEvents() 
{
    qApp->processEvents()
}

web_lib.h

class WEBLIBSHARED_EXPORT WebLib: public QObject
{
    Q_OBJECT
public:
    WebLib();
    WebLib(int argc, char *argv[]);
    void renderFile(QString fileName);

private slots:
    void handleEvents();

private:
    QWebPage *m_page;

    QTimer m_eventTimer;
};

main.cpp

int main(int argc, char *argv[])
{
    WebLib *webLib = new webLib(argc, argv);
    svgLib->renderFileFromName("somePath");

    return 0;
}

Upvotes: 1

Views: 1041

Answers (3)

As soon as I run qApp->exec() the event loop completely blocks and prevents anything else from executing.

That's correct. After you're done with your rendering, you should exit the event loop.

The timer is useless, since calling processEvents from a nonblocking slot like handleEvents simply forces the event loop to be re-entered for a short time, for no reason.

Upvotes: 1

Stuart Fisher
Stuart Fisher

Reputation: 200

Your event loop has nothing to do. You need to make the render file request before calling a.exec(), not afterwards. In other words, you need to make the following changes:

In the WebLib constructor: 1. Remove the call to a.exec(). 2. Dynamically allocate the QApplication instead of putting it on the stack. 3. Remove the timer, you don't need it.

In web_lib.cpp: Add WebLib::run(), which will call a.exec().

In main.cpp: After the call to renderFile(), call webLib->run().

Upvotes: 1

Velkan
Velkan

Reputation: 7592

The exec must be run in a tread. Alternatively, you can call QApplication::processEvents periodically.

Upvotes: -1

Related Questions