0

I'm trying to integrate QFontComboBox within Qmenu. I try to make two things happen when selecting a particular font from the menu:

  1. The Qmenu will close.
  2. print the selected font.

from PyQt5.QtCore import QObject
from PyQt5.QtGui import QIcon, QFont, QCursor
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QFontComboBox, QWidgetAction, QMenu, QPushButton
class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Pyside2 FontCombo Box")
        self.setGeometry(300,200,300,250)
        self.setFontBox()
        self.setIcon()
        self.show()
    def setIcon(self):
        appIcon = QIcon("icon.png")
        self.setWindowIcon(appIcon)
    def setFontBox(self):
        self.font_button = QPushButton(self)
        self.font_button.setFixedWidth(300)
        self.font_button.clicked.connect(lambda: self.setFontmenu())
        vbox = QVBoxLayout()
        vbox.addWidget(self.font_button)
        self.setLayout(vbox)
    def setFontmenu(self):
        font_menu = QMenu()
        font_submenu = QFontComboBox()
        font_submenu.setCurrentFont(QFont("Arial"))
        objectTest = QObject()
        widget = QWidgetAction(objectTest)
        widget.setDefaultWidget(font_submenu)
        font_menu.addAction(widget)
        font_menu.exec_(QCursor.pos())
        menu = font_menu
        menu.addSeparator()
        font_submenu.showPopup()
        font_submenu.setFocus()
        font_submenu.currentFontChanged.connect(self._changed)
    def _changed(self):
        font = self.currentFont().family()
        print(font)
        return
myapp = QApplication(sys.argv)
window = Window()
myapp.exec_()
sys.exit()
ROOMBON
  • 1
  • 1
  • Your code doesn't make a lot of sense. Most importantly, you're trying to add a separator to the menu, show the popup and connect a signal ***after*** the menu has been shown and (eventually) triggered. Just add a `font` argument to `_changed`, remove the first line (which would be invalid anyway), and also replace all lines after `font_menu.exec_` with `self._changed(font_submenu.currentFont())`. – musicamante Jun 03 '22 at 04:06
  • This could have been a solution but I need it done before the Qmenu closes – ROOMBON Jun 03 '22 at 08:06
  • You don't understand: *everything* after `menu.exec()` will *always* be called **after** the menu closes, also in your code. So, if you want to do something different, please be more clear. – musicamante Jun 03 '22 at 11:15

0 Answers0