我能得到Qwidget的绝对位置吗?

2024-04-27 02:22:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试了几种方法来获得QWidget的位置。我想要的是右小部件外缘的位置(确切地说,x位置)。但是我找不到办法。我能得到Qwidget的绝对位置吗

为了进行调试,我创建了一个代码,用于在单击鼠标时返回位置。通过单击边界获得的结果是QPoint(134462)。我想不用手动的方法得到134号。谢谢你的帮助

enter image description here

import sys
from PyQt5 import QtGui, QtCore, QtWidgets


class TestAbsPos(QtWidgets.QDialog):
    def __init__(self, parent=None):
        # Can I get an absolute position of qwidget?
        super(TestAbsPos, self).__init__(parent)

        self.resize(1080, 720)

        self.setStyleSheet("QWidget { background-color: %s }" % QtGui.QColor(26, 36, 45).name())

        self.leftWidget = QtWidgets.QWidget(self)
        self.rightWidget = QtWidgets.QScrollArea(self)
        self.rightWidget.setGeometry(0, 0, self.width(), self.height())

        window_layout = QtWidgets.QHBoxLayout()
        self.setLayout(window_layout)

        window_layout.addWidget(self.leftWidget)
        window_layout.addWidget(self.rightWidget)
        window_layout.setStretch(0, 1)
        window_layout.setStretch(1, 8)
        print(self.rightWidget.geometry())
        print(self.leftWidget.geometry())
        print(self.rightWidget.frameGeometry())
        print(self.leftWidget.frameGeometry())
        print(self.rightWidget.pos())
        print(self.leftWidget.pos())
        print(self.rightWidget.x())
        print(self.leftWidget.x())
        print(self.rightWidget.rect().topLeft())
        print(self.rightWidget.rect().topRight())
        print(self.leftWidget.rect().bottomRight())
        print(self.rightWidget.mapToGlobal(self.rightWidget.rect().topLeft()))
        print(self.rightWidget.mapToParent(self.rightWidget.rect().topLeft()))
        print(self.leftWidget.mapToGlobal(self.rightWidget.rect().topLeft()))
        print(self.leftWidget.mapToParent(QtCore.QPoint(0, 0)))

    def mousePressEvent(self, event):
        print(event.pos())


if __name__ == "__main__":
    app = QtWidgets.QApplication([])
    dl = TestAbsPos()
    dl.exec_()
    sys.exit(app.closeAllWindows())