PyQt5でボタンやラベルを追加する方法は何ですか?
PyQt5にボタンとラベルを追加するには、まず適切なモジュールをインポートする必要があります。
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QLabel
メインウィンドウにボタンとラベルを追加してください。
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("My Window")
self.setGeometry(100, 100, 400, 300)
self.button = QPushButton("Click me", self)
self.button.setGeometry(150, 50, 100, 30)
self.button.clicked.connect(self.on_button_click)
self.label = QLabel("Hello, PyQt5!", self)
self.label.setGeometry(150, 100, 100, 30)
def on_button_click(self):
self.label.setText("Button clicked")
if __name__ == '__main__':
app = QApplication([])
window = MyWindow()
window.show()
app.exec()
上記のコードでは、MyWindowというメインウィンドウクラスを作成し、ボタンとラベルを追加しました。ボタンをクリックすると、on_button_clickメソッドがトリガーされ、そのメソッドがラベルのテキスト内容を更新します。最後に、アプリケーションオブジェクトappを作成し、メインウィンドウwindowを表示します。