如何在 PyQt5 的 QWidget 中使用 statusBar().showMessage()?

Imr*_*nti 2 python pyqt5

我正在尝试学习 PyQt5/Python 3.6.3。我试图在单击按钮时在状态栏中显示一条消息。问题是上述按钮位于 QWidget 内,据我所知,statusBar() 仅在 QMainWindow 中可用。这是我到目前为止拼凑的代码......

import sys
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets  import QStatusBar, QMainWindow, QApplication, QWidget,QHBoxLayout, QVBoxLayout, QPushButton, QSlider, QLCDNumber, QLabel

class MyMainWindow(QMainWindow):

    def __init__(self, parent=None):
        super().__init__()
        self.main_widget = FormWidget(self)
        self.setCentralWidget(self.main_widget)
        self.init_UI()

    def init_UI(self):
        self.statusBar().showMessage('Ready')
        self.setGeometry(200, 100, 300, 300)
        self.setWindowTitle('Central Widget')
        self.show()

class FormWidget(QWidget):

    def __init__(self, parent):
        super(FormWidget, self).__init__(parent)
        self.init_UI()

    def init_UI(self):
        hbox = QHBoxLayout()
        button_1 = QPushButton('Button 1', self)
        button_1.clicked.connect(self.buttonClicked)
        hbox.addWidget(button_1)
        button_2 = QPushButton('Button 2', self)
        button_2.clicked.connect(self.buttonClicked)
        hbox.addWidget(button_2)
        self.setLayout(hbox)
        self.setGeometry(200, 100, 300, 300)
        self.setWindowTitle('Slider and LCD')
        self.show()

    def buttonClicked(self):
        sender = self.sender()
        self.statusBar.showMessage(sender.text() + ' was clicked')

if __name__ == '__main__':
    APP = QApplication(sys.argv)
    ex = MyMainWindow()
    sys.exit(APP.exec_())
Run Code Online (Sandbox Code Playgroud)

当我运行它时,我收到以下错误:

Traceback (most recent call last):
  File "central_widget_test.py", line 40, in buttonClicked
    self.statusBar.showMessage(sender.text() + ' was clicked')
AttributeError: 'FormWidget' object has no attribute 'statusBar'
Run Code Online (Sandbox Code Playgroud)

有人可以帮我解决这个问题吗?

Mar*_*ell 5

您应该在您的MyMainWindow类上初始化一个状态栏对象,该对象将来可以更新。

FormWidget然后您可以通过引用该MyMainWindow对象来更新状态栏。

class MyMainWindow(QMainWindow):

    . . .

    def init_UI(self):
        self.statusbar = self.statusBar()
        self.statusbar.showMessage('Ready')
        self.setGeometry(200, 100, 300, 300)
        self.setWindowTitle('Central Widget')
        self.show()

class FormWidget(QWidget):

    def __init__(self, parent):
        super(FormWidget, self).__init__(parent)
        self.parent = parent
        self.init_UI()

    . . .

     def buttonClicked(self):
        sender = self.sender()
        self.parent.statusbar.showMessage(sender.text() + ' was clicked')
Run Code Online (Sandbox Code Playgroud)