PyQt5 – 根据文本调整按钮的大小
在这篇文章中,我们将看到如何根据文本来调整按钮的大小。我们知道我们可以使用resize方法来改变按钮的大小,但每次手动调整它的大小都很困难。因此,我们有调整大小的方法,可以根据按钮中的文字自动调整其大小。
语法: button.adjustsize()
参数: 它不需要参数。
执行的动作: 它根据按钮中的文本改变按钮的大小。
代码。
# 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())
输出 :