PyQt5 – 获取按钮的大小

PyQt5 – 获取按钮的大小

在这篇文章中,我们将看到如何获得按钮的大小。基本上有两种方法来获取按钮的大小。让我们通过例子来看看这两种方法。

方法1: 通过使用size方法

这个方法将返回QSize对象,它将告诉我们按钮的宽度和高度。

语法: button.size()

参数: 它不需要参数。

返回: 它返回QSize对象。

代码。

# importing libraries
from PyQt5.QtWidgets import * 
from PyQt5.QtGui import * 
from PyQt5.QtCore import * 
import sys
  
  
class Window(QMainWindow):
    def __init__(self):
        super().__init__()
  
        # setting title
        self.setWindowTitle("Python ")
  
        # setting geometry
        self.setGeometry(100, 100, 600, 400)
  
        # calling method
        self.UiComponents()
  
  
  
    # method for widgets
    def UiComponents(self):
  
        # creating a push button
        button = QPushButton("CLICK", self)
  
        # setting geometry of button
        # rectangular shape i.e width > height
        button.setGeometry(200, 150, 150, 40)
  
        # adding action to a button
        button.clicked.connect(self.clickme)
  
        # printing button size
        print(button.size())
  
  
  
    # action method
    def clickme(self):
  
        # printing pressed
        print("pressed")
  
# create pyqt5 app
App = QApplication(sys.argv)
  
# create the instance of our Window
window = Window()

输出:

PyQt5.QtCore.QSize(150, 40)

方法2: 通过使用geometry或rect方法。

这些方法将返回QRect对象,它将告诉人们按钮的宽度和高度,以及按钮的位置。

语法:

button.geometry()
button.rect()

参数: 不需要参数

返回值: 返回 QRect 对象.

代码 :

# importing libraries
from PyQt5.QtWidgets import * 
from PyQt5.QtGui import * 
from PyQt5.QtCore import * 
import sys
  
  
class Window(QMainWindow):
    def __init__(self):
        super().__init__()
  
        # setting title
        self.setWindowTitle("Python ")
  
        # setting geometry
        self.setGeometry(100, 100, 600, 400)
  
        # calling method
        self.UiComponents()
  
  
  
    # method for widgets
    def UiComponents(self):
  
        # creating a push button
        button = QPushButton("CLICK", self)
  
        # setting geometry of button
        # rectangular shape i.e width > height
        button.setGeometry(200, 150, 150, 40)
  
        # adding action to a button
        button.clicked.connect(self.clickme)
  
        # printing button size
        print(button.geometry())
        print(button.rect())
  
  
  
    # action method
    def clickme(self):
  
        # printing pressed
        print("pressed")
  
# create pyqt5 app
App = QApplication(sys.argv)
  
# create the instance of our Window
window = Window()

输出:

PyQt5.QtCore.QRect(200, 150, 150, 40)
PyQt5.QtCore.QRect(0, 0, 150, 40)

注: geometry和rect方法给出的尺寸结果相同,但位置不同。geometry会给出相对于主窗口的位置,rect方法会给出相对于它自己的位置。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程