【问题标题】:pyqt5: why the mimeData().text() returns nothing?pyqt5:为什么 mimeData().text() 什么都不返回?
【发布时间】:2015-05-31 14:38:46
【问题描述】:

最近在学习PyQt5,尝试拖一个QPushButton学习本教程Drag & drop a button widget,并做了一些改进让按钮的放置更准确,所以我加了 mime = e.mimeData().text() x, y = mime.split(',') 根据@Avaris 对于这个question,但我发现e.mimeData().text() 没有返回任何应该是光标相对于按钮的本地位置的坐标,我尝试print(mime),并得到一个空行,什么都没有,然后我print(mime.split(','))得到['']

代码如下:

import sys
from PyQt5.QtWidgets import QPushButton, QWidget, QApplication, QLabel
from PyQt5.QtCore import Qt, QMimeData
from PyQt5.QtGui import QDrag
from PyQt5 import QtCore


class Button(QPushButton):

    def __init__(self, title, parent):
        super().__init__(title, parent)

    def mouseMoveEvent(self, e):

        if e.buttons() != Qt.RightButton:
            return

        mimeData = QMimeData()

        drag = QDrag(self)
        drag.setMimeData(mimeData)

       dropAction = drag.exec_(Qt.MoveAction)

    def mousePressEvent(self, e):

        QPushButton.mousePressEvent(self, e)

        if e.button() == Qt.LeftButton:
            print('press')


class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):

        self.setAcceptDrops(True)

        self.button = Button('Button', self)
        self.button.move(100, 65)

        self.setWindowTitle('Click or Move')
        self.setGeometry(300, 300, 280, 150)

    def dragEnterEvent(self, e):

        e.accept()

    def dropEvent(self, e):

        position = e.pos()
        mime = e.mimeData().text()
        x, y = mime.split(',')

        #print(mime.split(','))

        self.button.move(position - QtCore.QPoint(int(x), int(y)))

        e.setDropAction(Qt.MoveAction)
        e.accept()


if __name__ == '__main__':

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

【问题讨论】:

    标签: python-3.x drag-and-drop pyqt5


    【解决方案1】:

    answer of @Avaris 中,您会注意到他们将mimedata 设置为在mouseMoveEvent 中的按钮位置:

    mimeData = QtCore.QMimeData()
    # simple string with 'x,y'
    mimeData.setText('%d,%d' % (e.x(), e.y()))
    

    默认情况下,mimedata 不包含任何内容。你必须自己设置一切!查看QMimeData 的文档,看看您还能做什么(除了设置任意文本)

    【讨论】:

    • 感谢您的回答,它成功了,我应该自己想出来的,没有注意到 mimedata 默认不包含任何内容。
    • @CescFangs 乐于助人。如果这完全回答了您的问题,如果您可以通过单击答案左侧的勾号“接受”我的答案,我将不胜感激。干杯!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-04
    • 1970-01-01
    • 2012-06-18
    相关资源
    最近更新 更多