teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

検証してみた。

2019/01/10 14:05

投稿

katsuko
katsuko

スコア3599

answer CHANGED
@@ -26,4 +26,81 @@
26
26
  とすると、ワーカースレッド側で処理されると思います。
27
27
  もちろん、loadProcessメソッドとその他のメソッドでは別スレッドで処理されることになるので、スレッド間の同期処理も考慮する必要がありますので、ご注意。
28
28
 
29
- (余談:こう見ると、シグナルのスレッド処理はGTK+よりQtの方が優秀だなぁ)
29
+ (余談:こう見ると、シグナルのスレッド処理はGTK+よりQtの方が優秀だなぁ)
30
+
31
+ ---
32
+ 検証してみました。
33
+ (linuxmint19.1/python3.6.7、PyQt5でなくPySide2です。)
34
+
35
+ ```python
36
+ # coding: utf-8
37
+
38
+ import sys, threading
39
+ from PySide2.QtWidgets import *
40
+ from PySide2.QtCore import *
41
+ from PySide2.QtGui import *
42
+
43
+ def debugOutput(s):
44
+ sys.stdout.write(s + '\n')
45
+ sys.stdout.flush()
46
+
47
+ class Notifier(QObject):
48
+ notify = Signal()
49
+
50
+ class Thread(QThread):
51
+ def __init__(self, notifier):
52
+ super().__init__()
53
+ self.notifier = notifier
54
+
55
+ def run(self):
56
+ debugOutput('start thread %#x.' % threading.get_ident())
57
+ self.notifier.notify.emit()
58
+
59
+ class MainWindow(QWidget):
60
+ def __init__(self):
61
+ super().__init__()
62
+
63
+ layout = QVBoxLayout()
64
+ self.setLayout(layout)
65
+
66
+ button = QPushButton('Start')
67
+ button.clicked.connect(self.onClicked)
68
+ layout.addWidget(button)
69
+
70
+ def onClicked(self):
71
+ self.notifier = Notifier()
72
+ self.thread = Thread(self.notifier)
73
+ self.notifier.moveToThread(self.thread)
74
+ #self.notifier.notify.connect(self.onNotify)
75
+ self.notifier.notify.connect(self.onNotify, type=Qt.DirectConnection)
76
+ self.thread.start()
77
+
78
+ def onNotify(self):
79
+ debugOutput('received notify signal %#x.' % threading.get_ident())
80
+
81
+ if __name__ == '__main__':
82
+ debugOutput('main thread %#x.' % threading.get_ident())
83
+
84
+ app = QApplication(sys.argv)
85
+
86
+ window = MainWindow()
87
+ window.show()
88
+
89
+ sys.exit(app.exec_())
90
+ ```
91
+
92
+ Qt.DirectConnectionを指定しない場合。
93
+
94
+ ```
95
+ main thread 0x7f2f8fd6f740.
96
+ start thread 0x7f2f67f02700.
97
+ received notify signal 0x7f2f8fd6f740.
98
+ ```
99
+
100
+ Qt.DirectConnectionを指定した場合。
101
+
102
+ ```
103
+ main thread 0x7ff207af9740.
104
+ start thread 0x7ff1dfbea700.
105
+ received notify signal 0x7ff1dfbea700.
106
+ ```