qt - 将mapToGlobal应用于主窗口位置

标签 qt pyqt pyside

下面是一些创建单个窗口的代码,只是为了好玩,让您在窗口中单击以打印 self.pos()self.mapToGlobal(self.pos( )):

from PySide import QtGui, QtCore

class WinPosExplore(QtGui.QWidget):
    def __init__(self):
        QtGui.QApplication.setStyle(QtGui.QStyleFactory.create("Plastique"))
        QtGui.QWidget.__init__(self)
        self.show()

    def mousePressEvent(self, event):
        if event.buttons() == QtCore.Qt.LeftButton:
            winPos=self.pos() 
            globalWinPos = self.mapToGlobal(winPos)  
            msg1="winPos=self.pos(): <{0}, {1}>\n".format(winPos.x(), winPos.y())
            msg2="self.mapToGlobal(winPos): <{0}, {1}>\n\n".format(globalWinPos.x(), globalWinPos.y())
            print msg1 + msg2

def main():
    import sys
    qtApp=QtGui.QApplication(sys.argv)
    myWinPos=WinPosExplore()
    sys.exit(qtApp.exec_())

if __name__=="__main__":
    main()

因为我只使用一个顶级窗口,所以我希望两组坐标相同。也就是说,我希望程序能够意识到,对于应用程序的父窗口,mapToGlobal 只是标识函数。但事实并非如此。我以无法解释的方式(我)得到了不同的坐标。例如,以下是一份打印输出:

winPos=self.pos(): <86, 101> 
self.mapToGlobal(winPos): <176, 225>

谁能解释一下发生了什么?

注意,我意识到这在某种程度上是一个愚蠢的练习(从技术上讲,我们不需要主窗口的mapToGlobal,正如 this post at qtforum 所指出的)。但我仍然很好奇是否有人能在这个极端情况下理解这种行为。

最佳答案

文档:

QPoint QWidget::mapToGlobal ( const QPoint & pos ) const

Translates the widget coordinate pos to global screen coordinates. For example, mapToGlobal(QPoint(0,0)) would give the global coordinates of the top-left pixel of the widget.

mapToGlobal输入是小部件坐标中的一个点,即它相对于小部件区域的左上角。

为了澄清这一点,请考虑来自 docs 的这张图片:

enter image description here

mapToGlobal(self.pos()) 会给你 self.geometry().topLeft() + self.pos()

注意:mapToGlobal(QPoint(0, 0)) 也不会给出与 self.pos() 相同的结果。这是因为像标题栏等窗口装饰不包含在小部件区域中(请参见geometry().topLeft()pos()之间的区别上图)。

关于qt - 将mapToGlobal应用于主窗口位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24644609/

相关文章:

c++ - 获取QtDesigner制作的Widget指针

python - 如何创建复选框列表

python - Pyside:QScrollArea 调整大小小部件

python - 尝试构建 --onefile 时 PyQt 出现 PyInstaller 错误

python - 如何为 QGraphicsItem 中有孔的形状获取鼠标悬停事件?

c++ - 如何在 QPixmap 上应用深色 mask 层?

qt - 如何从 Qt 项目文件中引用 Qt Creator 当前构建目录?

c++ - QWebview:关闭在QWebview qt加载图片

C++ 基本文件 i/o,读取失败

python - QToolBar 的大小和与隐藏操作的对齐