简体   繁体   English

Pyqt5 获取 QpushButton 相对于 Qwidget 的位置

[英]Pyqt5 get position of a QpushButton with respect to a Qwidget

I have a Qwidget with a QVlayout.我有一个带有 QVlayout 的 Qwidget。 this QVlayout contains number of QPushButtons.这个 QVlayout 包含 QPushButtons 的数量。 I need to get the position of each QPushButton with respect to the parent Qwidget (x1,y1,x2,y2).我需要获取每个 QPushButton 相对于父 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位置 : 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_())

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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