【问题标题】:PyQt5: widget not displayed after being added to layoutPyQt5:添加到布局后不显示小部件
【发布时间】:2017-06-23 21:32:18
【问题描述】:

任务是编写机器人模拟器。我的代码中有三个类: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()

但魔法就在这里。我想让我的模拟器同时显示板子和控件:

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()

我已经花了三个小时试图修复它。我试图在 QBoxLayout 内的 QLabel 上将我的板显示为 QPixmap。我试图用 QHBoxLayout 替换 QBoxLayout。没有任何区别。

【问题讨论】:

  • 您需要在BoardWidget 上设置布局并向其添加小部件(例如,QLabel 显示机器人像素图)。

标签: python qt user-interface layout pyqt


【解决方案1】:

正如@ekhumoro 在cmets 中所说,需要将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")

结果显示在这里:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-30
    • 1970-01-01
    • 2018-02-04
    • 1970-01-01
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多