PyQt でボタンに背景画像を設定の方法

PyQtのボタンに背景画像を設定するにはQPushButtonクラスのsetStyleSheet()メソッドを使用して、CSSスタイルで背景画像を設定します。具体的な手順は次のとおりです。

  1. 必要なモジュールをインポートする
from PyQt5.QtWidgets import QApplication, QPushButton
from PyQt5.QtGui import QPixmap
  1. QPushButtonオブジェクトを生成します。
button = QPushButton()
  1. バックグラウンドイメージのロード:
background_img = QPixmap("path_to_image.jpg") # 替换为你的图片路径
  1. 背景画像のサイズを設定する
background_img = background_img.scaled(button.size(), aspectRatioMode=Qt.IgnoreAspectRatio)
  1. ボタンに背景画像を適用する:
button.setStyleSheet("border-image: url(%s);" % background_img)

上述のステップは以下のように1つの関数にまとめられます。

def set_button_background(button, image_path):
    button.setStyleSheet("border-image: url(%s);" % image_path)

ボタンの背景画像を設定するにはset_button_background()関数を呼び出します。

button = QPushButton()
set_button_background(button, "path_to_image.jpg")  # 替换为你的图片路径

これでボタンの背景画像の設定は完了です。

bannerAds