PySide/PyQtGraph对主Qt事件线程的访问

2024-04-19 05:34:21 发布

您现在位置:Python中文网/ 问答频道 /正文

附加的程序抛出以下错误:

QPixmap:在GUI线程之外使用pixmap是不安全的

QObject::startTimer:无法从其他线程启动计时器

import sys
import PySide
import numpy as np
import pyqtgraph as pg
import threading

from PySide import QtGui, QtCore
from PySide.QtGui import *
from PySide.QtCore import *
from ui_mainWindow import Ui_MainWindow

#-------------------------------------------------------------------------------
# Main Window Class
# handle events and updates to the Qt user interface objects
#-------------------------------------------------------------------------------
class MainWindow(QMainWindow, Ui_MainWindow):

    def __init__(self):
        super(MainWindow, self).__init__()
        self.setupUi(self)
        self.setup_actions()
        self.show()

    def setup_actions(self):
        self.startScopeButton.clicked.connect(self.start_stop_scope)

    def start_stop_scope(self):
        print("starting scope")
        self.scope_display_thread()

    def scope_display_thread(self):
        threading.Thread(target=self._scope_display_thread).start()

    def _scope_display_thread(self):
        global data_ch1      
        data_ch1  = np.random.normal(0, 10, 1000)
        self.graphicsView.plot(data_ch1,clear=True)

#-------------------------------------------------------------------------------
# Main Application Start Point
#-------------------------------------------------------------------------------

def main():
    app = QApplication(sys.argv)  
    mainWin = MainWindow()
    ret = app.exec_()
    sys.exit( ret )

data_ch1 = []
main()

这是我要做的事情的简化版本。。即有一个线程接收和绘制数据。从搜索论坛等,我知道根本上的问题是,我必须从“主Qt事件线程”更新绘图。。但我不知道该怎么做。我的代码的几个信号槽排列看起来很有前途,但只会导致程序崩溃。在

请别紧张,我是一个改过自新的C#人;-)在C或Java中通常我会在paint方法重写中绘制,然后在加载新数据时强制应用程序重新绘制。看来PyQtGraph.plot()想马上画画??我可以异步添加数据,然后告诉主线程去重新绘制场景吗??在

谢谢你!在


Tags: fromimportselfdatadefdisplaysys绘制
1条回答
网友
1楼 · 发布于 2024-04-19 05:34:21

当你评论你的问题时,你只能更新主线程中的GUI,那么这类问题的策略是通过信号将次线程的数据发送到主线程。在

信号可以携带多个数据,但这些数据必须在其创建过程中指明,创建方法如下:

signal = QtCore.Signal(type_1, type_2, ..., type_n)

在您的特定情况下,np.random.normal (0, 10, 1000)是{},可以通过执行以下操作轻松获得:

^{pr2}$

输出:

^{3}$

或者我们可以使用object,因为所有类都继承自该基类。然后我们将该信号与绘图函数连接,在本例中,我们将使用lambda函数,如下所示:

class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
    signal = QtCore.Signal(np.ndarray) # or signal = QtCore.Signal(object)

    def __init__(self):
        [..]
        self.show()

        self.signal.connect(lambda data: self.graphicsView.plot(data, clear=True))

    [...]

    def _scope_display_thread(self):
        data_ch1 = np.random.normal(0, 10, 1000)
        self.signal.emit(data_ch1)

相关问题 更多 >