简体   繁体   English

PyQt - FigureCanvas 未显示(导航工具栏显示)

[英]PyQt - FigureCanvas is not displayed (Navigation Toolbar does)

I'm trying to implement Drag and Drop on a FigureCanvas.我正在尝试在 FigureCanvas 上实现拖放。 That means, I want to drag the text from the left layout and drop it to the canvas on the right.这意味着,我想将文本从左侧布局拖放到右侧的画布上。 Unfortunately, even though the Navigation Toolbar is displayed, the canvas is not.不幸的是,即使显示了导航工具栏,画布也没有显示。

Before creating the Create_Canvas class to implement the Drag and Drop, I could display everything with no problem.在创建 Create_Canvas 类来实现拖放之前,我可以毫无问题地显示所有内容。 I'm new to programming, I'm not sure if I wrote the Create_Canvas class right.我是编程新手,我不确定我是否正确编写了 Create_Canvas 类。

I also post a picture:我也贴一张图:

在此处输入图片说明

In case you don't have matplotlib installed.如果您没有安装 matplotlib。

Thanks in advance!提前致谢!

import sys, time

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure

import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.colors as mcolors
import matplotlib.colorbar as mcolorbar

import numpy as np
import pylab as pl

import random


class Example(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)
        self.editLayout = QWidget()
        self.edit = QLineEdit('chfghfghf', self)
        self.edit.setDragEnabled(True)

        self.left_layout = QVBoxLayout()
        self.left_layout.addWidget(self.edit)

        self.editLayout.setLayout(self.left_layout)

        #Create the right layout that contains the plot canvas.    
        self.plotLayout = QWidget();

        canvas = Create_Canvas(self)       

        self.button = QPushButton('Plot')

        # set the layout
        self.right_layout = QVBoxLayout()
        self.right_layout.addWidget(canvas)
        self.right_layout.addWidget(self.button)

        self.plotLayout.setLayout(self.right_layout)

        splitter_filebrowser = QSplitter(Qt.Horizontal)
        splitter_filebrowser.addWidget(self.editLayout)
        splitter_filebrowser.addWidget(self.plotLayout)
        splitter_filebrowser.setStretchFactor(1, 1)

        hbox = QHBoxLayout(self)
        hbox.addWidget(splitter_filebrowser)

        self.centralWidget().setLayout(hbox)

        self.setWindowTitle('Simple drag & drop')
        self.setGeometry(750, 100, 600, 500)


class Create_Canvas(QWidget):
    def __init__(self, parent):
        super().__init__(parent)
        self.setAcceptDrops(True)

        figure = plt.figure()
        canvas = FigureCanvas(figure)
        toolbar = NavigationToolbar(canvas, self)

        self.right_layout = QVBoxLayout()
        self.right_layout.addWidget(canvas)
        self.right_layout.addWidget(toolbar)

    def dragEnterEvent(self, e):
        print('entering')
        if e.mimeData().hasFormat('text/plain'):
            e.accept()
        else:
            e.ignore()

    def dragMoveEvent(self, e):
        print('drag moving')

    def dropEvent(self, e):
        print("dropped")


if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    ex.show()
    app.exec_()      

The main point is that you need to add the canvas to a layout and add this layout to the widget.要点是您需要将画布添加到布局并将此布局添加到小部件。 At the end you also should not forget to draw the canvas.最后,您也不应该忘记绘制画布。

class Create_Canvas(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self,parent)
        self.setAcceptDrops(True)

        figure = plt.figure()
        self.canvas = FigureCanvas(figure)
        toolbar = NavigationToolbar(self.canvas, self)

        self.right_layout = QVBoxLayout()
        self.right_layout.addWidget(self.canvas)
        self.right_layout.addWidget(toolbar)
        # set the layout of this widget, otherwise the elements will not be seen.
        self.setLayout(self.right_layout)
        # plot some stuff
        self.ax = figure.add_subplot(111)
        self.ax.plot([1,2,5])        
        # finally draw the canvas
        self.canvas.draw()

(This is how it would look in PyQt4, should be similar in PyQt5). (这就是它在 PyQt4 中的样子,在 PyQt5 中应该类似)。

In PyQt5 you need to use super on the main window class to accept the drops.在 PyQt5 中,您需要在主窗口类上使用 super 来接受放置。 The dropevent function should be like this: dropevent 函数应该是这样的:

def dropEvent(self,e):
        """
        This function will enable the drop file directly on to the 
        main window. The file location will be stored in the self.filename
        """
        if e.mimeData().hasUrls:
            e.setDropAction(QtCore.Qt.CopyAction)
            e.accept()
            for url in e.mimeData().urls():
                if op_sys == 'Darwin':
                    fname = str(NSURL.URLWithString_(str(url.toString())).filePathURL().path())
                else:
                    fname = str(url.toLocalFile())
            self.filename = fname
            print("GOT ADDRESS:",self.filename)
            self.readData()
        else:
            e.ignore() # just like above functions  

The complete code gives this output:完整的代码给出了这个输出: 在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM