QWidget 无法在 QMainWindow 实例 PyQt5 上显示

QWidget cannot display on QMainWindow instance PyQt5

我现在正在学习 PyQt5 并尝试自己做一些小事情。我制作了一个非常基本的自定义工具箱,上面只有 6 个 QPushButtons 按钮,它继承自 QWidget class.

我的问题是无法在我的 QMainWidow 实例上显示我的工具箱。让我告诉你我做了什么;

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class ToolBox(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        btn = [QPushButton('B', self) for i in range(6)]
        for Btn in btn:
            Btn.resize(30, 30)
        self.resize(60, 90)
        k = 0
        for i in range(6):
            btn[i].move((i%2)*30, k*30)
            k += 1 if i % 2 == 1 else 0
        self.show()

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.resize(300, 200)
        self.statusBar().showMessage('Ready!')

        exitAction = QAction(QIcon('idea.png'), 'Exit', self)
        exitAction.setStatusTip('Exit application')
        exitAction.setShortcut('Ctrl+Q')
        exitAction.triggered.connect(qApp.quit)

        menuBar = self.menuBar()
        fileMenu = menuBar.addMenu('File')
        fileMenu.addAction(exitAction)

        t = ToolBox()
        t.move(150, 150)
        t.show() #With and without this line, it doesn't work.

        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    m = MainWindow()
    sys.exit(app.exec_())

您只需将小部件放置在 QMainWindow 中的某处 canvas。您所要做的就是将它放在主窗口中。举个例子,我使用 setCentralWidget() 来定位你的 QWidget。

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class ToolBox(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        btn = [QPushButton('B', self) for i in range(6)]
        for Btn in btn:
            Btn.resize(30, 30)
        self.resize(60, 90)
        k = 0
        for i in range(6):
            btn[i].move((i%2)*30, k*30)
            k += 1 if i % 2 == 1 else 0

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.resize(300, 200)
        self.statusBar().showMessage('Ready!')

        exitAction = QAction(QIcon('idea.png'), 'Exit', self)
        exitAction.setStatusTip('Exit application')
        exitAction.setShortcut('Ctrl+Q')
        exitAction.triggered.connect(qApp.quit)

        menuBar = self.menuBar()
        fileMenu = menuBar.addMenu('File')
        fileMenu.addAction(exitAction)

        t = ToolBox()
        self.setCentralWidget(t)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    m = MainWindow()
    m.show()
    sys.exit(app.exec_())