我有这个小型QT计划:
from PyQt4 import QtGui
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import sys
class QtZListView(QtGui.QListView):
def __init__(self, *args, **kwargs):
QtGui.QListView.__init__(self, *args, **kwargs)
self.model = QtGui.QStringListModel(['a','b','c'])
self.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers)
self.setModel(self.model)
self.setSelectionMode(QtGui.QAbstractItemView.ExtendedSelection)
self.setDragEnabled(True)
def setStringList(self, *args, **kwargs):
return self.model.setStringList(*args, **kwargs)
class mplsubwindow(QtGui.QMdiSubWindow):
def __init__(self, *args, **kwargs):
QtGui.QMdiSubWindow.__init__(self, *args, **kwargs)
self.setWindowTitle("testing")
self.setAcceptDrops(True)
fig = Figure(figsize=(5, 4), dpi=100,
facecolor = self.palette().color(QtGui.QPalette.Background).name()
)
p = FigureCanvas(fig)
self.axes = fig.add_subplot(111)
self.axes.hold(False)
FigureCanvas.setSizePolicy(
self,
QtGui.QSizePolicy.Expanding,
QtGui.QSizePolicy.Expanding
)
FigureCanvas.updateGeometry(self)
fig.tight_layout()
toolbar = NavigationToolbar(p, self)
self.layout().addWidget(toolbar)
self.layout().addWidget(p)
self.resize(400,400)
self.show()
def dragEnterEvent(self, event):
print('entering')
super(mplsubwindow, self).dragEnterEvent(event)
def dragMoveEvent(self, event):
print('drag moving')
super(mplsubwindow, self).dragMoveEvent(event)
def dropEvent(self, event):
print('dropped')
super(mplsubwindow, self).dropEvent(event)
class ExampleApp(QtGui.QMainWindow):
def __init__(self):
super(self.__class__, self).__init__()
mainwid = QtGui.QWidget()
layout = QtGui.QGridLayout()
mainwid.setLayout(layout)
self.mdiarea = QtGui.QMdiArea()
self.setCentralWidget(mainwid)
layout.addWidget(self.mdiarea)
sub = mplsubwindow(self.mdiarea)
fig = Figure()
p = FigureCanvas(fig)
sub.layout().addWidget(p)
sub.show()
layout.addWidget(QtZListView())
def main():
app = QtGui.QApplication(sys.argv)
form = ExampleApp()
form.show()
app.exec_()
if __name__ == '__main__':
main()
我希望能够将底部列表中的一个或多个项目拖到matplotlib画布中。由于某种原因,只调用了enter事件......剩下的拖放事件似乎被忽略了...而且,即使我设置了setAcceptDrops(True),QMdiSubWindow似乎也不接受丢弃。 我在这里缺少什么?
答案 0 :(得分:1)
您需要在dragEnterEvent
方法中接受该事件,否则将忽略移动和放弃事件。
def dragEnterEvent(self, event):
print('entering')
event.accept()
super(mplsubwindow, self).dragEnterEvent(event)
请注意,我真的想强调您应该通过QMdiSubWindow.setWidget()
添加小部件。任何其他方法(例如使用QMdiSubWindow.layout()
或QMdiSubWindow.setCentralWidget()
)都是 MDI窗口不完全支持,并可能导致其他问题。如果您认为setWidget()
没有按照您的意愿行事,请提出一个详细说明问题的新问题,以便在使用setWidget()
时解决问题。