python - 使用鼠标移动 QtWidgets.QtWidget

标签 python python-3.x pyqt5

我想使用鼠标移动 QtWidgets.QtWidget(不是 QPushButtonQLabel 等)。我在网上到处搜索,但找不到这个问题的答案。 mousePressEvent 似乎是这样,但它不起作用。

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_hGUI(QtWidgets.QWidget):
    def __init__(self):
        QtWidgets.QWidget.__init__(self)

    def setupUi(self, hGUI):
        hGUI.setObjectName("hGUI")
        hGUI.resize(161, 172)
        hGUI.setMinimumSize(QtCore.QSize(200, 200))
        hGUI.setMaximumSize(QtCore.QSize(200, 200))

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    hGUI = QtWidgets.QWidget()
    ui = Ui_hGUI()
    ui.setupUi(hGUI)

    hGUI.show()
    sys.exit(app.exec_())

我使用的是 Python 3.5,我使用 Qt Designer 创建 GUI,然后将其转换为 python 代码。

编辑:我正在尝试通过单击来移动无边框窗口。

最佳答案

先生,这是一个非常简单的问题,

假设您只需拥有一个变量来保存小部件的位置并根据您的需要与其进行交互。

  1. 这个位置变量我们称之为“oldPos”。
  2. 现在按下鼠标即可更新此位置。
  3. 最后但并非最不重要的一点是,您将“oldPos”和 mouseMove 实际位置关联起来并移动您的小部件。
  4. Wallahhhh,这里我们有一个漂亮且简单的可通过鼠标事件移动的小部件。

这是最简单的例子。

from PyQt5.QtWidgets import QWidget

class MyMovableWidget(QWidget):
    """WToolBar is a personalized toolbar."""

    homeAction = None

    oldPos = QPoint()

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

     def mousePressEvent(self, evt):
        """Select the toolbar."""
        self.oldPos = evt.globalPos()

    def mouseMoveEvent(self, evt):
        """Move the toolbar with mouse iteration."""

        delta = QPoint(evt.globalPos() - self.oldPos)
        self.move(self.x() + delta.x(), self.y() + delta.y())
        self.oldPos = evt.globalPos()


if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    coolWidget = MyMovableWidget()
    coolWidget.show()
    sys.exit(app.exec_())

就这么简单不是吗? :D

关于python - 使用鼠标移动 QtWidgets.QtWidget,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41784521/

相关文章:

Python 在关闭 GUI 应用程序时意外退出

python - QComboBox使用QQueryModel,从点击中获取id字段(不显示)

python - 我怎样才能杀死 python matplotlib 脚本?

python - pyomo 中的无效索引/值错误,有什么提示吗?

python - 如何解决 lambda 函数中的内部导入

python - ModuleNotFoundError : No module named 'tf_slim'

python - 为什么我需要用pyqtSlot装饰连接的插槽?

python - 如何(或为什么不)从子类调用 unicode.__init__

python - 按自然顺序对字典键进行排序

python - 无法识别 DataFrame 中的列。关键字错误: 'Date'