美文网首页
PyQt5 简单的控件拖和拉学习(drag and drop)

PyQt5 简单的控件拖和拉学习(drag and drop)

作者: _Mirage | 来源:发表于2020-04-05 07:10 被阅读0次

    In the first example, we have a QLineEdit and a QPushButton. We drag plain text from the line edit widget and drop it onto the button widget. The button's label will change.
    我们可以把单行输入框中的文本选中后拖拉到按钮上,这样按钮的名字就会改变。

    代码:

    # coding='utf-8'
    
    from PyQt5.QtWidgets import QApplication, QWidget,\
        QPushButton, QLineEdit
    import sys
    
    
    # 因为实现拖拉改变button的标签会很复杂,我们需要重写好几个函数,\
        # 所以这里为了方便我们直接写了个自己的类继承自QPushButton
    class Button(QPushButton):
        # 注意继承的子类也需要重写构造函数,需要参数标题和父组件
        def __init__(self, title, parent):
            # 利用得到的title和parent去初始化父类button
            super(Button, self).__init__(title, parent)
            # 这个很重要!!一定要将拖拉的接受者的setAcceptDrops变成True,\
            #        才能接受从别的地方的拖拉操作的作用
            self.setAcceptDrops(True)
    
        # 重写的这个slot会在将别的组件拖动\
        #       到我们这个按钮时触发(此时拖过来还没放下)
        def dragEnterEvent(self, e) -> None:
            # 此时刚刚拖到我们这个按钮上,但是还没放下,\
            #     我们需要对拖过来的信息进行处理,\
            #      由于我们需要改变按钮的标签内容,\
            #      所以我们只能接受拖过来的文本,而不能是其他内容.
            # e.mimeData()这个返回值是QMimeData对象,
            # 这个对象的hasFomat方法可以判断内容格式是否是某一特定类型
            if e.mimeData().hasFormat('text/plain'):
                # 如果拖拽过来的是文本格式,就可以放上去(松手)
                e.accept()
            else:
                # 如果拖过来的内容不是文本,就不接受,不能放置上去(不能松手)
                e.ignore()
    
        # 和这个对应:self.setAcceptDrops(True)
        # 我们把setAcceptDrops变成True,\
        #   所以我们的拖操作可以对button产生效果.\
        # 而这个重写的函数就是重写button接收到拖过来的东西在它上面放手后\
        #   的slot,这个事件要想触发,必须要dragEnterEvent事件能够接受.\
        #     也就是拖过来还没松手,这时要接受了才能松手触发这个dropEvent slot
        def dropEvent(self, e) -> None:
            # 将按钮标签名设置为拖过来的文本
            self.setText(e.mimeData().text())
    
    
    class Gui(QWidget):
        def __init__(self):
            super(Gui, self).__init__()
            self.start()
    
        def start(self):
            # 创建单行输入文本
            edit = QLineEdit('', self)
            # 这个很重要!! 必须要将edit的setDragEnabled设置为True\
            #       我们才能从输入的文本中拖出它,不然是拖不出的.
            edit.setDragEnabled(True)
            edit.move(20, 65)
    
            button = Button('按钮', self)
            button.move(200, 65)
    
            self.setGeometry(300, 300, 300, 150)
            self.setWindowTitle('简单的拖和拉')
            self.show()
    
    
    app = QApplication(sys.argv)
    gui = Gui()
    sys.exit(app.exec_())
    
    
    运行结果: image.png

    (先在文本框选中,然后将文字拖过去,按钮标签就改变了)

    相关文章

      网友评论

          本文标题:PyQt5 简单的控件拖和拉学习(drag and drop)

          本文链接:https://www.haomeiwen.com/subject/psvjphtx.html