将 QToolBar 放在 QWidget 而不是 QMainWindow 中

Put a QToolBar in a QWidget instead of QMainWindow

我正在尝试将 QToolBar 放在 QWidget 的布局上,而不是 QMainWindow。在 QMainWindow 和 QWidget 上工作正常,但是当我尝试先将它添加到布局上时,却不是。难道我做错了什么?可能吗?这是我的代码:

from PyQt4 import QtGui, QtCore
import sys


img = '../../Images/logo.png'


if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)


    mainWin = QtGui.QMainWindow()    

    widget = QtGui.QWidget()    
    hLayout = QtGui.QHBoxLayout()

    '''ToolBar On main Window '''    

    basicToolBar = mainWin.addToolBar('Basic')
    basicToolBar.addAction(QtGui.QAction('Test', mainWin))
#    basicToolBar.addAction(QtGui.QAction(QtGui.QIcon(img), 'Test', mainWin))

#    mainWin.show()


    '''ToolBar On Widget '''

    # Case 1: Set widget as parent
#    widgetToolBar = QtGui.QToolBar(widget)
#    widgetToolBar.addAction(QtGui.QAction('Test', widget))
#    widgetToolBar.addAction(QtGui.QAction(QtGui.QIcon(img), QtGui.QAction('Test', widget))

    # Case 2: Set toolBat on a layout
    widgetToolBar = QtGui.QToolBar()
    widgetToolBar.addAction(QtGui.QAction('Test', None))
#   widgetToolBar.addAction(QtGui.QAction(QtGui.QIcon(img), 'Test', None))    
    hLayout.addWidget(widgetToolBar)  
    widget.setLayout(hLayout)

    widget.show()

    # Run 
    sys.exit(app.exec_())

嗯,你读过QToolBar的描述了吗? http://doc.qt.io/qt-5/qtoolbar.html#details 如果您的对象不是 QMainWindow 的子对象,我认为它不会像这样工作。文档说:

When a QToolBar is not a child of a QMainWindow, it loses the ability to populate the extension pop up with widgets added to the toolbar using addWidget(). Please use widget actions created by inheriting QWidgetAction and implementing QWidgetAction::createWidget() instead.

QToolBar 只能在 QMainWindow 中,因为 QMainWindow 有特殊的布局。

因此您可以毫无问题地使用辅助 QMainWindow,如下所示:

from PyQt4 import QtCore, QtGui


class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.tabwidget = QtGui.QTabWidget()
        self.setCentralWidget(self.tabwidget)
        for name in ("tab1", "tab2", "tab3"):
            self.create_widgets(name)

    def create_widgets(self, name):
        w = QtGui.QMainWindow()
        self.tabwidget.addTab(w, name)
        basicToolBar = w.addToolBar('Basic')
        basicToolBar.addAction('Test')
        basicToolBar.addAction(QtGui.QIcon("home.png"), 'Test')
        tab = QtGui.QTabWidget()
        w.setCentralWidget(tab)
        for i in range(10):
            tab.addTab(QtGui.QWidget(), "tab-{}".format(i))


if __name__ == '__main__':
    import sys

    app = QtGui.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())