Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. Qt for Python
  4. Having issues with two identical implementations of keyPressEvent
Forum Updated to NodeBB v4.3 + New Features

Having issues with two identical implementations of keyPressEvent

Scheduled Pinned Locked Moved Unsolved Qt for Python
12 Posts 2 Posters 999 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • F Offline
    F Offline
    fvez_demtroys
    wrote on last edited by
    #1

    Hi,

    We are making an internal configuration tool using PyQt5 5.15.4.
    Development is done on Windows 10.

    I have two custom windows that can be shown in my app.
    I want to map control+w to close the windows.
    In both window widgets, I re-implemented the keyPressEvent function.

    Here is my implementation for both.

    def keyPressEvent(self, event):
        print('StickerPrintingWindow keyPressEvent')
        if event.modifiers() & QtCore.Qt.ControlModifier:
            print(event.key())
            if event.key() == QtCore.Qt.Key_W:
                self.close()
                return
            if event.key() == QtCore.Qt.Key_M:
                self.showMinimized()
                return
        super(StickerPrintingWindow, self).keyPressEvent(event)
    
    def keyPressEvent(self, event):
        print('SoftwareTestingWindow keyPressEvent')
        if event.modifiers() & QtCore.Qt.ControlModifier:
            print(event.key())
            if event.key() == QtCore.Qt.Key_W:
                self.close()
                return
            if event.key() == QtCore.Qt.Key_M:
                self.showMinimized()
                return
        super(SoftwareTestingWindow, self).keyPressEvent(event)
    

    From what I can tell, both these implementations are identical (other than the class name)
    For some reason, the StickerPrintingWindow works correctly and the SoftwareTestingWindow does not.

    When I hit control + w on the StickerPrintingWindow , I get the following prints:
    "
    StickerPrintingWindow keyPressEvent
    16777249
    StickerPrintingWindow keyPressEvent
    87
    "
    Where 16777249 is the control key and 87 is the W key.

    When I hit control + w on the SoftwareTestingWindow, I get the following prints:
    "
    SoftwareSettingsWindow keyPressEvent
    16777249
    "
    It is as if the event doesn't fire the second time correctly when hitting the W key.

    Any ideas on what could cause this?
    If needed I can also post a working sample application with both windows.

    Thanks in advance!
    FV

    SGaistS 1 Reply Last reply
    0
    • F fvez_demtroys

      Hi,

      We are making an internal configuration tool using PyQt5 5.15.4.
      Development is done on Windows 10.

      I have two custom windows that can be shown in my app.
      I want to map control+w to close the windows.
      In both window widgets, I re-implemented the keyPressEvent function.

      Here is my implementation for both.

      def keyPressEvent(self, event):
          print('StickerPrintingWindow keyPressEvent')
          if event.modifiers() & QtCore.Qt.ControlModifier:
              print(event.key())
              if event.key() == QtCore.Qt.Key_W:
                  self.close()
                  return
              if event.key() == QtCore.Qt.Key_M:
                  self.showMinimized()
                  return
          super(StickerPrintingWindow, self).keyPressEvent(event)
      
      def keyPressEvent(self, event):
          print('SoftwareTestingWindow keyPressEvent')
          if event.modifiers() & QtCore.Qt.ControlModifier:
              print(event.key())
              if event.key() == QtCore.Qt.Key_W:
                  self.close()
                  return
              if event.key() == QtCore.Qt.Key_M:
                  self.showMinimized()
                  return
          super(SoftwareTestingWindow, self).keyPressEvent(event)
      

      From what I can tell, both these implementations are identical (other than the class name)
      For some reason, the StickerPrintingWindow works correctly and the SoftwareTestingWindow does not.

      When I hit control + w on the StickerPrintingWindow , I get the following prints:
      "
      StickerPrintingWindow keyPressEvent
      16777249
      StickerPrintingWindow keyPressEvent
      87
      "
      Where 16777249 is the control key and 87 is the W key.

      When I hit control + w on the SoftwareTestingWindow, I get the following prints:
      "
      SoftwareSettingsWindow keyPressEvent
      16777249
      "
      It is as if the event doesn't fire the second time correctly when hitting the W key.

      Any ideas on what could cause this?
      If needed I can also post a working sample application with both windows.

      Thanks in advance!
      FV

      SGaistS Offline
      SGaistS Offline
      SGaist
      Lifetime Qt Champion
      wrote on last edited by
      #2

      Hi,

      What do you use that is different between both widgets ?

      Maybe something different having keyboard focus ?

      Interested in AI ? www.idiap.ch
      Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

      1 Reply Last reply
      0
      • F Offline
        F Offline
        fvez_demtroys
        wrote on last edited by
        #3

        Hi @SGaist,

        I am really not sure, from what I can tell, the usage is identical.
        Both windows are based on QMainWindow.

        If it was something about keyboard focus, wouldn't the problematic window catch nothing at all?
        From what I can tell, the SoftwareSettingsWindow is unable to receive key combinations since it is able to detect me pressing the control key.

        The libraries called are the same, the init is the same.
        I do not think this issue is related to my PC since we tried it on some other computers and the problem was still present.

        Regards,
        FV

        SGaistS 1 Reply Last reply
        0
        • F fvez_demtroys

          Hi @SGaist,

          I am really not sure, from what I can tell, the usage is identical.
          Both windows are based on QMainWindow.

          If it was something about keyboard focus, wouldn't the problematic window catch nothing at all?
          From what I can tell, the SoftwareSettingsWindow is unable to receive key combinations since it is able to detect me pressing the control key.

          The libraries called are the same, the init is the same.
          I do not think this issue is related to my PC since we tried it on some other computers and the problem was still present.

          Regards,
          FV

          SGaistS Offline
          SGaistS Offline
          SGaist
          Lifetime Qt Champion
          wrote on last edited by
          #4

          While it's not forbidden it's pretty unusual to have several QMainWindow based widgets in an application. Is there any reason for that ?

          How are you showing SoftwareSettingsWindow ?

          On a side note, did you consider using a QAction for that purpose ?

          Interested in AI ? www.idiap.ch
          Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

          1 Reply Last reply
          1
          • F Offline
            F Offline
            fvez_demtroys
            wrote on last edited by
            #5

            Hi @SGaist,

            I use the QMainWindow since I like to have an independent status bar for my sub-windows.
            This could very well not be the correct approach.

            I use a QAction for showing the window, yes.
            I invoke the "show" function. It was modified slightly to fit our needs.

            def show(self):
                """
                Override the show method to allow for the window to be centered on the main window
                """
                self.main.windowSwitcher.addWindow(self)
                geo = self.frameGeometry()
                geo.moveCenter(self.main.geometry().center())
                geo.moveTop(self.main.geometry().top())
                self.move(geo.topLeft())
                super().show()
            

            I got the go ahead from my boss to put some more time into this.
            I will write an example app that has the issue and I'll link it here.

            I will make sure to tag you when this is done, thanks in advance for the help!

            SGaistS 1 Reply Last reply
            0
            • F fvez_demtroys

              Hi @SGaist,

              I use the QMainWindow since I like to have an independent status bar for my sub-windows.
              This could very well not be the correct approach.

              I use a QAction for showing the window, yes.
              I invoke the "show" function. It was modified slightly to fit our needs.

              def show(self):
                  """
                  Override the show method to allow for the window to be centered on the main window
                  """
                  self.main.windowSwitcher.addWindow(self)
                  geo = self.frameGeometry()
                  geo.moveCenter(self.main.geometry().center())
                  geo.moveTop(self.main.geometry().top())
                  self.move(geo.topLeft())
                  super().show()
              

              I got the go ahead from my boss to put some more time into this.
              I will write an example app that has the issue and I'll link it here.

              I will make sure to tag you when this is done, thanks in advance for the help!

              SGaistS Offline
              SGaistS Offline
              SGaist
              Lifetime Qt Champion
              wrote on last edited by
              #6

              I meant: did you consider using a QAction for calling close ?

              By the way, you can use QKeySequence::Close for that action.

              Interested in AI ? www.idiap.ch
              Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

              1 Reply Last reply
              0
              • F Offline
                F Offline
                fvez_demtroys
                wrote on last edited by
                #7

                Hi @SGaist,

                I'll try using the built in QAction for that.
                This was used as an example but we have more custom key combinations we would like to enable which would still require this to be working correctly.

                What I find strange is that I have around 10 additional windows that can be shown, this issue is only present on 4 of them. From what I can tell, there is no difference in how the classes are written, shown, etc.

                SGaistS 1 Reply Last reply
                0
                • F fvez_demtroys

                  Hi @SGaist,

                  I'll try using the built in QAction for that.
                  This was used as an example but we have more custom key combinations we would like to enable which would still require this to be working correctly.

                  What I find strange is that I have around 10 additional windows that can be shown, this issue is only present on 4 of them. From what I can tell, there is no difference in how the classes are written, shown, etc.

                  SGaistS Offline
                  SGaistS Offline
                  SGaist
                  Lifetime Qt Champion
                  wrote on last edited by
                  #8

                  @fvez_demtroys that's strange indeed. Rather than re-implementing the keyPressEvent on all your widgets, did you consider using an eventFilter ? That way you would have a central handler and it might also be easier to find out why these 4 widgets are doing something non standard.

                  Interested in AI ? www.idiap.ch
                  Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                  1 Reply Last reply
                  0
                  • F Offline
                    F Offline
                    fvez_demtroys
                    wrote on last edited by
                    #9

                    Hi @SGaist,

                    I did try using an eventFilter when I started working on these features. This was the best/cleanest approach to get the different key combinations for each individual windows.

                    We have a large quantity of custom keyboard shortcuts since the app is quite big, when we had a general eventFilter, it became too big and was a hassle to edit and use. There were way too many different conditions.

                    I do not think I can upload a zip file containing the code to run my example so I will post them as code snippets here.

                    There is a main file, a UI file, a MenuBar file, a DataConverterWindow file, and a StickerPrintingWindow file.

                    The ctrl + w and ctrl + m shortcuts work with the StickerPrintingWindow but do not work with the DataConverterWindow.

                    To show the windows, click on the corresponding tools menu action.

                    main.py

                    import getopt
                    import os
                    import platform
                    import sys
                    
                    from PyQt5 import QtCore
                    from PyQt5.QtCore import QSettings, QProcess
                    from PyQt5.QtGui import *
                    from PyQt5.QtWidgets import *
                    
                    from UI import Ui_mainWindow
                    
                    
                    class App(QMainWindow):
                        def __init__(self):
                            super(App, self).__init__()
                            self.osName = platform.system()
                    
                            self.settings = QSettings('Demtroys', 'Test App')
                    
                            self.mainWindow = Ui_mainWindow(self)
                            self.initMainWindow()
                    
                            self.initKeyPressEventHandlers()
                            self.initSettings()
                    
                        def initMainWindow(self):
                            self.mainWindow.setupUI(self)
                            self.setWindowTitle('Demtroys Test App for Sharing Purposes')
                            # mainWindow settings
                            self.blockSignals(True)
                            self.mainWindow.setSettings(self.settings)
                            self.blockSignals(False)
                    
                        def keyPressEvent(self, event):
                            if event.modifiers() & QtCore.Qt.ControlModifier:
                                if event.key() == QtCore.Qt.Key_Q:
                                    if self.osName == 'Windows':
                                        self.close()
                                        app.quit()
                                        return
                                if event.key() == QtCore.Qt.Key_W:
                                    self.close()
                                    return
                                if event.key() == QtCore.Qt.Key_M:
                                    self.showMinimized()
                                    return
                            super(App, self).keyPressEvent(event)
                    
                        def initSettings(self, settings=None):
                            """
                            Initialize the settings of the application on startup or on import
                            On OSX this file is located in /Users/fvez/Library/Preferences/com.demtroys.Device Configurator.plist
                            On Windows this file is located in
                            """
                            if settings is None and self.settings is None:
                                self.settings = QSettings('Demtroys', 'Test App')
                            elif settings is not None:
                                self.settings = settings
                            try:
                                self.blockSignals(True)
                                # Set settings
                                # mainWindow settings are set in initMainWindow
                                self.blockSignals(False)
                    
                            except Exception as e:
                                print(str(e))
                                pass
                    
                        def getSettings(self, settings=None):
                            """
                            Get the settings of the application on shutdown or on export
                            """
                            if settings is None and self.settings is None:
                                self.settings = QSettings('Demtroys', 'Test App')
                            elif settings is not None:
                                self.settings = settings
                            # mainWindow settings
                            self.mainWindow.getSettings(self.settings)
                    
                        def closeEvent(self, event):
                            """
                            Called when the application is closed
                            Gets the settings
                            Closes any open processes and the logger
                            Close the application
                            :param event: The close event
                            """
                            # Get settings
                            self.getSettings()
                    
                            super(App, self).closeEvent(event)
                    
                            if self.osName == 'Windows' and event.spontaneous():
                                app.quit()
                    
                    
                    if __name__ == "__main__":
                        arguments = list(sys.argv)
                        production = True
                        if len(arguments) > 1:
                            opts, args = getopt.getopt(arguments[1:], 'd', ['debug'])
                            for opt in opts:
                                if opt[0] in ('-d', '--debug'):
                                    production = False
                        app = QApplication(sys.argv)
                        # app = QApplication(sys.argv)
                        ex = App()
                        # apply_stylesheet(app, theme='dark_teal.xml')
                        sys.exit(app.exec_())
                    
                    

                    UI.py

                    # -*- coding: utf-8 -*-
                    import sys
                    
                    from PyQt5 import QtCore
                    from PyQt5.QtCore import *
                    from PyQt5.QtWidgets import *
                    
                    from Scripts.TestApp.DataConverterWindow import DataConverterWindow
                    from Scripts.TestApp.MenuBar import MenuBar
                    from Scripts.TestApp.StickerPrintingWindow import StickerPrintingWindow
                    
                    
                    class Ui_mainWindow(QMainWindow):
                        """
                        The main window class for the application
                        """
                        def __init__(self, main):
                            super(Ui_mainWindow, self).__init__()
                            self.main = main
                            self.osName = self.main.osName
                    
                        def setupUI(self, mainWindow):
                            """
                            Setup the UI for the main window
                            :param mainWindow: The main window object
                            """
                            if not mainWindow.objectName():
                                mainWindow.setObjectName(u'mainWindow')
                            self.initCentral(mainWindow)
                            self.initTabWidget()
                            self.initAdditionalWindows()
                            self.initMenuBar(mainWindow)
                            self.initStatusBar(mainWindow)
                    
                            mainWindow.setCentralWidget(self.centralWidget)
                            self.retranslateUi(mainWindow)
                    
                            QMetaObject.connectSlotsByName(mainWindow)
                    
                        def initCentral(self, mainWindow):
                            """
                            Init the central widget for the main window
                            :param mainWindow: The main window object
                            """
                            self.centralWidget = QWidget(mainWindow)
                            self.centralWidget.setObjectName(u'centralWidget')
                            self.baseGridLayout = QGridLayout(self.centralWidget)
                            self.baseGridLayout.setObjectName(u'baseGridLayout')
                    
                        def initTabWidget(self):
                            """
                            Init the tab widget for the main window
                            """
                            self.tabWidget = QTabWidget(self.centralWidget)
                            self.tabWidget.setObjectName(u'tabWidget')
                            self.tabWidget.setAutoFillBackground(False)
                            self.tabWidget.setTabPosition(QTabWidget.North)
                            self.tabWidget.setTabShape(QTabWidget.Rounded)
                            self.tabWidget.setMovable(False)
                            self.tabWidget.setCurrentIndex(0)
                            self.baseGridLayout.addWidget(self.tabWidget, 0, 0, 1, 1)
                    
                        def initAdditionalWindows(self):
                            """
                            Init the additional windows
                            """
                            self.dataConverterWindow = DataConverterWindow(self.main, self)
                            self.stickerPrintingWindow = StickerPrintingWindow(self.main, self)
                    
                        def initMenuBar(self, mainWindow):
                            """
                            Init the menu bar
                            :param mainWindow: The main window object
                            """
                            self.menuBar = MenuBar(main=self.main, mainWindow=self, parent=mainWindow)
                            self.menuBar.setObjectName(u'menuBar')
                    
                        def initStatusBar(self, mainWindow):
                            """
                            Init the status bar
                            :param mainWindow: The main window object
                            """
                            self.statusBar = QStatusBar(mainWindow)
                            self.statusBar.setObjectName(u'statusbar')
                            mainWindow.setStatusBar(self.statusBar)
                    
                        def getSettings(self, settings):
                            """
                            Get the settings on shutdown or on export
                            :param settings: The settings object
                            """
                            # mainWindow settings
                            settings.beginGroup('mainWindow')
                            settings.setValue('isMaximized', self.main.isMaximized())
                            settings.setValue('isFullScreen', self.main.isFullScreen())
                            if self.main.isMaximized() or self.main.isFullScreen():
                                settings.setValue('windowPosition', QPoint(self.main.normalGeometry().x(), self.main.normalGeometry().y()))
                                settings.setValue('windowSize', self.main.normalGeometry().size())
                            else:
                                settings.setValue('windowPosition', self.main.pos())
                                settings.setValue('windowSize', self.main.size())
                            settings.endGroup()
                    
                            # StickerPrintingWindow settings
                            self.stickerPrintingWindow.getSettings(settings)
                    
                        def setSettings(self, settings):
                            """
                            Set the settings on startup or on import
                            :param settings: The settings object
                            """
                            # mainWindow settings
                            # .plist : QPoint | .ini : QPoint
                            if settings.value('mainWindow/windowPosition') is not None:
                                self.main.move(settings.value('mainWindow/windowPosition'))
                            else:
                                self.main.move(QPoint(0, 0))
                            # .plist : QSize | .ini : QSize
                            if settings.value('mainWindow/windowSize') is not None:
                                self.main.resize(settings.value('mainWindow/windowSize'))
                            else:
                                self.main.resize(QSize(1200, 800))
                    
                            showNormalWindow = True
                            if settings.value('mainWindow/isMaximized') is not None:
                                if settings.value('mainWindow/isMaximized') == 'true':
                                    self.main.showMaximized()
                                    showNormalWindow = False
                            if settings.value('mainWindow/isFullScreen') is not None:
                                if settings.value('mainWindow/isFullScreen') == 'true':
                                    self.main.showFullScreen()
                                    showNormalWindow = False
                            if showNormalWindow:
                                self.main.showNormal()
                    
                            # StickerPrintingWindow settings
                            self.stickerPrintingWindow.setSettings(settings)
                    
                    

                    MenuBar.py

                    from PyQt5 import QtCore
                    from PyQt5.QtCore import QRect, QCoreApplication
                    from PyQt5.QtWidgets import QAction, QMenuBar, QMenu, QWidget
                    
                    
                    class MenuBar(QMenuBar):
                        """
                        The MenuBar class for the main window
                        """
                        def __init__(self, main, mainWindow, parent):
                            super().__init__()
                            self.main = main
                            self.mainWindow = mainWindow
                            self.parent = parent
                    
                            # self.initMenuActions(parent)
                            self.initMenuBar(parent)
                    
                            self.initConnections()
                    
                        def initConnections(self):
                            """
                            Init connections for the QMenuBar
                            """
                            # Actions
                            self.action_stickerPrintingWindow.triggered.connect(self.mainWindow.stickerPrintingWindow.show)
                            self.action_dataConverterWindow.triggered.connect(self.mainWindow.dataConverterWindow.show)
                    
                        def initMenuBar(self, mainWindow):
                            """
                            Initialize the menu bar
                            :param mainWindow: The main window
                            """
                            mainWindow.setMenuBar(self)
                            self.initMenusAndActions()
                    
                        def initMenusAndActions(self):
                            """
                            Initialize the menus and actions
                            """
                            # Menu Actions
                            self.menuTools = self.addMenu('Tools')
                    
                            # Tools Menu Actions
                            self.action_stickerPrintingWindow = self.menuTools.addAction('Sticker Printing')
                            self.action_stickerPrintingWindow.setCheckable(False)
                            self.action_dataConverterWindow = self.menuTools.addAction('Data Converter')
                            self.action_dataConverterWindow.setCheckable(False)
                    
                    

                    DataConverterWindow.py

                    import copy
                    
                    from PyQt5 import QtCore
                    from PyQt5.QtCore import Qt, QTimer, QCoreApplication, pyqtSignal
                    from PyQt5.QtWidgets import QGridLayout, QStatusBar, QMainWindow, QGroupBox, QPushButton, QVBoxLayout, \
                        QComboBox, QSpinBox, QLineEdit
                    
                    
                    class DataConverterWindow(QMainWindow):
                        def __init__(self, main, mainWindow):
                            super().__init__()
                            self.setFixedSize(440, 125)
                            self.setWindowFlags(Qt.WindowStaysOnTopHint)  # Discuss if this is what we want
                            self.setWindowTitle('Data Converter')
                            self.main = main
                            self.mainWindow = mainWindow
                    
                            self.initUI()
                            self.initStatusBar()
                            self.setCentralWidget(self.groupBox_dataConverter)
                    
                        def initConnections(self):
                            """
                            Initialize the connections
                            """
                            self.pushButton_convert.clicked.connect(self.convert)
                    
                        def keyPressEvent(self, event):
                            """
                            Override the keyPressEvent method to allow for the window to be closed with Ctrl+W and minimized with Ctrl+M
                            Also links the Enter key to the convert button
                            :param event: The key press event
                            """
                            print('DataConverterWindow keyPressEvent')
                            if event.modifiers() & QtCore.Qt.ControlModifier:
                                print(event.key())
                                if event.key() == QtCore.Qt.Key_W:
                                    self.close()
                                    return
                                if event.key() == QtCore.Qt.Key_M:
                                    self.showMinimized()
                                    return
                            elif event.key() == QtCore.Qt.Key_Return:
                                self.pushButton_convert.animateClick()
                            super(DataConverterWindow, self).keyPressEvent(event)
                    
                        def setVisible(self, visible: bool):
                            """
                            Override the setVisible method to allow for the window to be centered on the main window
                            :param visible: Whether the window should be visible or not
                            """
                            if visible:
                                geo = self.frameGeometry()
                                geo.moveCenter(self.main.geometry().center())
                                geo.moveTop(self.main.geometry().top())
                                self.move(geo.topLeft())
                            super().setVisible(visible)
                    
                        def show(self):
                            """
                            Override the show method to allow for the window to be centered on the main window
                            """
                            geo = self.frameGeometry()
                            geo.moveCenter(self.main.geometry().center())
                            geo.moveTop(self.main.geometry().top())
                            self.move(geo.topLeft())
                            super().show()
                    
                        def hide(self):
                            """
                            Hide the window
                            """
                            super().hide()
                    
                        def initStatusBar(self):
                            """
                            Initialize the status bar
                            """
                            self.statusBar_dataConverterWindow = QStatusBar(self)
                            self.statusBar_dataConverterWindow.setObjectName(u'statusBar_dataConverterWindow')
                            self.setStatusBar(self.statusBar_dataConverterWindow)
                    
                        def initUI(self):
                            """
                            Initialize the UI
                            """
                            self.groupBox_dataConverter = QGroupBox(self)
                            self.groupBox_dataConverter.setObjectName(u'groupBox_dataConverter')
                            self.groupBox_dataConverter.setFlat(True)
                            self.gridLayout_dataConverter = QGridLayout()
                            self.gridLayout_dataConverter.setObjectName(u'gridLayout_dataConverter')
                            self.gridLayout_dataConverter.setContentsMargins(10, 10, 10, 10)
                            self.gridLayout_dataConverter.setSpacing(0)
                    
                            self.comboBox = QComboBox(self.groupBox_dataConverter)
                            self.comboBox.setObjectName(u'comboBox')
                            self.comboBox.addItems(['placeholder1', 'placeholder2', 'placeholder3', 'placeholder4', 'placeholder5'])
                            self.gridLayout_dataConverter.addWidget(self.comboBox, 0, 0, 1, 2)
                    
                            self.spinBox = QSpinBox(self.groupBox_dataConverter)
                            self.spinBox.setObjectName(u'spinBox')
                            self.spinBox.setMinimum(1)
                            self.spinBox.setMaximum(64)
                            self.gridLayout_dataConverter.addWidget(self.spinBox, 0, 2, 1, 2)
                    
                            self.lineEdit = QLineEdit(self.groupBox_dataConverter)
                            self.lineEdit.setObjectName(u'lineEdit')
                            self.lineEdit.setPlaceholderText('LineEdit')
                            self.gridLayout_dataConverter.addWidget(self.lineEdit, 0, 4, 1, 2)
                    
                            self.pushButton_convert = QPushButton(self.groupBox_dataConverter)
                            self.pushButton_convert.setDefault(True)
                            self.pushButton_convert.setObjectName(u'pushButton_convert')
                            self.pushButton_convert.setText('Convert')
                            self.gridLayout_dataConverter.addWidget(self.pushButton_convert, 1, 5, 1, 1)
                    
                            self.groupBox_dataConverter.setLayout(self.gridLayout_dataConverter)
                    
                        def convert(self):
                            """
                            Convert
                            """
                            pass
                    
                        def retranslate(self):
                            """
                            Translate the window
                            """
                            pass
                    
                        def getSettings(self, settings):
                            """
                            Get the settings on shutdown or on export
                            :param settings: The settings object
                            """
                            settings.beginGroup('dataConverterWindow')
                            settings.endGroup()
                    
                        def setSettings(self, settings):
                            """
                            Set the settings on startup or on import
                            :param settings: The settings object
                            """
                            pass
                    
                    

                    StickerPrintingWindow.py

                    import platform
                    
                    from PyQt5 import QtGui, QtCore
                    from PyQt5.QtGui import QRegExpValidator
                    from PyQt5.QtCore import QRegExp, QCoreApplication, Qt, pyqtSignal
                    from PyQt5.QtWidgets import QGridLayout, QStatusBar, QMainWindow, QGroupBox, QPushButton, QLineEdit, QComboBox, QVBoxLayout, QSpinBox, QSizePolicy, \
                        QDateTimeEdit, QFrame, QScrollArea, QHBoxLayout, QWidget, QSpacerItem
                    
                    
                    class StickerPrintingWindow(QMainWindow):
                        def __init__(self, main, mainWindow):
                            super().__init__()
                            self.setFixedWidth(525)
                            self.setMinimumHeight(150)
                            self.main = main
                            self.mainWindow = mainWindow
                    
                            self.initUI()
                            self.initStatusBar()
                            self.setCentralWidget(self.groupBox_StickerPrintingConfigs)
                    
                        def keyPressEvent(self, event):
                            """
                            Override the keyPressEvent method to allow for the window to be closed with Ctrl+W and minimized with Ctrl+M
                            Also links the Enter key to the print button
                            :param event: The key press event
                            """
                            print('StickerPrintingWindow keyPressEvent')
                            if event.modifiers() & QtCore.Qt.ControlModifier:
                                print(event.key())
                                if event.key() == QtCore.Qt.Key_W:
                                    self.close()
                                    return
                                if event.key() == QtCore.Qt.Key_M:
                                    self.showMinimized()
                                    return
                            elif event.key() == QtCore.Qt.Key_Return:
                                self.pushButton_print.animateClick()
                            super(StickerPrintingWindow, self).keyPressEvent(event)
                    
                        def setVisible(self, visible: bool):
                            """
                            Override the setVisible method to allow for the window to be centered on the main window
                            :param visible: Indicates whether the window should be visible or not
                            """
                            if visible:
                                geo = self.frameGeometry()
                                geo.moveCenter(self.main.geometry().center())
                                geo.moveTop(self.main.geometry().top())
                                self.move(geo.topLeft())
                                self.hideAllStickerPrintingConfigWidgets()
                            super().setVisible(visible)
                    
                        def show(self):
                            """
                            Override the show method to allow for the window to be centered on the main window
                            :return:
                            """
                            geo = self.frameGeometry()
                            geo.moveCenter(self.main.geometry().center())
                            geo.moveTop(self.main.geometry().top())
                            self.move(geo.topLeft())
                            self.hideAllStickerPrintingConfigWidgets()
                            super().show()
                    
                        def hide(self):
                            """
                            Hide the window
                            """
                            super().hide()
                    
                        def initConnections(self):
                            """
                            Init connections for the QMainWindow
                            """
                            self.pushButton_print.clicked.connect(self.print)
                            for i in range(0, 15):
                                self.StickerPrintingConfigWidgets[i].initConnections()
                    
                        def initStatusBar(self):
                            """
                            Init the status bar for the window
                            """
                            self.statusBar_renameSerialPortWindow = QStatusBar(self)
                            self.statusBar_renameSerialPortWindow.setObjectName(u'statusBar_renameSerialPortWindow')
                            self.setStatusBar(self.statusBar_renameSerialPortWindow)
                    
                        def initUI(self):
                            """
                            Init the UI
                            """
                            self.groupBox_StickerPrintingConfigs = QGroupBox(self)
                            self.groupBox_StickerPrintingConfigs.setObjectName(u'groupBox_StickerPrintingConfigs')
                            self.gridLayout_groupBox_StickerPrintingConfigs = QGridLayout(self.groupBox_StickerPrintingConfigs)
                            self.gridLayout_groupBox_StickerPrintingConfigs.setObjectName(u'gridLayout_groupBox_StickerPrintingConfigs')
                            self.gridLayout_groupBox_StickerPrintingConfigs.setSpacing(0)
                            self.gridLayout_groupBox_StickerPrintingConfigs.setContentsMargins(0, 0, 0, 0)
                    
                            self.initStickerGroupsScrollArea()
                            self.gridLayout_groupBox_StickerPrintingConfigs.addWidget(self.scrollArea_StickerPrintingConfig, 0, 0, 1, 6)
                    
                            self.pushButton_addStickerPrintingConfigWidget = QPushButton(self)
                            self.pushButton_addStickerPrintingConfigWidget.setObjectName(u'pushButton_addStickerPrintingConfigWidget')
                            self.pushButton_addStickerPrintingConfigWidget.setText('+')
                            self.pushButton_addStickerPrintingConfigWidget.pressed.connect(self.addStickerPrintingConfigWidget)
                            self.gridLayout_groupBox_StickerPrintingConfigs.addWidget(self.pushButton_addStickerPrintingConfigWidget, 2, 0, 1, 1)
                    
                            self.pushButton_removeStickerPrintingConfigWidget = QPushButton(self)
                            self.pushButton_removeStickerPrintingConfigWidget.setObjectName(u'pushButton_removeStickerPrintingConfigWidget')
                            self.pushButton_removeStickerPrintingConfigWidget.setText('-')
                            self.pushButton_removeStickerPrintingConfigWidget.pressed.connect(self.removeStickerPrintingConfigWidget)
                            self.pushButton_removeStickerPrintingConfigWidget.setEnabled(False)
                            self.gridLayout_groupBox_StickerPrintingConfigs.addWidget(self.pushButton_removeStickerPrintingConfigWidget, 2, 1, 1, 1)
                    
                            self.pushButton_print = QPushButton(self.groupBox_StickerPrintingConfigs)
                            self.pushButton_print.setObjectName(u'pushButton_print')
                            self.pushButton_print.setDefault(True)
                            self.gridLayout_groupBox_StickerPrintingConfigs.addWidget(self.pushButton_print, 2, 5, 1, 1)
                    
                        def initStickerGroupsScrollArea(self):
                            """
                            Initializes the Sticker Groups scroll area
                            """
                            self.scrollArea_StickerPrintingConfig = QScrollArea()
                            self.scrollArea_StickerPrintingConfig.setObjectName(u'scrollArea_StickerPrintingConfig')
                            self.scrollArea_StickerPrintingConfig.setWidgetResizable(True)
                            self.scrollArea_StickerPrintingConfig.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
                            self.scrollArea_StickerPrintingConfig.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
                            # self.scrollArea_StickerPrintingConfig.setStyleSheet('QScrollArea {background: transparent;}')
                            self.scrollArea_StickerPrintingConfig.setFrameShape(QFrame.NoFrame)
                    
                            self.groupBox_scrollArea_StickerPrintingConfig = QGroupBox()
                            self.groupBox_scrollArea_StickerPrintingConfig.setObjectName(u'groupBox_scrollArea_StickerPrintingConfig')
                    
                            self.verticalLayout_groupBox_scrollArea_StickerPrintingConfig = QVBoxLayout()
                            self.verticalLayout_groupBox_scrollArea_StickerPrintingConfig.\
                                setObjectName(u'verticalLayout_groupBox_scrollArea_StickerPrintingConfig')
                            margins = self.verticalLayout_groupBox_scrollArea_StickerPrintingConfig.getContentsMargins()
                            self.verticalLayout_groupBox_scrollArea_StickerPrintingConfig.setContentsMargins(margins[0], 0, margins[2], 0)
                            self.verticalLayout_groupBox_scrollArea_StickerPrintingConfig.setSpacing(5)
                    
                            self.StickerPrintingConfigWidgets = []
                            for i in range(0, 16):
                                self.StickerPrintingConfigWidget = StickerPrintingConfigWidget(self,
                                                                                                     self.verticalLayout_groupBox_scrollArea_StickerPrintingConfig)
                                self.StickerPrintingConfigWidgets.append(self.StickerPrintingConfigWidget)
                            self.hideAllStickerPrintingConfigWidgets()
                    
                            self.verticalSpacer_groupBox_scrollArea_StickerPrintingConfig = QSpacerItem(0, 100, QSizePolicy.Minimum, QSizePolicy.Expanding)
                            self.verticalLayout_groupBox_scrollArea_StickerPrintingConfig.\
                                addSpacerItem(self.verticalSpacer_groupBox_scrollArea_StickerPrintingConfig)
                    
                            self.groupBox_scrollArea_StickerPrintingConfig.setLayout(self.verticalLayout_groupBox_scrollArea_StickerPrintingConfig)
                            self.scrollArea_StickerPrintingConfig.setWidget(self.groupBox_scrollArea_StickerPrintingConfig)
                    
                        def addStickerPrintingConfigWidget(self):
                            """
                            Adds a CSA sticker printing config widget to the window
                            """
                            if self.activeStickerPrintingConfigWidgets < 16:
                                self.activeStickerPrintingConfigWidgets = self.activeStickerPrintingConfigWidgets + 1
                                for i in range(0, self.activeStickerPrintingConfigWidgets):
                                    self.StickerPrintingConfigWidgets[i].show()
                            if self.activeStickerPrintingConfigWidgets == 16:
                                self.pushButton_addStickerPrintingConfigWidget.setEnabled(False)
                            if not self.pushButton_removeStickerPrintingConfigWidget.isEnabled():
                                self.pushButton_removeStickerPrintingConfigWidget.setEnabled(True)
                    
                        def removeStickerPrintingConfigWidget(self):
                            """
                            Removes a CSA sticker printing config widget from the window
                            """
                            if self.activeStickerPrintingConfigWidgets > 1:
                                self.activeStickerPrintingConfigWidgets = self.activeStickerPrintingConfigWidgets - 1
                                self.StickerPrintingConfigWidgets[self.activeStickerPrintingConfigWidgets].clear()
                                self.StickerPrintingConfigWidgets[self.activeStickerPrintingConfigWidgets].hide()
                            if self.activeStickerPrintingConfigWidgets == 1:
                                self.pushButton_removeStickerPrintingConfigWidget.setEnabled(False)
                            if not self.pushButton_addStickerPrintingConfigWidget.isEnabled():
                                self.pushButton_addStickerPrintingConfigWidget.setEnabled(True)
                    
                        def hideAllStickerPrintingConfigWidgets(self):
                            """
                            Hides all CSA sticker printing config widgets
                            """
                            self.activeStickerPrintingConfigWidgets = 1
                            for i in range(1, 16):
                                self.StickerPrintingConfigWidgets[i].hide()
                    
                        def clearAllStickerFields(self):
                            """
                            Clears all CSA sticker printing config widgets
                            """
                            for i in range(0, 16):
                                self.StickerPrintingConfigWidgets[i].clear()
                    
                        def retranslate(self):
                            """
                            Retranslate the window
                            """
                            pass
                    
                        def getSettings(self, settings):
                            """
                            This function is used to get the settings on shutdown or on export
                            :param settings: The settings object
                            """
                            settings.beginGroup('StickerPrintingWindow')
                            settings.setValue('windowSize', self.size())
                            settings.setValue('windowPosition', self.pos())
                            settings.endGroup()  # StickerPrintingWindow
                    
                        def setSettings(self, settings):
                            """
                            This function is used to set the settings on startup or on import
                            :param settings: The settings object
                            """
                            # StickerPrintingWindow settings
                            # .plist : QSize | .ini : QSize
                            if settings.value('StickerPrintingWindow/windowSize') is not None:
                                self.resize(settings.value('StickerPrintingWindow/windowSize'))
                            # .plist : QPoint | .ini : QPoint
                            if settings.value('StickerPrintingWindow/windowPosition') is not None:
                                self.move(settings.value('StickerPrintingWindow/windowPosition'))
                    
                    
                    class StickerPrintingConfigWidget(QWidget):
                        """
                        Individual CSA sticker printing configuration widget
                        This is repeated as many times as needed in the CSA sticker printing configuration window (max 16)
                        """
                        def __init__(self, parent=None, layout=None):
                            super(QWidget, self).__init__(parent)
                            self.StickerPrintingConfig = parent
                            self.layout = layout
                    
                            self.groupBox_StickerPrintingConfig = QGroupBox(self)
                            self.groupBox_StickerPrintingConfig.setObjectName(u'groupBox_StickerPrintingConfig')
                            self.layout.addWidget(self.groupBox_StickerPrintingConfig)
                    
                            self.gridLayout_groupBox_StickerPrintingConfig = QGridLayout(self.groupBox_StickerPrintingConfig)
                            self.gridLayout_groupBox_StickerPrintingConfig.setObjectName(u'gridLayout_groupBox_StickerPrintingConfig')
                            self.gridLayout_groupBox_StickerPrintingConfig.setSpacing(0)
                    
                            self.comboBox1 = QComboBox(self.groupBox_StickerPrintingConfig)
                            self.comboBox1.setObjectName(u'comboBox1')
                            self.comboBox1.addItems(['placeholder1', 'placeholder2', 'placeholder3', 'placeholder4', 'placeholder5'])
                            self.gridLayout_groupBox_StickerPrintingConfig.addWidget(self.comboBox1, 0, 0, 1, 2)
                    
                            self.spinBox1 = QSpinBox(self.groupBox_StickerPrintingConfig)
                            self.spinBox1.setObjectName(u'spinBox1')
                            self.spinBox1.setMinimum(1)
                            self.spinBox1.setMaximum(9999)
                            self.gridLayout_groupBox_StickerPrintingConfig.addWidget(self.spinBox1, 1, 0, 1, 1)
                    
                            self.comboBox2 = QComboBox(self.groupBox_StickerPrintingConfig)
                            self.comboBox2.setObjectName(u'comboBox2')
                            self.comboBox2.addItems(['placeholder1', 'placeholder2', 'placeholder3', 'placeholder4', 'placeholder5'])
                            self.gridLayout_groupBox_StickerPrintingConfig.addWidget(self.comboBox2, 1, 1, 1, 1)
                    
                            self.lineEdit1 = QLineEdit(self.groupBox_StickerPrintingConfig)
                            self.lineEdit1.setObjectName(u'lineEdit1')
                            self.lineEdit1.setPlaceholderText('LineEdit')
                            self.gridLayout_groupBox_StickerPrintingConfig.addWidget(self.lineEdit1, 0, 2, 1, 2)
                    
                            self.lineEdit2 = QLineEdit(self.groupBox_StickerPrintingConfig)
                            self.lineEdit2.setObjectName(u'lineEdit2')
                            self.lineEdit2.setPlaceholderText('LineEdit')
                            self.gridLayout_groupBox_StickerPrintingConfig.addWidget(self.lineEdit2, 1, 2, 1, 2)
                    
                        def initConnections(self):
                            """
                            Initialize connections
                            """
                            pass
                    
                        def clear(self):
                            """
                            Clear all fields
                            """
                            self.comboBox1.setCurrentIndex(0)
                            self.spinBox1.setValue(1)
                            self.lineEdit1.clear()
                            self.lineEdit2.clear()
                    
                        def hide(self):
                            """
                            Hide the QWidget
                            """
                            self.groupBox_StickerPrintingConfig.hide()
                            super().hide()
                    
                        def show(self):
                            """
                            Show the QWidget
                            """
                            self.groupBox_StickerPrintingConfig.show()
                            super().show()
                    
                        def isVisible(self):
                            """
                            Check if the QWidget is visible
                            :return: True if visible, False otherwise
                            """
                            return self.groupBox_StickerPrintingConfig.isVisible()
                    
                    

                    I hope this will help you understand what the issue is, we really aren't sure why this isn't working as intended...

                    Thanks!
                    Best Regards,

                    FV

                    F 1 Reply Last reply
                    0
                    • F fvez_demtroys

                      Hi @SGaist,

                      I did try using an eventFilter when I started working on these features. This was the best/cleanest approach to get the different key combinations for each individual windows.

                      We have a large quantity of custom keyboard shortcuts since the app is quite big, when we had a general eventFilter, it became too big and was a hassle to edit and use. There were way too many different conditions.

                      I do not think I can upload a zip file containing the code to run my example so I will post them as code snippets here.

                      There is a main file, a UI file, a MenuBar file, a DataConverterWindow file, and a StickerPrintingWindow file.

                      The ctrl + w and ctrl + m shortcuts work with the StickerPrintingWindow but do not work with the DataConverterWindow.

                      To show the windows, click on the corresponding tools menu action.

                      main.py

                      import getopt
                      import os
                      import platform
                      import sys
                      
                      from PyQt5 import QtCore
                      from PyQt5.QtCore import QSettings, QProcess
                      from PyQt5.QtGui import *
                      from PyQt5.QtWidgets import *
                      
                      from UI import Ui_mainWindow
                      
                      
                      class App(QMainWindow):
                          def __init__(self):
                              super(App, self).__init__()
                              self.osName = platform.system()
                      
                              self.settings = QSettings('Demtroys', 'Test App')
                      
                              self.mainWindow = Ui_mainWindow(self)
                              self.initMainWindow()
                      
                              self.initKeyPressEventHandlers()
                              self.initSettings()
                      
                          def initMainWindow(self):
                              self.mainWindow.setupUI(self)
                              self.setWindowTitle('Demtroys Test App for Sharing Purposes')
                              # mainWindow settings
                              self.blockSignals(True)
                              self.mainWindow.setSettings(self.settings)
                              self.blockSignals(False)
                      
                          def keyPressEvent(self, event):
                              if event.modifiers() & QtCore.Qt.ControlModifier:
                                  if event.key() == QtCore.Qt.Key_Q:
                                      if self.osName == 'Windows':
                                          self.close()
                                          app.quit()
                                          return
                                  if event.key() == QtCore.Qt.Key_W:
                                      self.close()
                                      return
                                  if event.key() == QtCore.Qt.Key_M:
                                      self.showMinimized()
                                      return
                              super(App, self).keyPressEvent(event)
                      
                          def initSettings(self, settings=None):
                              """
                              Initialize the settings of the application on startup or on import
                              On OSX this file is located in /Users/fvez/Library/Preferences/com.demtroys.Device Configurator.plist
                              On Windows this file is located in
                              """
                              if settings is None and self.settings is None:
                                  self.settings = QSettings('Demtroys', 'Test App')
                              elif settings is not None:
                                  self.settings = settings
                              try:
                                  self.blockSignals(True)
                                  # Set settings
                                  # mainWindow settings are set in initMainWindow
                                  self.blockSignals(False)
                      
                              except Exception as e:
                                  print(str(e))
                                  pass
                      
                          def getSettings(self, settings=None):
                              """
                              Get the settings of the application on shutdown or on export
                              """
                              if settings is None and self.settings is None:
                                  self.settings = QSettings('Demtroys', 'Test App')
                              elif settings is not None:
                                  self.settings = settings
                              # mainWindow settings
                              self.mainWindow.getSettings(self.settings)
                      
                          def closeEvent(self, event):
                              """
                              Called when the application is closed
                              Gets the settings
                              Closes any open processes and the logger
                              Close the application
                              :param event: The close event
                              """
                              # Get settings
                              self.getSettings()
                      
                              super(App, self).closeEvent(event)
                      
                              if self.osName == 'Windows' and event.spontaneous():
                                  app.quit()
                      
                      
                      if __name__ == "__main__":
                          arguments = list(sys.argv)
                          production = True
                          if len(arguments) > 1:
                              opts, args = getopt.getopt(arguments[1:], 'd', ['debug'])
                              for opt in opts:
                                  if opt[0] in ('-d', '--debug'):
                                      production = False
                          app = QApplication(sys.argv)
                          # app = QApplication(sys.argv)
                          ex = App()
                          # apply_stylesheet(app, theme='dark_teal.xml')
                          sys.exit(app.exec_())
                      
                      

                      UI.py

                      # -*- coding: utf-8 -*-
                      import sys
                      
                      from PyQt5 import QtCore
                      from PyQt5.QtCore import *
                      from PyQt5.QtWidgets import *
                      
                      from Scripts.TestApp.DataConverterWindow import DataConverterWindow
                      from Scripts.TestApp.MenuBar import MenuBar
                      from Scripts.TestApp.StickerPrintingWindow import StickerPrintingWindow
                      
                      
                      class Ui_mainWindow(QMainWindow):
                          """
                          The main window class for the application
                          """
                          def __init__(self, main):
                              super(Ui_mainWindow, self).__init__()
                              self.main = main
                              self.osName = self.main.osName
                      
                          def setupUI(self, mainWindow):
                              """
                              Setup the UI for the main window
                              :param mainWindow: The main window object
                              """
                              if not mainWindow.objectName():
                                  mainWindow.setObjectName(u'mainWindow')
                              self.initCentral(mainWindow)
                              self.initTabWidget()
                              self.initAdditionalWindows()
                              self.initMenuBar(mainWindow)
                              self.initStatusBar(mainWindow)
                      
                              mainWindow.setCentralWidget(self.centralWidget)
                              self.retranslateUi(mainWindow)
                      
                              QMetaObject.connectSlotsByName(mainWindow)
                      
                          def initCentral(self, mainWindow):
                              """
                              Init the central widget for the main window
                              :param mainWindow: The main window object
                              """
                              self.centralWidget = QWidget(mainWindow)
                              self.centralWidget.setObjectName(u'centralWidget')
                              self.baseGridLayout = QGridLayout(self.centralWidget)
                              self.baseGridLayout.setObjectName(u'baseGridLayout')
                      
                          def initTabWidget(self):
                              """
                              Init the tab widget for the main window
                              """
                              self.tabWidget = QTabWidget(self.centralWidget)
                              self.tabWidget.setObjectName(u'tabWidget')
                              self.tabWidget.setAutoFillBackground(False)
                              self.tabWidget.setTabPosition(QTabWidget.North)
                              self.tabWidget.setTabShape(QTabWidget.Rounded)
                              self.tabWidget.setMovable(False)
                              self.tabWidget.setCurrentIndex(0)
                              self.baseGridLayout.addWidget(self.tabWidget, 0, 0, 1, 1)
                      
                          def initAdditionalWindows(self):
                              """
                              Init the additional windows
                              """
                              self.dataConverterWindow = DataConverterWindow(self.main, self)
                              self.stickerPrintingWindow = StickerPrintingWindow(self.main, self)
                      
                          def initMenuBar(self, mainWindow):
                              """
                              Init the menu bar
                              :param mainWindow: The main window object
                              """
                              self.menuBar = MenuBar(main=self.main, mainWindow=self, parent=mainWindow)
                              self.menuBar.setObjectName(u'menuBar')
                      
                          def initStatusBar(self, mainWindow):
                              """
                              Init the status bar
                              :param mainWindow: The main window object
                              """
                              self.statusBar = QStatusBar(mainWindow)
                              self.statusBar.setObjectName(u'statusbar')
                              mainWindow.setStatusBar(self.statusBar)
                      
                          def getSettings(self, settings):
                              """
                              Get the settings on shutdown or on export
                              :param settings: The settings object
                              """
                              # mainWindow settings
                              settings.beginGroup('mainWindow')
                              settings.setValue('isMaximized', self.main.isMaximized())
                              settings.setValue('isFullScreen', self.main.isFullScreen())
                              if self.main.isMaximized() or self.main.isFullScreen():
                                  settings.setValue('windowPosition', QPoint(self.main.normalGeometry().x(), self.main.normalGeometry().y()))
                                  settings.setValue('windowSize', self.main.normalGeometry().size())
                              else:
                                  settings.setValue('windowPosition', self.main.pos())
                                  settings.setValue('windowSize', self.main.size())
                              settings.endGroup()
                      
                              # StickerPrintingWindow settings
                              self.stickerPrintingWindow.getSettings(settings)
                      
                          def setSettings(self, settings):
                              """
                              Set the settings on startup or on import
                              :param settings: The settings object
                              """
                              # mainWindow settings
                              # .plist : QPoint | .ini : QPoint
                              if settings.value('mainWindow/windowPosition') is not None:
                                  self.main.move(settings.value('mainWindow/windowPosition'))
                              else:
                                  self.main.move(QPoint(0, 0))
                              # .plist : QSize | .ini : QSize
                              if settings.value('mainWindow/windowSize') is not None:
                                  self.main.resize(settings.value('mainWindow/windowSize'))
                              else:
                                  self.main.resize(QSize(1200, 800))
                      
                              showNormalWindow = True
                              if settings.value('mainWindow/isMaximized') is not None:
                                  if settings.value('mainWindow/isMaximized') == 'true':
                                      self.main.showMaximized()
                                      showNormalWindow = False
                              if settings.value('mainWindow/isFullScreen') is not None:
                                  if settings.value('mainWindow/isFullScreen') == 'true':
                                      self.main.showFullScreen()
                                      showNormalWindow = False
                              if showNormalWindow:
                                  self.main.showNormal()
                      
                              # StickerPrintingWindow settings
                              self.stickerPrintingWindow.setSettings(settings)
                      
                      

                      MenuBar.py

                      from PyQt5 import QtCore
                      from PyQt5.QtCore import QRect, QCoreApplication
                      from PyQt5.QtWidgets import QAction, QMenuBar, QMenu, QWidget
                      
                      
                      class MenuBar(QMenuBar):
                          """
                          The MenuBar class for the main window
                          """
                          def __init__(self, main, mainWindow, parent):
                              super().__init__()
                              self.main = main
                              self.mainWindow = mainWindow
                              self.parent = parent
                      
                              # self.initMenuActions(parent)
                              self.initMenuBar(parent)
                      
                              self.initConnections()
                      
                          def initConnections(self):
                              """
                              Init connections for the QMenuBar
                              """
                              # Actions
                              self.action_stickerPrintingWindow.triggered.connect(self.mainWindow.stickerPrintingWindow.show)
                              self.action_dataConverterWindow.triggered.connect(self.mainWindow.dataConverterWindow.show)
                      
                          def initMenuBar(self, mainWindow):
                              """
                              Initialize the menu bar
                              :param mainWindow: The main window
                              """
                              mainWindow.setMenuBar(self)
                              self.initMenusAndActions()
                      
                          def initMenusAndActions(self):
                              """
                              Initialize the menus and actions
                              """
                              # Menu Actions
                              self.menuTools = self.addMenu('Tools')
                      
                              # Tools Menu Actions
                              self.action_stickerPrintingWindow = self.menuTools.addAction('Sticker Printing')
                              self.action_stickerPrintingWindow.setCheckable(False)
                              self.action_dataConverterWindow = self.menuTools.addAction('Data Converter')
                              self.action_dataConverterWindow.setCheckable(False)
                      
                      

                      DataConverterWindow.py

                      import copy
                      
                      from PyQt5 import QtCore
                      from PyQt5.QtCore import Qt, QTimer, QCoreApplication, pyqtSignal
                      from PyQt5.QtWidgets import QGridLayout, QStatusBar, QMainWindow, QGroupBox, QPushButton, QVBoxLayout, \
                          QComboBox, QSpinBox, QLineEdit
                      
                      
                      class DataConverterWindow(QMainWindow):
                          def __init__(self, main, mainWindow):
                              super().__init__()
                              self.setFixedSize(440, 125)
                              self.setWindowFlags(Qt.WindowStaysOnTopHint)  # Discuss if this is what we want
                              self.setWindowTitle('Data Converter')
                              self.main = main
                              self.mainWindow = mainWindow
                      
                              self.initUI()
                              self.initStatusBar()
                              self.setCentralWidget(self.groupBox_dataConverter)
                      
                          def initConnections(self):
                              """
                              Initialize the connections
                              """
                              self.pushButton_convert.clicked.connect(self.convert)
                      
                          def keyPressEvent(self, event):
                              """
                              Override the keyPressEvent method to allow for the window to be closed with Ctrl+W and minimized with Ctrl+M
                              Also links the Enter key to the convert button
                              :param event: The key press event
                              """
                              print('DataConverterWindow keyPressEvent')
                              if event.modifiers() & QtCore.Qt.ControlModifier:
                                  print(event.key())
                                  if event.key() == QtCore.Qt.Key_W:
                                      self.close()
                                      return
                                  if event.key() == QtCore.Qt.Key_M:
                                      self.showMinimized()
                                      return
                              elif event.key() == QtCore.Qt.Key_Return:
                                  self.pushButton_convert.animateClick()
                              super(DataConverterWindow, self).keyPressEvent(event)
                      
                          def setVisible(self, visible: bool):
                              """
                              Override the setVisible method to allow for the window to be centered on the main window
                              :param visible: Whether the window should be visible or not
                              """
                              if visible:
                                  geo = self.frameGeometry()
                                  geo.moveCenter(self.main.geometry().center())
                                  geo.moveTop(self.main.geometry().top())
                                  self.move(geo.topLeft())
                              super().setVisible(visible)
                      
                          def show(self):
                              """
                              Override the show method to allow for the window to be centered on the main window
                              """
                              geo = self.frameGeometry()
                              geo.moveCenter(self.main.geometry().center())
                              geo.moveTop(self.main.geometry().top())
                              self.move(geo.topLeft())
                              super().show()
                      
                          def hide(self):
                              """
                              Hide the window
                              """
                              super().hide()
                      
                          def initStatusBar(self):
                              """
                              Initialize the status bar
                              """
                              self.statusBar_dataConverterWindow = QStatusBar(self)
                              self.statusBar_dataConverterWindow.setObjectName(u'statusBar_dataConverterWindow')
                              self.setStatusBar(self.statusBar_dataConverterWindow)
                      
                          def initUI(self):
                              """
                              Initialize the UI
                              """
                              self.groupBox_dataConverter = QGroupBox(self)
                              self.groupBox_dataConverter.setObjectName(u'groupBox_dataConverter')
                              self.groupBox_dataConverter.setFlat(True)
                              self.gridLayout_dataConverter = QGridLayout()
                              self.gridLayout_dataConverter.setObjectName(u'gridLayout_dataConverter')
                              self.gridLayout_dataConverter.setContentsMargins(10, 10, 10, 10)
                              self.gridLayout_dataConverter.setSpacing(0)
                      
                              self.comboBox = QComboBox(self.groupBox_dataConverter)
                              self.comboBox.setObjectName(u'comboBox')
                              self.comboBox.addItems(['placeholder1', 'placeholder2', 'placeholder3', 'placeholder4', 'placeholder5'])
                              self.gridLayout_dataConverter.addWidget(self.comboBox, 0, 0, 1, 2)
                      
                              self.spinBox = QSpinBox(self.groupBox_dataConverter)
                              self.spinBox.setObjectName(u'spinBox')
                              self.spinBox.setMinimum(1)
                              self.spinBox.setMaximum(64)
                              self.gridLayout_dataConverter.addWidget(self.spinBox, 0, 2, 1, 2)
                      
                              self.lineEdit = QLineEdit(self.groupBox_dataConverter)
                              self.lineEdit.setObjectName(u'lineEdit')
                              self.lineEdit.setPlaceholderText('LineEdit')
                              self.gridLayout_dataConverter.addWidget(self.lineEdit, 0, 4, 1, 2)
                      
                              self.pushButton_convert = QPushButton(self.groupBox_dataConverter)
                              self.pushButton_convert.setDefault(True)
                              self.pushButton_convert.setObjectName(u'pushButton_convert')
                              self.pushButton_convert.setText('Convert')
                              self.gridLayout_dataConverter.addWidget(self.pushButton_convert, 1, 5, 1, 1)
                      
                              self.groupBox_dataConverter.setLayout(self.gridLayout_dataConverter)
                      
                          def convert(self):
                              """
                              Convert
                              """
                              pass
                      
                          def retranslate(self):
                              """
                              Translate the window
                              """
                              pass
                      
                          def getSettings(self, settings):
                              """
                              Get the settings on shutdown or on export
                              :param settings: The settings object
                              """
                              settings.beginGroup('dataConverterWindow')
                              settings.endGroup()
                      
                          def setSettings(self, settings):
                              """
                              Set the settings on startup or on import
                              :param settings: The settings object
                              """
                              pass
                      
                      

                      StickerPrintingWindow.py

                      import platform
                      
                      from PyQt5 import QtGui, QtCore
                      from PyQt5.QtGui import QRegExpValidator
                      from PyQt5.QtCore import QRegExp, QCoreApplication, Qt, pyqtSignal
                      from PyQt5.QtWidgets import QGridLayout, QStatusBar, QMainWindow, QGroupBox, QPushButton, QLineEdit, QComboBox, QVBoxLayout, QSpinBox, QSizePolicy, \
                          QDateTimeEdit, QFrame, QScrollArea, QHBoxLayout, QWidget, QSpacerItem
                      
                      
                      class StickerPrintingWindow(QMainWindow):
                          def __init__(self, main, mainWindow):
                              super().__init__()
                              self.setFixedWidth(525)
                              self.setMinimumHeight(150)
                              self.main = main
                              self.mainWindow = mainWindow
                      
                              self.initUI()
                              self.initStatusBar()
                              self.setCentralWidget(self.groupBox_StickerPrintingConfigs)
                      
                          def keyPressEvent(self, event):
                              """
                              Override the keyPressEvent method to allow for the window to be closed with Ctrl+W and minimized with Ctrl+M
                              Also links the Enter key to the print button
                              :param event: The key press event
                              """
                              print('StickerPrintingWindow keyPressEvent')
                              if event.modifiers() & QtCore.Qt.ControlModifier:
                                  print(event.key())
                                  if event.key() == QtCore.Qt.Key_W:
                                      self.close()
                                      return
                                  if event.key() == QtCore.Qt.Key_M:
                                      self.showMinimized()
                                      return
                              elif event.key() == QtCore.Qt.Key_Return:
                                  self.pushButton_print.animateClick()
                              super(StickerPrintingWindow, self).keyPressEvent(event)
                      
                          def setVisible(self, visible: bool):
                              """
                              Override the setVisible method to allow for the window to be centered on the main window
                              :param visible: Indicates whether the window should be visible or not
                              """
                              if visible:
                                  geo = self.frameGeometry()
                                  geo.moveCenter(self.main.geometry().center())
                                  geo.moveTop(self.main.geometry().top())
                                  self.move(geo.topLeft())
                                  self.hideAllStickerPrintingConfigWidgets()
                              super().setVisible(visible)
                      
                          def show(self):
                              """
                              Override the show method to allow for the window to be centered on the main window
                              :return:
                              """
                              geo = self.frameGeometry()
                              geo.moveCenter(self.main.geometry().center())
                              geo.moveTop(self.main.geometry().top())
                              self.move(geo.topLeft())
                              self.hideAllStickerPrintingConfigWidgets()
                              super().show()
                      
                          def hide(self):
                              """
                              Hide the window
                              """
                              super().hide()
                      
                          def initConnections(self):
                              """
                              Init connections for the QMainWindow
                              """
                              self.pushButton_print.clicked.connect(self.print)
                              for i in range(0, 15):
                                  self.StickerPrintingConfigWidgets[i].initConnections()
                      
                          def initStatusBar(self):
                              """
                              Init the status bar for the window
                              """
                              self.statusBar_renameSerialPortWindow = QStatusBar(self)
                              self.statusBar_renameSerialPortWindow.setObjectName(u'statusBar_renameSerialPortWindow')
                              self.setStatusBar(self.statusBar_renameSerialPortWindow)
                      
                          def initUI(self):
                              """
                              Init the UI
                              """
                              self.groupBox_StickerPrintingConfigs = QGroupBox(self)
                              self.groupBox_StickerPrintingConfigs.setObjectName(u'groupBox_StickerPrintingConfigs')
                              self.gridLayout_groupBox_StickerPrintingConfigs = QGridLayout(self.groupBox_StickerPrintingConfigs)
                              self.gridLayout_groupBox_StickerPrintingConfigs.setObjectName(u'gridLayout_groupBox_StickerPrintingConfigs')
                              self.gridLayout_groupBox_StickerPrintingConfigs.setSpacing(0)
                              self.gridLayout_groupBox_StickerPrintingConfigs.setContentsMargins(0, 0, 0, 0)
                      
                              self.initStickerGroupsScrollArea()
                              self.gridLayout_groupBox_StickerPrintingConfigs.addWidget(self.scrollArea_StickerPrintingConfig, 0, 0, 1, 6)
                      
                              self.pushButton_addStickerPrintingConfigWidget = QPushButton(self)
                              self.pushButton_addStickerPrintingConfigWidget.setObjectName(u'pushButton_addStickerPrintingConfigWidget')
                              self.pushButton_addStickerPrintingConfigWidget.setText('+')
                              self.pushButton_addStickerPrintingConfigWidget.pressed.connect(self.addStickerPrintingConfigWidget)
                              self.gridLayout_groupBox_StickerPrintingConfigs.addWidget(self.pushButton_addStickerPrintingConfigWidget, 2, 0, 1, 1)
                      
                              self.pushButton_removeStickerPrintingConfigWidget = QPushButton(self)
                              self.pushButton_removeStickerPrintingConfigWidget.setObjectName(u'pushButton_removeStickerPrintingConfigWidget')
                              self.pushButton_removeStickerPrintingConfigWidget.setText('-')
                              self.pushButton_removeStickerPrintingConfigWidget.pressed.connect(self.removeStickerPrintingConfigWidget)
                              self.pushButton_removeStickerPrintingConfigWidget.setEnabled(False)
                              self.gridLayout_groupBox_StickerPrintingConfigs.addWidget(self.pushButton_removeStickerPrintingConfigWidget, 2, 1, 1, 1)
                      
                              self.pushButton_print = QPushButton(self.groupBox_StickerPrintingConfigs)
                              self.pushButton_print.setObjectName(u'pushButton_print')
                              self.pushButton_print.setDefault(True)
                              self.gridLayout_groupBox_StickerPrintingConfigs.addWidget(self.pushButton_print, 2, 5, 1, 1)
                      
                          def initStickerGroupsScrollArea(self):
                              """
                              Initializes the Sticker Groups scroll area
                              """
                              self.scrollArea_StickerPrintingConfig = QScrollArea()
                              self.scrollArea_StickerPrintingConfig.setObjectName(u'scrollArea_StickerPrintingConfig')
                              self.scrollArea_StickerPrintingConfig.setWidgetResizable(True)
                              self.scrollArea_StickerPrintingConfig.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
                              self.scrollArea_StickerPrintingConfig.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
                              # self.scrollArea_StickerPrintingConfig.setStyleSheet('QScrollArea {background: transparent;}')
                              self.scrollArea_StickerPrintingConfig.setFrameShape(QFrame.NoFrame)
                      
                              self.groupBox_scrollArea_StickerPrintingConfig = QGroupBox()
                              self.groupBox_scrollArea_StickerPrintingConfig.setObjectName(u'groupBox_scrollArea_StickerPrintingConfig')
                      
                              self.verticalLayout_groupBox_scrollArea_StickerPrintingConfig = QVBoxLayout()
                              self.verticalLayout_groupBox_scrollArea_StickerPrintingConfig.\
                                  setObjectName(u'verticalLayout_groupBox_scrollArea_StickerPrintingConfig')
                              margins = self.verticalLayout_groupBox_scrollArea_StickerPrintingConfig.getContentsMargins()
                              self.verticalLayout_groupBox_scrollArea_StickerPrintingConfig.setContentsMargins(margins[0], 0, margins[2], 0)
                              self.verticalLayout_groupBox_scrollArea_StickerPrintingConfig.setSpacing(5)
                      
                              self.StickerPrintingConfigWidgets = []
                              for i in range(0, 16):
                                  self.StickerPrintingConfigWidget = StickerPrintingConfigWidget(self,
                                                                                                       self.verticalLayout_groupBox_scrollArea_StickerPrintingConfig)
                                  self.StickerPrintingConfigWidgets.append(self.StickerPrintingConfigWidget)
                              self.hideAllStickerPrintingConfigWidgets()
                      
                              self.verticalSpacer_groupBox_scrollArea_StickerPrintingConfig = QSpacerItem(0, 100, QSizePolicy.Minimum, QSizePolicy.Expanding)
                              self.verticalLayout_groupBox_scrollArea_StickerPrintingConfig.\
                                  addSpacerItem(self.verticalSpacer_groupBox_scrollArea_StickerPrintingConfig)
                      
                              self.groupBox_scrollArea_StickerPrintingConfig.setLayout(self.verticalLayout_groupBox_scrollArea_StickerPrintingConfig)
                              self.scrollArea_StickerPrintingConfig.setWidget(self.groupBox_scrollArea_StickerPrintingConfig)
                      
                          def addStickerPrintingConfigWidget(self):
                              """
                              Adds a CSA sticker printing config widget to the window
                              """
                              if self.activeStickerPrintingConfigWidgets < 16:
                                  self.activeStickerPrintingConfigWidgets = self.activeStickerPrintingConfigWidgets + 1
                                  for i in range(0, self.activeStickerPrintingConfigWidgets):
                                      self.StickerPrintingConfigWidgets[i].show()
                              if self.activeStickerPrintingConfigWidgets == 16:
                                  self.pushButton_addStickerPrintingConfigWidget.setEnabled(False)
                              if not self.pushButton_removeStickerPrintingConfigWidget.isEnabled():
                                  self.pushButton_removeStickerPrintingConfigWidget.setEnabled(True)
                      
                          def removeStickerPrintingConfigWidget(self):
                              """
                              Removes a CSA sticker printing config widget from the window
                              """
                              if self.activeStickerPrintingConfigWidgets > 1:
                                  self.activeStickerPrintingConfigWidgets = self.activeStickerPrintingConfigWidgets - 1
                                  self.StickerPrintingConfigWidgets[self.activeStickerPrintingConfigWidgets].clear()
                                  self.StickerPrintingConfigWidgets[self.activeStickerPrintingConfigWidgets].hide()
                              if self.activeStickerPrintingConfigWidgets == 1:
                                  self.pushButton_removeStickerPrintingConfigWidget.setEnabled(False)
                              if not self.pushButton_addStickerPrintingConfigWidget.isEnabled():
                                  self.pushButton_addStickerPrintingConfigWidget.setEnabled(True)
                      
                          def hideAllStickerPrintingConfigWidgets(self):
                              """
                              Hides all CSA sticker printing config widgets
                              """
                              self.activeStickerPrintingConfigWidgets = 1
                              for i in range(1, 16):
                                  self.StickerPrintingConfigWidgets[i].hide()
                      
                          def clearAllStickerFields(self):
                              """
                              Clears all CSA sticker printing config widgets
                              """
                              for i in range(0, 16):
                                  self.StickerPrintingConfigWidgets[i].clear()
                      
                          def retranslate(self):
                              """
                              Retranslate the window
                              """
                              pass
                      
                          def getSettings(self, settings):
                              """
                              This function is used to get the settings on shutdown or on export
                              :param settings: The settings object
                              """
                              settings.beginGroup('StickerPrintingWindow')
                              settings.setValue('windowSize', self.size())
                              settings.setValue('windowPosition', self.pos())
                              settings.endGroup()  # StickerPrintingWindow
                      
                          def setSettings(self, settings):
                              """
                              This function is used to set the settings on startup or on import
                              :param settings: The settings object
                              """
                              # StickerPrintingWindow settings
                              # .plist : QSize | .ini : QSize
                              if settings.value('StickerPrintingWindow/windowSize') is not None:
                                  self.resize(settings.value('StickerPrintingWindow/windowSize'))
                              # .plist : QPoint | .ini : QPoint
                              if settings.value('StickerPrintingWindow/windowPosition') is not None:
                                  self.move(settings.value('StickerPrintingWindow/windowPosition'))
                      
                      
                      class StickerPrintingConfigWidget(QWidget):
                          """
                          Individual CSA sticker printing configuration widget
                          This is repeated as many times as needed in the CSA sticker printing configuration window (max 16)
                          """
                          def __init__(self, parent=None, layout=None):
                              super(QWidget, self).__init__(parent)
                              self.StickerPrintingConfig = parent
                              self.layout = layout
                      
                              self.groupBox_StickerPrintingConfig = QGroupBox(self)
                              self.groupBox_StickerPrintingConfig.setObjectName(u'groupBox_StickerPrintingConfig')
                              self.layout.addWidget(self.groupBox_StickerPrintingConfig)
                      
                              self.gridLayout_groupBox_StickerPrintingConfig = QGridLayout(self.groupBox_StickerPrintingConfig)
                              self.gridLayout_groupBox_StickerPrintingConfig.setObjectName(u'gridLayout_groupBox_StickerPrintingConfig')
                              self.gridLayout_groupBox_StickerPrintingConfig.setSpacing(0)
                      
                              self.comboBox1 = QComboBox(self.groupBox_StickerPrintingConfig)
                              self.comboBox1.setObjectName(u'comboBox1')
                              self.comboBox1.addItems(['placeholder1', 'placeholder2', 'placeholder3', 'placeholder4', 'placeholder5'])
                              self.gridLayout_groupBox_StickerPrintingConfig.addWidget(self.comboBox1, 0, 0, 1, 2)
                      
                              self.spinBox1 = QSpinBox(self.groupBox_StickerPrintingConfig)
                              self.spinBox1.setObjectName(u'spinBox1')
                              self.spinBox1.setMinimum(1)
                              self.spinBox1.setMaximum(9999)
                              self.gridLayout_groupBox_StickerPrintingConfig.addWidget(self.spinBox1, 1, 0, 1, 1)
                      
                              self.comboBox2 = QComboBox(self.groupBox_StickerPrintingConfig)
                              self.comboBox2.setObjectName(u'comboBox2')
                              self.comboBox2.addItems(['placeholder1', 'placeholder2', 'placeholder3', 'placeholder4', 'placeholder5'])
                              self.gridLayout_groupBox_StickerPrintingConfig.addWidget(self.comboBox2, 1, 1, 1, 1)
                      
                              self.lineEdit1 = QLineEdit(self.groupBox_StickerPrintingConfig)
                              self.lineEdit1.setObjectName(u'lineEdit1')
                              self.lineEdit1.setPlaceholderText('LineEdit')
                              self.gridLayout_groupBox_StickerPrintingConfig.addWidget(self.lineEdit1, 0, 2, 1, 2)
                      
                              self.lineEdit2 = QLineEdit(self.groupBox_StickerPrintingConfig)
                              self.lineEdit2.setObjectName(u'lineEdit2')
                              self.lineEdit2.setPlaceholderText('LineEdit')
                              self.gridLayout_groupBox_StickerPrintingConfig.addWidget(self.lineEdit2, 1, 2, 1, 2)
                      
                          def initConnections(self):
                              """
                              Initialize connections
                              """
                              pass
                      
                          def clear(self):
                              """
                              Clear all fields
                              """
                              self.comboBox1.setCurrentIndex(0)
                              self.spinBox1.setValue(1)
                              self.lineEdit1.clear()
                              self.lineEdit2.clear()
                      
                          def hide(self):
                              """
                              Hide the QWidget
                              """
                              self.groupBox_StickerPrintingConfig.hide()
                              super().hide()
                      
                          def show(self):
                              """
                              Show the QWidget
                              """
                              self.groupBox_StickerPrintingConfig.show()
                              super().show()
                      
                          def isVisible(self):
                              """
                              Check if the QWidget is visible
                              :return: True if visible, False otherwise
                              """
                              return self.groupBox_StickerPrintingConfig.isVisible()
                      
                      

                      I hope this will help you understand what the issue is, we really aren't sure why this isn't working as intended...

                      Thanks!
                      Best Regards,

                      FV

                      F Offline
                      F Offline
                      fvez_demtroys
                      wrote on last edited by
                      #10

                      @SGaist

                      I introduced a last minute error before pasting the code here, sorry about that.

                      Here are the main.py and UI.py files again with the fix.

                      main.py

                      import getopt
                      import os
                      import platform
                      import sys
                      
                      from PyQt5 import QtCore
                      from PyQt5.QtCore import QSettings, QProcess
                      from PyQt5.QtGui import *
                      from PyQt5.QtWidgets import *
                      
                      from UI import Ui_mainWindow
                      
                      
                      class App(QMainWindow):
                          def __init__(self):
                              super(App, self).__init__()
                              self.osName = platform.system()
                      
                              self.settings = QSettings('Demtroys', 'Test App')
                      
                              self.mainWindow = Ui_mainWindow(self)
                              self.initMainWindow()
                      
                              self.initSettings()
                      
                          def initMainWindow(self):
                              self.mainWindow.setupUI(self)
                              self.setWindowTitle('Demtroys Test App for Sharing Purposes')
                              # mainWindow settings
                              self.blockSignals(True)
                              self.mainWindow.setSettings(self.settings)
                              self.blockSignals(False)
                      
                          def keyPressEvent(self, event):
                              if event.modifiers() & QtCore.Qt.ControlModifier:
                                  if event.key() == QtCore.Qt.Key_Q:
                                      if self.osName == 'Windows':
                                          self.close()
                                          app.quit()
                                          return
                                  if event.key() == QtCore.Qt.Key_W:
                                      self.close()
                                      return
                                  if event.key() == QtCore.Qt.Key_M:
                                      self.showMinimized()
                                      return
                              super(App, self).keyPressEvent(event)
                      
                          def initSettings(self, settings=None):
                              """
                              Initialize the settings of the application on startup or on import
                              On OSX this file is located in /Users/fvez/Library/Preferences/com.demtroys.Device Configurator.plist
                              On Windows this file is located in
                              """
                              if settings is None and self.settings is None:
                                  self.settings = QSettings('Demtroys', 'Test App')
                              elif settings is not None:
                                  self.settings = settings
                              try:
                                  self.blockSignals(True)
                                  # Set settings
                                  # mainWindow settings are set in initMainWindow
                                  self.blockSignals(False)
                      
                              except Exception as e:
                                  print(str(e))
                                  pass
                      
                          def getSettings(self, settings=None):
                              """
                              Get the settings of the application on shutdown or on export
                              """
                              if settings is None and self.settings is None:
                                  self.settings = QSettings('Demtroys', 'Test App')
                              elif settings is not None:
                                  self.settings = settings
                              # mainWindow settings
                              self.mainWindow.getSettings(self.settings)
                      
                          def closeEvent(self, event):
                              """
                              Called when the application is closed
                              Gets the settings
                              Closes any open processes and the logger
                              Close the application
                              :param event: The close event
                              """
                              # Get settings
                              self.getSettings()
                      
                              super(App, self).closeEvent(event)
                      
                              if self.osName == 'Windows' and event.spontaneous():
                                  app.quit()
                      
                      
                      if __name__ == "__main__":
                          arguments = list(sys.argv)
                          production = True
                          if len(arguments) > 1:
                              opts, args = getopt.getopt(arguments[1:], 'd', ['debug'])
                              for opt in opts:
                                  if opt[0] in ('-d', '--debug'):
                                      production = False
                          app = QApplication(sys.argv)
                          # app = QApplication(sys.argv)
                          ex = App()
                          # apply_stylesheet(app, theme='dark_teal.xml')
                          sys.exit(app.exec_())
                      
                      

                      UI.py

                      # -*- coding: utf-8 -*-
                      import sys
                      
                      from PyQt5 import QtCore
                      from PyQt5.QtCore import *
                      from PyQt5.QtWidgets import *
                      
                      from Scripts.TestApp.DataConverterWindow import DataConverterWindow
                      from Scripts.TestApp.MenuBar import MenuBar
                      from Scripts.TestApp.StickerPrintingWindow import StickerPrintingWindow
                      
                      
                      class Ui_mainWindow(QMainWindow):
                          """
                          The main window class for the application
                          """
                          def __init__(self, main):
                              super(Ui_mainWindow, self).__init__()
                              self.main = main
                              self.osName = self.main.osName
                      
                          def setupUI(self, mainWindow):
                              """
                              Setup the UI for the main window
                              :param mainWindow: The main window object
                              """
                              if not mainWindow.objectName():
                                  mainWindow.setObjectName(u'mainWindow')
                              self.initCentral(mainWindow)
                              self.initTabWidget()
                              self.initAdditionalWindows()
                              self.initMenuBar(mainWindow)
                              self.initStatusBar(mainWindow)
                      
                              mainWindow.setCentralWidget(self.centralWidget)
                      
                              QMetaObject.connectSlotsByName(mainWindow)
                      
                          def initCentral(self, mainWindow):
                              """
                              Init the central widget for the main window
                              :param mainWindow: The main window object
                              """
                              self.centralWidget = QWidget(mainWindow)
                              self.centralWidget.setObjectName(u'centralWidget')
                              self.baseGridLayout = QGridLayout(self.centralWidget)
                              self.baseGridLayout.setObjectName(u'baseGridLayout')
                      
                          def initTabWidget(self):
                              """
                              Init the tab widget for the main window
                              """
                              self.tabWidget = QTabWidget(self.centralWidget)
                              self.tabWidget.setObjectName(u'tabWidget')
                              self.tabWidget.setAutoFillBackground(False)
                              self.tabWidget.setTabPosition(QTabWidget.North)
                              self.tabWidget.setTabShape(QTabWidget.Rounded)
                              self.tabWidget.setMovable(False)
                              self.tabWidget.setCurrentIndex(0)
                              self.baseGridLayout.addWidget(self.tabWidget, 0, 0, 1, 1)
                      
                          def initAdditionalWindows(self):
                              """
                              Init the additional windows
                              """
                              self.dataConverterWindow = DataConverterWindow(self.main, self)
                              self.stickerPrintingWindow = StickerPrintingWindow(self.main, self)
                      
                          def initMenuBar(self, mainWindow):
                              """
                              Init the menu bar
                              :param mainWindow: The main window object
                              """
                              self.menuBar = MenuBar(main=self.main, mainWindow=self, parent=mainWindow)
                              self.menuBar.setObjectName(u'menuBar')
                      
                          def initStatusBar(self, mainWindow):
                              """
                              Init the status bar
                              :param mainWindow: The main window object
                              """
                              self.statusBar = QStatusBar(mainWindow)
                              self.statusBar.setObjectName(u'statusbar')
                              mainWindow.setStatusBar(self.statusBar)
                      
                          def getSettings(self, settings):
                              """
                              Get the settings on shutdown or on export
                              :param settings: The settings object
                              """
                              # mainWindow settings
                              settings.beginGroup('mainWindow')
                              settings.setValue('isMaximized', self.main.isMaximized())
                              settings.setValue('isFullScreen', self.main.isFullScreen())
                              if self.main.isMaximized() or self.main.isFullScreen():
                                  settings.setValue('windowPosition', QPoint(self.main.normalGeometry().x(), self.main.normalGeometry().y()))
                                  settings.setValue('windowSize', self.main.normalGeometry().size())
                              else:
                                  settings.setValue('windowPosition', self.main.pos())
                                  settings.setValue('windowSize', self.main.size())
                              settings.endGroup()
                      
                              # StickerPrintingWindow settings
                              self.stickerPrintingWindow.getSettings(settings)
                      
                          def setSettings(self, settings):
                              """
                              Set the settings on startup or on import
                              :param settings: The settings object
                              """
                              # mainWindow settings
                              # .plist : QPoint | .ini : QPoint
                              if settings.value('mainWindow/windowPosition') is not None:
                                  self.main.move(settings.value('mainWindow/windowPosition'))
                              else:
                                  self.main.move(QPoint(0, 0))
                              # .plist : QSize | .ini : QSize
                              if settings.value('mainWindow/windowSize') is not None:
                                  self.main.resize(settings.value('mainWindow/windowSize'))
                              else:
                                  self.main.resize(QSize(1200, 800))
                      
                              showNormalWindow = True
                              if settings.value('mainWindow/isMaximized') is not None:
                                  if settings.value('mainWindow/isMaximized') == 'true':
                                      self.main.showMaximized()
                                      showNormalWindow = False
                              if settings.value('mainWindow/isFullScreen') is not None:
                                  if settings.value('mainWindow/isFullScreen') == 'true':
                                      self.main.showFullScreen()
                                      showNormalWindow = False
                              if showNormalWindow:
                                  self.main.showNormal()
                      
                              # StickerPrintingWindow settings
                              self.stickerPrintingWindow.setSettings(settings)
                      
                      
                      1 Reply Last reply
                      0
                      • F Offline
                        F Offline
                        fvez_demtroys
                        wrote on last edited by
                        #11

                        @SGaist Sorry for the ping, have you had a chance to look at this?

                        Big thanks in advance,
                        Best regards,
                        FV

                        SGaistS 1 Reply Last reply
                        0
                        • F fvez_demtroys

                          @SGaist Sorry for the ping, have you had a chance to look at this?

                          Big thanks in advance,
                          Best regards,
                          FV

                          SGaistS Offline
                          SGaistS Offline
                          SGaist
                          Lifetime Qt Champion
                          wrote on last edited by
                          #12

                          No need to be sorry, it's not something forbidden.

                          I don't have Windows at hand so I have tested your code on macOS and PyQt6 as I could not install PyQt5. Beside some adjustment for the enum values, the filters worked properly.

                          Interested in AI ? www.idiap.ch
                          Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                          1 Reply Last reply
                          0

                          • Login

                          • Login or register to search.
                          • First post
                            Last post
                          0
                          • Categories
                          • Recent
                          • Tags
                          • Popular
                          • Users
                          • Groups
                          • Search
                          • Get Qt Extensions
                          • Unsolved