Issue
The application I'm writing has several different pages that I switch between with a QStackedWidget
. I want to have a toolbar that is shown only when a certain page is active.
My initial plan was to simply call addToolbar()
from that page, but it appears that only a QMainWindow
has the addToolbar()
method. So instead, I create the toolbar as a member of the page. My QMainWindow
holds the QStackedWidget
and calls addToolbar(self.page.toolbar)
when I switch to that page and removeToolbar(self.page.toolbar)
when I switch away from it.
In the documentation for removeToolbar()
it says: Removes the toolbar from the main window layout and hides it. Note that the toolbar is not deleted.
But it certainly seems as if the toolbar is being deleted. When I start the program, the toolbar is hidden as I want it to be. When I switch to the page, addToolbar()
is called and the toolbar is displayed. When I leave the page, removeToolbar()
is called and it is hidden again. So far so good.
The problem is that any following time that I go to the page, the toolbar is never shown again, even though addToolbar()
is being called each time.
Am I adding a toolbar that has been hidden? How can I unhide it?
Or, alternatively, is it possible to tie a QToolBar
to an arbitrary widget instead of only a QMainWindow
?
Solution
Instead of using addToolBar
and removeToolBar
I used QToolBar
's toggleViewAction()
.
In widget for the page where I want the toolbar, I create the toolbar and set it's toggleViewAction to false, then trigger it. That makes the toolbar initially hidden.
self.toolbar = QtGui.QToolBar(self)
#add the toolbar to the main window
self.parent().addToolBar(self.toolbar)
#start hidden
self.toolbar.toggleViewAction().setChecked(False)
self.toolbar.toggleViewAction().trigger()
Then whenever I switch to or from the page, I trigger toggleViewAction()
again:
def changeMode(self, page_num):
#leaving page
if self.page_stack.currentIndex() == PageEnum.PAGE_WITH_TOOLBAR:
self.tb_page.toolbar.toggleViewAction().trigger()
None
#entering page
if page_num == PageEnum.PAGE_WITH_TOOLBAR:
self.tb_page.toolbar.toggleViewAction().trigger()
None
self.page_stack.setCurrentIndex(page_num)
I feel like a fool for finding the answer so quickly by browsing the QToolBar documentation, but hopefully someone finds this useful.
Answered By - Josh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.