[Interest] Never ending thread: blocking GUI

Bo Thorsen bo at fioniasoftware.dk
Tue Oct 16 16:06:54 CEST 2012


Den 16-10-2012 15:34, Lincoln Ramsay skrev:
> On 16/10/12 11:15 PM, Sensei wrote:
>> Once in a while, when the GUI needs it, it will "wake the thread up",
>> and run a method of my QThread subclass, in my case, a "find in files"
>> or "rename all files", or any other method.
>>
>> I thought I could simply make run() be an infinite loop, sleeping for a
>> long period (one day).
> You're doing it wrong.
>
> You want an async QObject-based interface (call in via slot, answer via
> signal).
>
>> class ScanFiles : public QObject
>> {
>> public:
>>
>>        ScanFiles(QObject *parent = 0) : QObject(parent) {};
>>
>> signals:
>> QString searchResult();
>> public slots:
>>
>>        // Here I will place the methods that should be run by the thread
>>        void search(const QStringList &files);
>> };
>>
> Then you just put that object on the thread, connect up your signals and
> slots and you're good to go.
>
> QThread *thread = new QThread;
> thread->start();
> ScanFiles *sf = new ScanFiles;
> sf->moveToThread(thread);
> connect(..., sf, SLOT(search(QStringList)));
> connect(sf, SIGNAL(searchResult()), ...);

If this had been another type of forum, I would have pressed the "like", 
"thumbs up" or so :)

I was just about to write an answer when I saw this mail. It is exactly 
the right answer for the question. All the others in this thread are 
slightly off (though Igor's close). Go with this suggestion. If you have 
problems with it, ask about those problems, but stay with this solution.

Bo Thorsen.

Come by my DevDays talk in Berlin - "Designing for testability" - and learn how to build your unit tests into the Qt applications.

Fionia Software - Qt experts for hire.




More information about the Interest mailing list