PyQt5:添加到layou后未显示widget

2024-04-27 02:36:44 发布

您现在位置:Python中文网/ 问答频道 /正文

任务是编写一个机器人仿真器。我的代码中有三个类:ControlWidget、BoardWidget和Emulator(应该在一个窗口中组合Control和Board的主要小部件)。我将使用qpaint在BoardWidget上绘制一些图片。在

class ControlWidget(QFrame):
    def __init__(self):
        super().__init__()        
        self._vbox_main = QVBoxLayout()
        self.initUI()        

    def initUI(self):
        # ... adding some buttons        
        self.setLayout(self._vbox_main)
        self.setGeometry(50, 50, 600, 600)
        self.setWindowTitle('Robot Controller')

class BoardWidget(QWidget):
    def __init__(self):
        super().__init__()       
        self._robot_pixmap = QPixmap("robo.png")            
        self.initUI()            

    def initUI(self):
        self.setStyleSheet("QWidget { background: #123456 }")
        self.setFixedSize(300, 300)
        self.setWindowTitle("Robot Emulator")

如果显示在不同的窗口中,这两个窗口的显示效果都很好:

^{pr2}$

{1美元^

但是魔法来了。我要我的模拟器同时显示板和控件:

class Emulator(QWidget):
    def __init__(self):
        super().__init__()
        self._control = ControlWidget()
        self._board = BoardWidget()        
        self.initUI()
        self.show()

    def initUI(self):
        layout = QBoxLayout(QBoxLayout.RightToLeft, self)
        layout.addWidget(self._control)
        layout.addStretch(1)
        layout.addWidget(self._board)
        self.setLayout(layout)        
        self.setWindowTitle('Robot Emulator')
        self.setWindowIcon(QIcon("./assets/robo.png"))
        # self._board.update()

And the board's background disappears...

我花了三个小时来修理它。我试图将我的董事会作为QPixmap呈现在QBoxLayout内部的QLabel之上。我试图用QHBoxLayout替换QBoxLayout。没什么区别。在


Tags: selfboardinitdefrobotclasslayoutsuper
1条回答
网友
1楼 · 发布于 2024-04-27 02:36:44

正如@ekhurvo在注释中所述,有必要将QPixmap添加到QLabel中,然后使用setLayout()函数将其设置在BoardWidget布局管理器上。在

一个解决方案可能是BoardWidget类的下一个重新实现:

class BoardWidget(QWidget):
    def __init__(self):
        super().__init__()
        self._robot_pixmap = QPixmap("robo.png")
        self.label = QLabel()
        self.label.setPixmap(self._robot_pixmap)
        self._vbox_board = QVBoxLayout()
        self.initUI()

    def initUI(self):
        self._vbox_board.addWidget(self.label)
        self.setLayout(self._vbox_board)
        self.setStyleSheet("QWidget { background: #123456 }")
        self.setFixedSize(300, 300)
        self.setWindowTitle("Robot Emulator")

结果如下:

相关问题 更多 >