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

时间:2018-01-03 13:01:11

标签: 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_())

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

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'

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

1 个答案:

答案 0 :(得分:1)

您应该初始化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')