问题描述
我现在正在学习 PyQt5,并尝试自己做一些小事.我制作了一个非常基本的自定义工具箱,上面只有 6 个 QPushButton
按钮,它继承自 QWidget
类.
I am learning PyQt5 now and tried to do something little on my own. I have made a very basic custom toolbox, which has just 6 QPushButton
s buttons on it, which inherits from QWidget
class.
我的问题是我无法在我的 QMainWidow
实例上显示我的工具箱.让我告诉你我做了什么;
My problem is that I can't display my toolbox on my QMainWidow
instance. Let me show you what I did;
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 画布中的某个位置.您所要做的就是将其放置在 MainWindow 中.举个例子,我使用 setCentralWidget()
来定位你的 QWidget.
You just need to position your widget somewhere in the QMainWindow canvas. All you have to do is position it in the MainWindow. Just for an example, I use setCentralWidget()
to position your 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_())
这篇关于QWidget 无法在 QMainWindow 实例 PyQt5 上显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!