PyQt5 - 根据文本调整按钮的大小
在本文中,我们将了解如何根据文本调整按钮的大小。我们知道,每次手动调整按钮大小很困难时,我们都可以使用resize
方法更改按钮的大小。因此,我们有adjustSize
方法,它会根据其中的文本自动调整按钮的大小。
Syntax : button.adjustSize()
Argument : It takes no argument.
Action performed : It changes the size of button according to the text in it.
代码 :
# 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()
# showing all the widgets
self.show()
# method for widgets
def UiComponents(self):
# creating a push button
button = QPushButton("CLICK", self)
# setting geometry of button
button.setGeometry(200, 150, 200, 40)
# adjusting the size of button
button.adjustSize()
# adding action to a button
button.clicked.connect(self.clickme)
# action method
def clickme(self):
# printing pressed
print("pressed")
# create pyqt5 app
App = QApplication(sys.argv)
# create the instance of our Window
window = Window()
# start the app
sys.exit(App.exec())
输出 :