回答編集履歴

1

検証してみた。

2019/01/10 14:05

投稿

katsuko
katsuko

スコア3471

test CHANGED
@@ -55,3 +55,157 @@
55
55
 
56
56
 
57
57
  (余談:こう見ると、シグナルのスレッド処理はGTK+よりQtの方が優秀だなぁ)
58
+
59
+
60
+
61
+ ---
62
+
63
+ 検証してみました。
64
+
65
+ (linuxmint19.1/python3.6.7、PyQt5でなくPySide2です。)
66
+
67
+
68
+
69
+ ```python
70
+
71
+ # coding: utf-8
72
+
73
+
74
+
75
+ import sys, threading
76
+
77
+ from PySide2.QtWidgets import *
78
+
79
+ from PySide2.QtCore import *
80
+
81
+ from PySide2.QtGui import *
82
+
83
+
84
+
85
+ def debugOutput(s):
86
+
87
+ sys.stdout.write(s + '\n')
88
+
89
+ sys.stdout.flush()
90
+
91
+
92
+
93
+ class Notifier(QObject):
94
+
95
+ notify = Signal()
96
+
97
+
98
+
99
+ class Thread(QThread):
100
+
101
+ def __init__(self, notifier):
102
+
103
+ super().__init__()
104
+
105
+ self.notifier = notifier
106
+
107
+
108
+
109
+ def run(self):
110
+
111
+ debugOutput('start thread %#x.' % threading.get_ident())
112
+
113
+ self.notifier.notify.emit()
114
+
115
+
116
+
117
+ class MainWindow(QWidget):
118
+
119
+ def __init__(self):
120
+
121
+ super().__init__()
122
+
123
+
124
+
125
+ layout = QVBoxLayout()
126
+
127
+ self.setLayout(layout)
128
+
129
+
130
+
131
+ button = QPushButton('Start')
132
+
133
+ button.clicked.connect(self.onClicked)
134
+
135
+ layout.addWidget(button)
136
+
137
+
138
+
139
+ def onClicked(self):
140
+
141
+ self.notifier = Notifier()
142
+
143
+ self.thread = Thread(self.notifier)
144
+
145
+ self.notifier.moveToThread(self.thread)
146
+
147
+ #self.notifier.notify.connect(self.onNotify)
148
+
149
+ self.notifier.notify.connect(self.onNotify, type=Qt.DirectConnection)
150
+
151
+ self.thread.start()
152
+
153
+
154
+
155
+ def onNotify(self):
156
+
157
+ debugOutput('received notify signal %#x.' % threading.get_ident())
158
+
159
+
160
+
161
+ if __name__ == '__main__':
162
+
163
+ debugOutput('main thread %#x.' % threading.get_ident())
164
+
165
+
166
+
167
+ app = QApplication(sys.argv)
168
+
169
+
170
+
171
+ window = MainWindow()
172
+
173
+ window.show()
174
+
175
+
176
+
177
+ sys.exit(app.exec_())
178
+
179
+ ```
180
+
181
+
182
+
183
+ Qt.DirectConnectionを指定しない場合。
184
+
185
+
186
+
187
+ ```
188
+
189
+ main thread 0x7f2f8fd6f740.
190
+
191
+ start thread 0x7f2f67f02700.
192
+
193
+ received notify signal 0x7f2f8fd6f740.
194
+
195
+ ```
196
+
197
+
198
+
199
+ Qt.DirectConnectionを指定した場合。
200
+
201
+
202
+
203
+ ```
204
+
205
+ main thread 0x7ff207af9740.
206
+
207
+ start thread 0x7ff1dfbea700.
208
+
209
+ received notify signal 0x7ff1dfbea700.
210
+
211
+ ```