我是一個新手QT。我有一個擴展類的小部件類:QT如何把我的函數成線
class myclass: public Qwidget
{
Q_OBJECT
public:
void myfunction(int);
slots:
void myslot(int)
{
//Here I want to put myfunction into a thread
}
...
}
我不知道該怎麼做。請幫幫我。
我是一個新手QT。我有一個擴展類的小部件類:QT如何把我的函數成線
class myclass: public Qwidget
{
Q_OBJECT
public:
void myfunction(int);
slots:
void myslot(int)
{
//Here I want to put myfunction into a thread
}
...
}
我不知道該怎麼做。請幫幫我。
添加QThread
成員,那麼在myslot
移動你的對象的線程並運行的功能。
class myclass: public Qwidget
{
QThread thread;
public:
slots:
void myfunction(int); //changed to slot
void myslot(int)
{
//Here I want to put myfunction into a thread
moveToThread(&thread);
connect(&thread, SIGNAL(started()), this, SLOT(myfunction())); //cant have parameter sorry, when using connect
thread.start();
}
...
}
我的回答是基本相同,從這個帖子:Is it possible to implement polling with QThread without subclassing it?
你提的問題是非常廣泛的。請找一些替代品,可能是有益的給你:
的對象,如果它有一個 父母不能移動。
由於您的對象是一個小部件,我認爲它將有一個父項。
所以這是不可能,這種方法將是對您有用。
另一種替代方法是使用QtConcurrent::run()這允許一個方法由另一個線程執行。但是這樣你不能使用信號/插槽機制。既然你宣佈你的方法是一個插槽。我假定你想使用這種機制。如果你不保健那麼這種方法將對你有用。
最後,你可以創建你的插槽內的QThread子類,並執行任何你喜歡那裏。
這就是我所能想到的。
我希望這會有所幫助。
的Qt文檔說:moveToThread更改線程的親和力此對象和它的孩子。如果該對象具有父級,則該對象無法移動。他有一個小部件,它可能有一個父母。你必須在這裏小心這個小部件的父項。你可能根本無法移動它!你怎麼看 ? – 2011-06-17 08:28:48
感謝您的幫助。它幫助了我很多:D – 2011-06-17 08:42:12
@orcunc:我需要改變它的孩子以在不影響主進程的情況下解決新線程中的問題。之後,它會將值返回給主線程。這是我的想法。你有什麼想法來解決這個問題嗎?請告訴我。 – 2011-06-17 08:49:45