問題描述
我正在使用 PyQt5 創(chuàng)建一個簡單的 GUI 應(yīng)用程序,我從 API 請求一些數(shù)據(jù),然后用于填充 UI 的各種控件.
I'm creating a simple GUI application using PyQt5 where I request some data from an API which is then used to populate various controls of the UI.
我在 PyQt 中關(guān)注的關(guān)于工作線程的示例似乎都是 QThread
的子類,然后在重寫的 run()
方法中執(zhí)行它們的業(yè)務(wù)邏輯.這工作正常,但我想使用工作人員在不同時間執(zhí)行不同的 API 調(diào)用.
The examples I was following about worker threads in PyQt all seem to sub-class QThread
and then do their business logic in the overridden run()
method. This works fine but I want to execute different API calls at different times using a worker.
所以我的問題是:我是否需要為我希望執(zhí)行的每個操作創(chuàng)建一個特定的工作線程,或者是否有一種方法可以讓我可以使用單個線程類在不同的時間執(zhí)行不同的操作,從而避免創(chuàng)建不同線程子類的開銷?
So my question is: do I need to create a specific worker thread for every operation I wish to do or is there a way of having a single thread class that I can use to carry out different operations at different times and therefore avoid the overhead of creating different thread sub-classes?
推薦答案
你可以做的是設(shè)計(jì)一個對象來完成所有這些任務(wù)(繼承 QObject 用于槽/信號).假設(shè)每個任務(wù)都定義為一個單獨(dú)的函數(shù) - 讓我們將這些函數(shù)指定為插槽.
What you can do is design an object to do all these tasks (inherit QObject for slots / signals). Lets say each task is defined as a separate function - lets designate these functions as slots.
那么(事件的一般順序):
Then (a general order of events):
- 實(shí)例化一個 QThread 對象.
- 實(shí)例化你的類.
- 使用
YouClass->moveToThread(pThread)
將您的對象移動到線程中. - 現(xiàn)在為每個插槽定義一個信號,并將這些信號連接到對象中的相關(guān)插槽.
- 最后使用
pThread->start()
運(yùn)行線程
- instantiate a QThread object.
- instantiate your class.
- Move your object into the thread using
YouClass->moveToThread(pThread)
. - Now define a signal for each slot and connect these signals to the relevant slots in your object.
- Finally run the thread using
pThread->start()
現(xiàn)在您可以發(fā)出信號以在線程中執(zhí)行特定任務(wù).您不需要子類 QThread 只需使用從 QObject 派生的普通類(這樣您就可以使用槽/信號).
Now you can emit a signal to do a particular task in the thread. You do not need to sub-class QThread just use a normal class derived from QObject (so that you can use slots/signals).
您可以在一個線程中使用一個類來執(zhí)行許多操作(注意:它們將被排隊(duì)).或者在多個線程中創(chuàng)建多個類(以并行"運(yùn)行).
You can either use one class in one thread to do many operations (note: they will be queued). Or make many classes in many threads (to run "parallel").
我不太了解python,無法在這里嘗試示例,所以我不會:o
I don't know python well enough to attempt an example here so I won't :o
注意:子類 QThread 的原因是如果您想擴(kuò)展 QThread 類的功能 - 即添加更多/特定的線程相關(guān)功能.QThread 是一個控制線程的類,并不意味著用于運(yùn)行任意/通用任務(wù)......即使你可以濫用它來這樣做,如果你愿意:)
Note: The reason to sub-class QThread would be if you wanted to extend the functionality of the QThread class - i.e. add more/specific thread-related functions. QThread is a class that controls a thread, and is not meant to be used to run arbitrary/generic tasks... even though you can abuse it to do so if you wish :)
這篇關(guān)于所有任務(wù)的單個工作線程還是多個特定工作人員?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!