Pyqt5获得QpushButton相对于Qwidget的位置

问题描述 投票:0回答:1

我有一个带有QVlayout的Qwidget。此QVlayout包含多个QPushButton。我需要获取每个QPushButton相对于父Qwidget(x1,y1,x2,y2)的位置。下面是示例代码:

import sys
from PyQt5.QtWidgets import (QWidget, QPushButton, 
    QHBoxLayout, QVBoxLayout, QApplication)


class Example(QWidget):

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

        self.initUI()


    def initUI(self):

        okButton = QPushButton("OK")
        cancelButton = QPushButton("Cancel")

        # this is to get position of the button in 
        okButton.clicked.connect(self.pos)
        cancelButton.clicked.connect(self.pos)

        vbox = QVBoxLayout()
        vbox.addWidget(okButton)
        vbox.addWidget(cancelButton)

        self.setLayout(vbox)    

        self.setGeometry(300, 300, 300, 150)
        self.setWindowTitle('Buttons')    
        self.show()

    # this function is to get position with respect to the QWidget
    def pos(self):
        return pos

if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())
python pyqt5
1个回答
0
投票

pos:QPoint

此属性保存窗口小部件在其父窗口小部件中的位置

import sys
from PyQt5.QtWidgets import (QWidget, QPushButton, 
    QHBoxLayout, QVBoxLayout, QApplication)


class Example(QWidget):

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

        self.initUI()


    def initUI(self):

        self.okButton = QPushButton("OK")
        self.cancelButton = QPushButton("Cancel")

        # this is to get position of the button in 
        self.okButton.clicked.connect(self.pos)
        self.cancelButton.clicked.connect(self.pos)

        vbox = QVBoxLayout()
        vbox.addWidget(self.okButton)
        vbox.addWidget(self.cancelButton)

        self.setLayout(vbox)    

        self.setGeometry(300, 300, 300, 150)
        self.setWindowTitle('Buttons')    
        self.show()

    # this function is to get position with respect to the QWidget
    def pos(self):
        textButton = self.sender().text()
        if textButton == 'OK':
            pos = self.okButton.pos()
        else:
            pos = self.cancelButton.pos()

        print("Button `{:6}`: x={}, y={}".format(textButton, pos.x(), pos.y()))
        return pos

if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.