凌的博客

您现在的位置是: 首页 > 学无止境 > python > 

python

31. PyQt6 中的拖拽操作

2023-10-17 python 705
import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QPushButton, QLineEdit
from PyQt6.QtGui import QGuiApplication


class Button(QPushButton):

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

        self.setAcceptDrops(True)

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

    def dropEvent(self, e):
        self.setText(e.mimeData().text())


class App(QMainWindow):

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

    def initUI(self):
        self.setWindowTitle("PyQt6 中的拖拽操作")

        edit_text = QLineEdit("", self)
        edit_text.setDragEnabled(True)

        edit_text.move(30, 65)

        button = Button("按钮", self)
        button.move(190, 65)

        self.setGeometry(100, 100, 400, 300)
        self.center()

    def center(self):
        qr = self.frameGeometry()
        cp = QGuiApplication.primaryScreen().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())


if __name__ == "__main__":
    app = QApplication(sys.argv)
    cls_app = App()
    cls_app.show()
    sys.exit(app.exec())

image.png

文章评论

0条评论