我想使用鼠标移动 QtWidgets.QtWidget(不是 QPushButton、QLabel 等)。我在网上到处搜索,但找不到这个问题的答案。 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 代码。
编辑:我正在尝试通过单击来移动无边框窗口。
最佳答案
先生,这是一个非常简单的问题,
假设您只需拥有一个变量来保存小部件的位置并根据您的需要与其进行交互。
- 这个位置变量我们称之为“oldPos”。
- 现在按下鼠标即可更新此位置。
- 最后但并非最不重要的一点是,您将“oldPos”和 mouseMove 实际位置关联起来并移动您的小部件。
- 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/