【发布时间】:2022-01-12 14:24:42
【问题描述】:
我觉得我有点累了,可能错过了显而易见的事情,所以请放轻松;)
我正在尝试解决一个问题,我的自定义 QPushButton 类对象显示在一个单独的窗口中(见附图)。如果我通过函数而不是类来实现按钮,那么它会出现在主窗口中。但是,由于应用程序有几个按钮(我删除了按钮以简化代码并帮助故障排除),为了最大限度地减少代码重复,我想实现一个可重用的类。
显然,代码运行正常:按钮正在显示。我的问题是,如何将 ButtonClass 对象链接到 Window 对象?
这是我的代码:
from PyQt6.QtWidgets import QApplication, QPushButton, QWidget
from PyQt6.QtGui import QIcon
from PyQt6.QtCore import *
import sys
class ButtonClass(QPushButton):
def __init__(self, set_image, set_button_geometry, set_button_resize, set_button_visible):
super().__init__()
# Instance variables assigned with arguments
self.set_image = set_image
self.set_button_geometry = set_button_geometry
self.set_button_resize = set_button_resize
self.set_button_visible = set_button_visible
# Initialise instance of QPushButton
self.button = QPushButton()
# Declare variable, inherit QPushButton->QAbstractButton->QWidget functions
self.button_attributes()
def button_attributes(self):
# Assign icon to QPushButton object and insert custom image
self.button.setIcon(QIcon(self.set_image))
# Specify button geometry
self.button.setGeometry(self.set_button_geometry[0],
self.set_button_geometry[1],
self.set_button_geometry[2],
self.set_button_geometry[3])
# Specify Icon size
self.button.setIconSize(QSize(self.set_button_resize[0],
self.set_button_resize[1]))
# Stylesheet attributes
self.button.setStyleSheet("border: 0px")
# Set button visibility
self.button.setVisible(self.set_button_visible)
class Window(QWidget):
def __init__(self):
super().__init__()
# Define window title
self.setWindowTitle("Soular")
# Define window height
self.setFixedHeight(700)
# Define window width
self.setFixedWidth(400)
# window stylesheet defines window background colour
self.setStyleSheet("background-color:'#323232'")
self.move(10, 10)
# initialises play_button from class 'Button_class'
self.play_button = ButtonClass('Images/Play_standard.png', [165, 580, 70, 70], [70, 70], True)
app = QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec())
这就是输出:
【问题讨论】:
-
你为什么要在 inside 按钮类中创建 另一个 按钮?
-
你指的是QPushButton引用'class ButtonClass(QPushButton)'和'self.button_attributes()'吗?
-
@IanThompson 打字错误:删除
self.button = QPushButton()并将self.button更改为self -
哦,当然,哦!谢谢你,我很感激你的帮助。你知道为什么我的按钮仍然出现在一个单独的窗口中吗?
-
@IanThompson 因为您没有使用父级创建小部件(按钮),或者更准确地说,您没有按照应有的方式将其添加到 layout manager。