简体   繁体   中英

Pyqt5 get position of a QpushButton with respect to a Qwidget

I have a Qwidget with a QVlayout. this QVlayout contains number of QPushButtons. I need to get the position of each QPushButton with respect to the parent Qwidget (x1,y1,x2,y2). Below is a sample code:

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_())

pos : QPoint

This property holds the position of the widget within its parent widget

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_())

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM