How do I prevent a QToolButton from resizing when changing the ToolButtonStyle? I'm switching between `Qt.ToolButtonIconOnly` and `Qt.ToolButtonTextOnly`, and `QSizePolicy.Fixed` doesn't appear to help.

I am trying to switch back and forth between the text and the icon without it changing size. It should simply place the text in the center of the button.

Sample code (not my actual use for it); move mouse over button to see change:

Qt Code:
  1. from PyQt4.QtCore import *
  2. from PyQt4.QtGui import *
  3.  
  4. class MainWindow(QMainWindow):
  5. def __init__(self):
  6. super().__init__()
  7.  
  8. button = QToolButton(self)
  9. button.enterEvent = lambda e: button.setToolButtonStyle(Qt.ToolButtonTextOnly)
  10. button.leaveEvent = lambda e: button.setToolButtonStyle(Qt.ToolButtonIconOnly)
  11. button.setIcon(self.style().standardIcon(QStyle.SP_MediaVolume))
  12. button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
  13. button.setText('10')
  14. button.setToolButtonStyle(Qt.ToolButtonIconOnly)
  15.  
  16. toolbar = QToolBar(self)
  17. toolbar.setIconSize(QSize(32,32))
  18. toolbar.addWidget(button)
  19. self.addToolBar(Qt.TopToolBarArea, toolbar)
  20.  
  21. if __name__ == '__main__':
  22. import sys
  23. application = QApplication(sys.argv)
  24. window = MainWindow()
  25. window.show()
  26. sys.exit(application.exec_())
To copy to clipboard, switch view to plain text mode