【问题标题】:Button doesn't show up按钮不显示
【发布时间】:2021-10-15 08:36:41
【问题描述】:

我正在尝试为 python 脚本做一个简单的 GUI,将一些文本转换为特定格式,但按钮不显示在窗口中。

我先创建按钮类

class Button(QPushButton):
    def __init__(self, btn_name=None):
        super().__init__()
        self.button = QPushButton(btn_name)
        self.button.setCursor(
            QCursor(QtCore.Qt.CursorShape.PointingHandCursor))
        self.button.setStyleSheet(
            """*{border: 4px solid 'green';
            border-radius: 45px;
            font-size: 35px;
            color: 'white';
            padding: 25px 0;
            margin: 100px, 200px}
            *:hover{background: 'green'}
            *:pressed{background: 'lightgreen'}"""
        )

然后像这样创建窗口类

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.window = QWidget()
        self.window.resize(500, 500)
        self.window.setWindowTitle("Pantuflis Software")
        self.window.setFixedWidth(1000)
        self.window.setStyleSheet("background: 'black';")
        self.grid = QGridLayout()
        self.window.setLayout(self.grid)
        self.button = Button("Play")
        self.grid.addWidget(self.button)
        self.window.show()

最后添加其余部分

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec())

但是按钮没有显示,只有主窗口显示。我也尝试了相同的方法,但没有从我自己的班级和作品中创建按钮。按钮类中一定有问题,但我看不到是什么。

【问题讨论】:

    标签: python pyqt pyqt6


    【解决方案1】:

    如果要实现继承,则必须将更改应用到类。在您的情况下,它有一个继承自 QPushButton 的类,但是您可以在其中创建不必要的自定义按钮,与主窗口相同。我的建议是 OP 应该查看他关于继承的注释。

    import sys
    
    from PyQt6.QtCore import Qt
    from PyQt6.QtGui import QCursor
    from PyQt6.QtWidgets import QApplication, QGridLayout, QPushButton, QWidget
    
    
    class Button(QPushButton):
        def __init__(self, btn_name=""):
            super().__init__(btn_name)
            self.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
            self.setStyleSheet(
                """*{border: 4px solid 'green';
                border-radius: 45px;
                font-size: 35px;
                color: 'white';
                padding: 25px 0;
                margin: 100px, 200px}
                *:hover{background: 'green'}
                *:pressed{background: 'lightgreen'}"""
            )
    
    
    class MainWindow(QWidget):
        def __init__(self):
            super().__init__()
            self.resize(500, 500)
            self.setWindowTitle("Pantuflis Software")
            self.setFixedWidth(1000)
            self.setStyleSheet("background: 'black';")
            self.grid = QGridLayout(self)
            self.button = Button("Play")
            self.grid.addWidget(self.button)
    
    
    if __name__ == "__main__":
        app = QApplication(sys.argv)
        window = MainWindow()
        window.show()
        sys.exit(app.exec())
    

    【讨论】:

      猜你喜欢
      • 2012-10-08
      • 2019-07-31
      • 2018-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多