【问题标题】:PyQt: Widget constantly moving to position (0, 0)PyQt:小部件不断移动到位置 (0, 0)
【发布时间】:2016-05-28 18:13:30
【问题描述】:

我制作了一个带有事件过滤器的 PyQt 应用程序,它使小部件跟随鼠标移动,它跟随鼠标移动,有时会回到位置 0, 0...

import sys
from PyQt4 import QtGui, QtCore
import resources



class Window(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        widget = QtGui.QWidget(self) # Central Widget
        self.edit = QtGui.QLineEdit(self) # Field that show's mouse position
        self.somewidget = QtGui.QPushButton(self) # Widget that will follow mouse    movement
        self.setCentralWidget(widget)
        self.edit.move(0, 0)
        self.somewidget.show()
        self.timer = QtCore.QTimer(self) # Timer that will be used to set a little interval for mouse movement, to make it smoother.
        self.timer.timeout.connect(self.movefunc)



    def eventFilter(self, source, event): # Defining event type to follow mouse movement without button.
        if event.type() == QtCore.QEvent.MouseMove:
            if event.buttons() == QtCore.Qt.NoButton:
                self.pos = event.pos()  # Define full position.
                self.edit.setText('x: %d, y: %d' % (self.pos.x(), self.pos.y())) # show's mouse x and y position in field.
                self.timer.start(5) # starts timer for 5 milliseconds.
            else:
                pass
        return QtGui.QMainWindow.eventFilter(self, source, event)

    def movefunc(self):
        self.somewidget.move(self.pos.x(), self.pos.y()) # moves widget to mouse position in every 5 milliseconds.




if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    win = Window()
    win.show()
    app.installEventFilter(win)
    sys.exit(app.exec_())

所以你可以看到小部件每 5 毫秒移动一次,所以它可以更平滑,但它有时会回到位置 0, 0(每 1-2 秒),问题可能是什么?我怎样才能将它限制在某些位置,并且它是平滑的?

【问题讨论】:

  • 你想做什么?为什么鼠标移动时按钮会移动?

标签: python pyqt pyqt4


【解决方案1】:

一些事情

您不必多次致电timer.start()。一旦计时器开始,它将继续每 5 毫秒触发一次,直到您调用 timer.stop()

Window 和按钮的坐标系不同。坐标始终位于其父级的几何图形中。对于Window,这意味着全局坐标,因为它是一个顶级窗口。对于按钮,坐标位于窗口的几何图形中,因为窗口是其父级。所以从窗口中给出按钮坐标并没有多大意义。

【讨论】:

  • 我正在尝试为我的游戏制作一个范围的东西,所以背景在范围内移动,随着鼠标的移动,我怎样才能以不同的方式实现呢?
猜你喜欢
  • 2011-10-25
  • 1970-01-01
  • 2018-03-17
  • 2022-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-16
相关资源
最近更新 更多