PyQt5:添加到布局

时间:2017-02-06 20:03:55

标签: python qt user-interface layout pyqt

任务是编写机器人模拟器。我的代码中有三个类:ControlWidget,BoardWidget和Emulator(应该在一个窗口中组合Control和Board的主要小部件)。我将使用QPainter在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")

如果在不同的窗口中显示,它们都很好看:

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

That's the result...

但魔术来到这里。我希望我的模拟器显示板和控件:

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。没有任何区别。

1 个答案:

答案 0 :(得分:1)

正如@ekhumoro在评论中所述,有必要将QPixmap添加到QLabel,然后使用BoardWidget功能在setLayout()布局管理器上进行设置。

一个解决方案可能是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")

结果如下所示:

相关问题