def _init_misc(): """Initialize misc. config-related files.""" save_manager = objreg.get('save-manager') state_config = ini.ReadWriteConfigParser(standarddir.data(), 'state') for sect in ['general', 'geometry']: try: state_config.add_section(sect) except configparser.DuplicateSectionError: pass # See commit a98060e020a4ba83b663813a4b9404edb47f28ad. state_config['general'].pop('fooled', None) objreg.register('state-config', state_config) save_manager.add_saveable('state-config', state_config.save) # We need to import this here because lineparser needs config. from qutebrowser.misc import lineparser command_history = lineparser.LimitLineParser( standarddir.data(), 'cmd-history', limit=('completion', 'cmd-history-max-items'), parent=objreg.get('config')) objreg.register('command-history', command_history) save_manager.add_saveable('command-history', command_history.save, command_history.changed) # Set the QSettings path to something like # ~/.config/qutebrowser/qsettings/qutebrowser/qutebrowser.conf so it # doesn't overwrite our config. # # This fixes one of the corruption issues here: # https://github.com/The-Compiler/qutebrowser/issues/515 path = os.path.join(standarddir.config(), 'qsettings') for fmt in [QSettings.NativeFormat, QSettings.IniFormat]: QSettings.setPath(fmt, QSettings.UserScope, path)
def __init__(self, argv, Liststr=None): QSettings.setPath(QSettings.IniFormat, QSettings.UserScope, str(FOLDER.parent / "settings")) self.settings = QSettings(QSettings.IniFormat, QSettings.UserScope, "adanteh", "testapp") self.settings.IniFormat super().__init__(argv)
def setUp(self): self.tempFile = tempfile.NamedTemporaryFile(prefix='retext-', suffix='.ini') baseName = splitext(basename(self.tempFile.name))[0] QSettings.setPath(QSettings.IniFormat, QSettings.UserScope, dirname(self.tempFile.name)) self.settings = QSettings(QSettings.IniFormat, QSettings.UserScope, baseName)
def __init__(self): super().__init__() self.targetAddr = '0.0.0.0' self.targetPort = 0 QSettings.setPath(QSettings.IniFormat, QSettings.UserScope, QDir.currentPath()) self.settings = QSettings(QSettings.IniFormat, QSettings.UserScope, 'config') self.readSettings() self.connectionSettings = ConnectionSettings(self.targetAddr, self.targetPort, self) self.connectionSettings.settingsChanged.connect( self.onConnectionSettingsSettingsChanged) self.socket = QTcpSocket(self) self.socket.stateChanged.connect(self.onSocketStateChanged) self.socket.readyRead.connect(self.onSocketReadyRead) self.frameLength = 0 self.lastSocketState = QAbstractSocket.UnconnectedState self.animationTimer = QTimer(self) self.animationTimer.timeout.connect(self.onAnimationTimerTimeout) self.animationCounter = 0 self.connectionTimer = QTimer(self) self.connectionTimer.setSingleShot(True) self.connectionTimer.timeout.connect(self.onConnectionTimerTimeout) self.dataExchangeTimer = QTimer(self) self.dataExchangeTimer.timeout.connect(self.onDataExchangeTimerTimeout) self.initUI() self.onConnectionSettingsSettingsChanged(self.targetAddr, self.targetPort) self.onSocketStateChanged()
def __init__(self): self._settings = {} self._settingsClient = None QSettings.setPath(QSettings.IniFormat, QSettings.UserScope, "settings") QSettings.setDefaultFormat(QSettings.IniFormat)
def setUpClass(cls): QCoreApplication.setApplicationName("test1") QCoreApplication.setOrganizationName("org1") cls.settings_dir = tempfile.TemporaryDirectory() QSettings.setDefaultFormat(QSettings.Format.IniFormat) QSettings.setPath(QSettings.Format.IniFormat, QSettings.Scope.UserScope, cls.settings_dir.name)
def _init_misc(): """Initialize misc. config-related files.""" save_manager = objreg.get('save-manager') state_config = ini.ReadWriteConfigParser(standarddir.data(), 'state') for sect in ['general', 'geometry']: try: state_config.add_section(sect) except configparser.DuplicateSectionError: pass # See commit a98060e020a4ba83b663813a4b9404edb47f28ad. state_config['general'].pop('fooled', None) objreg.register('state-config', state_config) save_manager.add_saveable('state-config', state_config.save) # We need to import this here because lineparser needs config. from qutebrowser.misc import lineparser command_history = lineparser.LimitLineParser( standarddir.data(), 'cmd-history', limit=('completion', 'cmd-history-max-items'), parent=objreg.get('config')) objreg.register('command-history', command_history) save_manager.add_saveable('command-history', command_history.save, command_history.changed) # Set the QSettings path to something like # ~/.config/qutebrowser/qsettings/qutebrowser/qutebrowser.conf so it # doesn't overwrite our config. # # This fixes one of the corruption issues here: # https://github.com/qutebrowser/qutebrowser/issues/515 path = os.path.join(standarddir.config(), 'qsettings') for fmt in [QSettings.NativeFormat, QSettings.IniFormat]: QSettings.setPath(fmt, QSettings.UserScope, path)
def __init__(self, configuration: Configuration): super().__init__() QSettings.setDefaultFormat(QSettings.IniFormat) QSettings.setPath(QSettings.IniFormat, QSettings.UserScope, configuration.user_settings_directory) # We fake the application and organisation name to try and use a "nicer" directory for settings. # However, an organisation name is required to ensure this works properly on all systems. # See issues like this: https://www.qtcentre.org/threads/35300-QSplitter-restoreState()-not-working self.__store = QSettings(QSettings.IniFormat, QSettings.UserScope, "nasm", "settings", self)
def init() -> None: """Initialize config storage not related to the main config.""" global state state = StateConfig() # Set the QSettings path to something like # ~/.config/glimpsebrowser/qsettings/glimpsebrowser/glimpsebrowser.conf so it # doesn't overwrite our config. # # This fixes one of the corruption issues here: # https://github.com/glimpsebrowser/glimpsebrowser/issues/515 path = os.path.join(standarddir.config(auto=True), 'qsettings') for fmt in [QSettings.NativeFormat, QSettings.IniFormat]: QSettings.setPath(fmt, QSettings.UserScope, path)
def init(): """Initialize config storage not related to the main config.""" global state state = StateConfig() state['general']['version'] = qutebrowser.__version__ # Set the QSettings path to something like # ~/.config/qutebrowser/qsettings/qutebrowser/qutebrowser.conf so it # doesn't overwrite our config. # # This fixes one of the corruption issues here: # https://github.com/qutebrowser/qutebrowser/issues/515 path = os.path.join(standarddir.config(auto=True), 'qsettings') for fmt in [QSettings.NativeFormat, QSettings.IniFormat]: QSettings.setPath(fmt, QSettings.UserScope, path)
def init() -> None: """Initialize config storage not related to the main config.""" global state try: state = StateConfig() except configparser.Error as e: msg = "While loading state file from {}".format(standarddir.data()) desc = configexc.ConfigErrorDesc(msg, e) raise configexc.ConfigFileErrors('state', [desc], fatal=True) # Set the QSettings path to something like # ~/.config/qutebrowser/qsettings/qutebrowser/qutebrowser.conf so it # doesn't overwrite our config. # # This fixes one of the corruption issues here: # https://github.com/qutebrowser/qutebrowser/issues/515 path = os.path.join(standarddir.config(auto=True), 'qsettings') for fmt in [QSettings.NativeFormat, QSettings.IniFormat]: QSettings.setPath(fmt, QSettings.UserScope, path)
def _init_misc(): """Initialize misc. config-related files.""" save_manager = objreg.get("save-manager") state_config = ini.ReadWriteConfigParser(standarddir.data(), "state") for sect in ("general", "geometry"): try: state_config.add_section(sect) except configparser.DuplicateSectionError: pass # See commit a98060e020a4ba83b663813a4b9404edb47f28ad. state_config["general"].pop("fooled", None) objreg.register("state-config", state_config) save_manager.add_saveable("state-config", state_config.save) # We need to import this here because lineparser needs config. from qutebrowser.misc import lineparser command_history = lineparser.LimitLineParser( standarddir.data(), "cmd-history", limit=("completion", "cmd-history-max-items"), parent=objreg.get("config") ) objreg.register("command-history", command_history) save_manager.add_saveable("command-history", command_history.save, command_history.changed) # Set the QSettings path to something like # ~/.config/qutebrowser/qsettings/qutebrowser/qutebrowser.conf so it # doesn't overwrite our config. # # This fixes one of the corruption issues here: # https://github.com/The-Compiler/qutebrowser/issues/515 if standarddir.config() is None: path = os.devnull else: path = os.path.join(standarddir.config(), "qsettings") for fmt in (QSettings.NativeFormat, QSettings.IniFormat): QSettings.setPath(fmt, QSettings.UserScope, path)
def __init__(self, ): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.modelArray = [QStandardItemModel(), QStandardItemModel()] self.filterProxyArray = [RecursiveProxyModel(), RecursiveProxyModel()] self.treeViewArray = [self.ui.treeView, self.ui.treeView_2] self.pathLabelArray = [self.ui.labelPath, self.ui.labelPath_2] self.setWindowTitle('QDICOMDiffer ' + version) # Read the settings from the settings.ini file system_location = os.path.dirname(os.path.abspath(sys.argv[0])) QSettings.setPath(QSettings.IniFormat, QSettings.SystemScope, system_location) self.settings = QSettings("settings.ini", QSettings.IniFormat) if os.path.exists(system_location + "/settings.ini"): print("Loading settings from " + system_location + "/settings.ini") col = self.settings.value('Appearance/directMatchColour') if col is None: direct_match_colour = default_direct_match_colour else: direct_match_colour = QColor(col) col = self.settings.value('Appearance/indirectMatchColour') if col is None: indirect_match_colour = default_indirect_match_colour else: indirect_match_colour = QColor(col) font = self.settings.value('Appearance/new_font') for i in range(2): self.modelArray[i].setHorizontalHeaderLabels( ['Tag', 'Description', 'Value', 'Different', 'Index']) self.filterProxyArray[i].setSourceModel(self.modelArray[i]) self.ui.lineEditTagFilter.textChanged.connect( self.filterProxyArray[i].set_tag_filter) self.ui.lineEditDescFilter.textChanged.connect( self.filterProxyArray[i].set_desc_filter) self.ui.lineEditValFilter.textChanged.connect( self.filterProxyArray[i].set_value_filter) self.treeViewArray[i].setModel(self.filterProxyArray[i]) self.treeViewArray[i].setEditTriggers( QAbstractItemView.NoEditTriggers) self.treeViewArray[i].setColumnHidden(3, True) self.treeViewArray[i].setColumnHidden(4, True) # the i=i here is needed to ensure i is within the local namespace, without it i evaluates to 1 both times self.ui.checkBoxShowOnlyDifferent.stateChanged.connect( lambda state, i=i: self.filterProxyArray[ i].set_show_only_different(bool(state))) self.treeViewArray[i].file_dropped.connect( lambda filepath, i=i: self.load_file(filepath, i)) self.treeViewArray[i].indirect_match_colour = indirect_match_colour self.treeViewArray[i].direct_match_colour = direct_match_colour if font is not None: self.treeViewArray[i].setFont(font) self.ui.splitter.setSizes([100, 0]) self.ui.actionOpen.triggered.connect(self.open_files) self.ui.actionDiff.triggered.connect(self.do_diff) self.ui.actionHTML_diff.triggered.connect(self.open_html_diff_window) self.ui.actionAbout.triggered.connect(self.open_about_window) self.ui.actionAppearance.triggered.connect(self.open_appearance_window) self.raw_diff_window = None self.html_diff_window = None self.appearance_window = None self.ui.actionText_diff.triggered.connect(self.open_text_diff_window) self.ui.actionExpand_all.triggered.connect(self.expand_all) self.ui.actionCollapse_all.triggered.connect(self.collapse_all) self.dc_array = [None] * 2 self.diff_result = None self.html_diff_result = None # If we were given command line arguments, try and load them arguments = sys.argv[1:] for number, line in enumerate(arguments): self.load_file(line, number) # Only ever handle two files if number == 1: self.ui.splitter.setSizes([50, 50]) break self.show()
SettingsDir = None sys.path.insert(1, os.path.dirname(__file__)) for arg in sys.argv[:]: if arg.startswith("--config="): import Globals configDir = arg.replace("--config=", "") Globals.setConfigDir(configDir) sys.argv.remove(arg) elif arg.startswith("--settings="): from PyQt5.QtCore import QSettings SettingsDir = os.path.expanduser(arg.replace("--settings=", "")) if not os.path.isdir(SettingsDir): os.makedirs(SettingsDir) QSettings.setPath(QSettings.IniFormat, QSettings.UserScope, SettingsDir) sys.argv.remove(arg) from Globals import AppInfo from Toolbox import Startup def createMainWidget(argv): """ Function to create the main widget. @param argv list of commandline parameters (list of strings) @return reference to the main widget (QWidget) """ from Tools.TrayStarter import TrayStarter
def __init__(self): super(MainWindow, self).__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.setWindowTitle('QDICOMMiner ' + __version__) # TODO: Find a better way of stopping the selection of list items. This only sortof works self.ui.listWidget.setSelectionMode(QAbstractItemView.NoSelection) system_location = os.path.dirname(os.path.realpath(__file__)) plugin_locations = [os.path.join(system_location, 'Plugins')] self.plugin_manager = PluginManager() self.plugin_manager.setPluginPlaces(plugin_locations) self.plugin_manager.collectPlugins() self.plugin_list = [] for plugin in self.plugin_manager.getAllPlugins(): self.plugin_list.append(plugin.name) # Read the settings from the settings.ini file system_location = os.path.dirname(os.path.realpath(__file__)) QSettings.setPath(QSettings.IniFormat, QSettings.SystemScope, system_location) self.settings = QSettings("settings.ini", QSettings.IniFormat) if os.path.exists(system_location + "/settings.ini"): print("Loading settings from " + system_location + "/settings.ini") # Set the last used output file and analyse folder locations output_file = self.settings.value('main/lastOutputFile') if output_file is None: output_file = 'data.csv' if not os.path.isabs(output_file): abs_output_location = os.path.join(system_location, output_file) self.ui.labelOutputFile.setText(abs_output_location) else: self.ui.labelOutputFile.setText(output_file) folder_to_analyse = self.settings.value('main/lastAnalyseFolder') if folder_to_analyse is None: folder_to_analyse = '' if not os.path.isabs(folder_to_analyse): abs_folder_to_analyse = os.path.join(system_location, folder_to_analyse) self.ui.labelFolderToAnalysePath.setText(abs_folder_to_analyse) else: self.ui.labelFolderToAnalysePath.setText(folder_to_analyse) self.ui.labelFolderToAnalysePath.clicked.connect( lambda: self.open_folder_in_explorer( self.ui.labelFolderToAnalysePath.text())) self.ui.labelOutputFile.clicked.connect( lambda: self.open_folder_in_explorer(self.ui.labelOutputFile.text( ))) # Setup a dictionary of key DICOM description and value the DICOM tag names = [] self.DICOM_dic = {} for key in dicom_dict.DicomDictionary: names.append(dicom_dict.DicomDictionary[key][2]) self.DICOM_dic[dicom_dict.DicomDictionary[key][2]] = key self.completer = QCompleter() self.completer.setCaseSensitivity(Qt.CaseInsensitive) self.model = QStringListModel() self.model.setStringList(names) self.completer.setModel(self.model) self.ui.pushButtonAddListWidget.clicked.connect( self.add_new_list_widget) self.ui.pushButtonBrowseFolderToAnalysePath.clicked.connect( self.browse_for_input_folder) self.ui.pushButtonBrowseOutputFilePath.clicked.connect( self.browse_for_output_file) self.ui.pushButtonDoAnalysis.clicked.connect(self.do_analysis) self.count_num_of_files_thread = CountFilesThread() self.count_num_of_files_thread.num_of_files.connect( self.update_number_of_files) self.count_file_number.connect(self.count_num_of_files_thread.count) self.count_file_number.emit(self.ui.labelFolderToAnalysePath.text() ) # Using a signal to keep thread safety self.ui.progressBar.setFormat(' %v/%m (%p%)') self.ui.progressBar.hide() self.ui.actionSave_Template.triggered.connect(self.save_template) self.ui.actionLoad_Template.triggered.connect(self.load_template) self.ui.actionAbout.triggered.connect(self.open_about_window) self.analyse_and_output_data_thread = AnalyseAndOutputDataThread() self.show()
import sys import os for arg in sys.argv[:]: if arg.startswith("--config="): import Globals configDir = arg.replace("--config=", "") Globals.setConfigDir(configDir) sys.argv.remove(arg) elif arg.startswith("--settings="): from PyQt5.QtCore import QSettings settingsDir = os.path.expanduser(arg.replace("--settings=", "")) if not os.path.isdir(settingsDir): os.makedirs(settingsDir) QSettings.setPath(QSettings.IniFormat, QSettings.UserScope, settingsDir) sys.argv.remove(arg) from Globals import AppInfo from Toolbox import Startup def createMainWidget(argv): """ Function to create the main widget. @param argv list of commandline parameters (list of strings) @return reference to the main widget (QWidget) """ from SqlBrowser.SqlBrowser import SqlBrowser
# Copyright (C) 2010-2017, kachelaqa <*****@*****.**> import sys, os, getopt from PyQt5 import QtWidgets from PyQt5.QtCore import ( QSettings, ) from PyQt5.QtWidgets import ( QApplication, ) QApplication.setApplicationName('PkgBrowser') QApplication.setApplicationVersion('0.20.1') QSettings.setPath(QSettings.NativeFormat, QSettings.SystemScope, '/etc') class Application(QApplication): @staticmethod def applicationName(): return QApplication.applicationName().lower() @staticmethod def applicationTitle(): return QApplication.applicationName() @classmethod def applicationUrl(cls, *paths): url = 'https://bitbucket.org/kachelaqa/%s' % cls.applicationName() if paths: url = os.path.join(url, *paths) return url
DEBUG = False EMBED_JUPYTER = False USE_OPENGL = True USE_PYTHON_RENDERING = False # Make app portable if `application folder`/data folder exists IS_PORTABLE = os.path.exists(os.path.join('.', 'data')) if IS_PORTABLE: USER_PATH = os.path.join(APP_PATH, 'data') try: # Network visualisation from PyQt5.QtCore import QSettings QSettings.setDefaultFormat(QSettings.IniFormat) QSettings.setPath(QSettings.IniFormat, QSettings.UserScope, USER_PATH) except ImportError: pass elif sys.platform.startswith('win'): USER_PATH = os.path.join(os.path.expandvars(r'%APPDATA%'), "MetGem") elif sys.platform.startswith('darwin'): USER_PATH = os.path.join(os.path.expanduser('~'), 'Library', 'Application Support', "MetGem") elif sys.platform.startswith('linux'): USER_PATH = os.path.join(os.path.expanduser('~'), '.config', "MetGem") else: USER_PATH = os.path.realpath('.') DATABASES_PATH = os.path.join(USER_PATH, 'databases') SQL_PATH = os.path.join(DATABASES_PATH, 'spectra.sqlite') if sys.platform.startswith('darwin'): LOG_PATH = os.path.join(os.path.expanduser('~'), 'Library', 'Logs', "MetGem")
def __init__( self, **kwargs ): self.system_settings_dir = self.settings_dir() QSettings.setPath(QSettings.IniFormat, QSettings.SystemScope, self.system_settings_dir ) self.project_name = None self.default_settings = kwargs.get('defaults',{})
class window(QMainWindow): def __init__(self): super(window, self).__init__() print("Starting to do things") self.setObjectName( "Mother Window") # print("I am the "+ self.objectName()) self.setAttribute( Qt.WA_QuitOnClose, True ) #Ensures that closing the main window also closes the preferences window self.clip = QApplication.clipboard() #System-wide clipboard self.pickerButton = self.clickButton("Pipette", QColorDialog.getColor) #Configs self.settings = QSettings( "D:\Projects\Python\SwitchBoard\MySwitchboard.cfg", QSettings.IniFormat) self.settings.setPath( QSettings.IniFormat, QSettings.UserScope, "D:\Projects\Python\SwitchBoard\MySwitchboard.cfg") # self.settingsPath = QSettings("D:\Projects\Python\SwitchBoard\MySwitchboard.cfg", QSettings.NativeFormat) # self.settings.setPath(QSettings.IniFormat,QSettings.UserScope,"D:\Projects\Python\SwitchBoard\MySwitchboard.cfg") self.initSettings() # DEBUG: LIST ALL CONFIG KEYS # print("Listing all config keys:" + str(self.settings.allKeys())); print("Config file is" + self.settings.fileName()) # setup window aspects self.setWindowTitle(self.settings.value("cfgWindowTitle")) self.setWindowIcon(QIcon('logo.png')) self.declareActions() self.setStatusBar(QStatusBar(self)) self.XY = QLabel( "Cursor:" ) # TODO: Make this come with something to display the numerical position of the cursor; might involve the timerEvent of QStatusBar # self.statusBar.addPermanentWidget(self.XY) QStatusBar.addPermanentWidget(self.statusBar(), self.XY) #TODO: Check if status bar properly has its QSizeGrip, using isSizeGripEnabled() self.topMenu() self.mainToolBar = QObject self.preferencesDialog = QDialog() self.setupToolBars() #NOTE: for QMainWindow, do a find for things with menu, status, tab, tool pop = self.basicButton('test', self.popup, None, 25, 100) box = self.basicCheckBox(self.editTitle) self.bar = self.progressBar(325, 75, 160, 28) self.doProgress = self.basicButton('Increment Progress', self.progress, "", 200, 75) clearClipboard = self.basicButton( "Clear Clipboard", self.clip.clear) #Button which clears the system clipboard #print(self.clip.text())#print clipboard text Dial = self.dial(1, 100, 300) self.pageBar = QTabWidget(self) # TabWidget is a QWidget self.tab1 = QWidget() # ;self.tab1.adjustSize() self.tab2 = QWidget() # ;self.tab2.adjustSize() tab1Layout = QVBoxLayout() tab1Layout.addStretch(1) tab1Layout.addWidget(pop) tab1Layout.addWidget(clearClipboard) tab1Layout.addWidget(box) tab1Layout.addWidget(Dial) progressBox = QHBoxLayout() progressBox.addStretch(1) progressBox.addWidget(self.doProgress) progressBox.addWidget(self.bar) self.tab1.setLayout(tab1Layout) self.tab2.setLayout(progressBox) #previously took progressBox as param self.pageBar.addTab(self.tab1, "tab1") self.pageBar.addTab(self.tab2, "tab2") # self.mainToolBar # tesT=QVBoxLayout() # tesT.addWidget(self.mainToolBar) # tesT.addWidget(self.pageBar) # self.setLayout(tesT) self.mainToolBar.addWidget(self.pageBar) # self.mainToolBar.addAction(self.actCopy) # self.mainToolBar.setLayout=QHBoxLayout(self) # make the pageBar occupy everything below the toolbar. # anything else being displayed must be part of a tab, # otherwise it will end up being rendered behind the pageBar # self.setCentralWidget() tempPref = self.basicButton('Options', self.appPreferences, None, 300, 300) self.restoreGeometry(self.settings.value("mainWindowGeometry")) print("Window width:" + str(self.width())) print("Window height:" + str(self.height())) print("done init") #Declare application wide Actions # noinspection PyUnresolvedReferences def declareActions(self): # WIP # cut self.actCut = QAction("Cu&t", self) self.actCut.setShortcut("Ctrl+x") def Link(): wrapper(testPrint, "Cut").call() self.actCut.triggered.connect(Link) # copy self.actCopy = QAction("&Copy", self) self.actCopy.setShortcut("Ctrl+c") def Link(): wrapper(testPrint, "Copy").call() self.actCopy.triggered.connect(Link) # paste self.actPaste = QAction("&Paste", self) self.actPaste.setShortcut("Ctrl+v") def Link(): wrapper(testPrint, "Paste").call() self.actPaste.triggered.connect(Link) # quit self.actQuit = QAction("&Quit", self) self.actQuit.setShortcut("Ctrl+q") # self.actQuit.triggered.connect(endProgram) # self.actQuit.setToolTip("Close the Application") self.actQuit.setStatusTip("Close the application") self.actQuit.triggered.connect(self.closeEvent) #Simple button with default parameters for position, label, and tooltip(none) # noinspection PyUnresolvedReferences def basicButton(self, text='test', func=None, tip=None, X=200, Y=200): btn = QPushButton(text, self) btn.adjustSize() btn.move(X, Y) btn.setToolTip(tip) if isinstance(func, wrapper): def link(): func.call() # print("Calling wrapped function according to button press") btn.triggered.connect(link) # might need to be clicked instead of triggered elif func is not None: btn.clicked.connect(func) else: print("no function") pass return btn #Tri-state checkbox WIP def triCheckBox(self, func=None, text='test', X=25, Y=75): self.basicCheckBox(func, text, X, Y, True) #Simple checkbox with default parameters for position and label, and handling for tri-state boxes # noinspection PyUnresolvedReferences def basicCheckBox(self, func=None, text='test', X=25, Y=75, isTri=False): checkBox = QCheckBox(text, self) checkBox.adjustSize() checkBox.move(X, Y) if isTri == True: checkBox.setTristate(True) if func is not None: checkBox.stateChanged.connect(func) return checkBox # Round dial/knob WIP def dial(self, func=None, X=200, Y=200, radius=50, wrap=False): knob = QDial(self) knob.move(X, Y) knob.resize(radius, radius) knob.setWrapping(wrap) if func is not None: func # TODO:something something show number in a box nearby return knob # "Template" function for a toolbar button with an icon def toolBar_Icon(self, icon, func, tooltip, statustip="Null"): item = QAction(QIcon(icon), tooltip, self) if statustip != "Null": item.setStatusTip(statustip) # noinspection PyUnresolvedReferences if func is not None: item.triggered.connect(func) else: print( "One or more icon type items on your toolbar has no function") return item # "Template" function for a text-only toolbar button def toolBar_Text(self, text, func): item = QAction(text, self) # noinspection PyUnresolvedReferences if func is not None: item.triggered.connect(func) else: print( "One or more text type items on your toolbar has no function") return item # Add toolbars and populate them with buttons def setupToolBars(self): # Make buttons iconB = self.toolBar_Icon("logo.png", testPrint, "icon", "Do something") textB = self.toolBar_Text("&Textual Button", testPrint) # Make toolbars self.mainToolBar = QToolBar("Main Toolbar") # Add toolbars to window. CRITICAL STEP mainToolBarPosition = int( self.settings.value("MainToolbar/mainToolBarPosition")) print("Main toolbar pos: " + str(mainToolBarPosition)) self.mainToolBar.setFloatable( self.settings.value("MainToolbar/isMainToolBarFloatable")) self.mainToolBar.setMovable( self.settings.value("MainToolbar/isMainToolBarMovable")) self.addToolBar(mainToolBarPosition, self.mainToolBar) # Add buttons to toolbars self.mainToolBar.addAction(iconB) self.mainToolBar.addAction(textB) # "Template" function for a simple menu item def menuItem(self, func, name, tip=None, shortcut="Null", isToggle=False, group=None): item = QAction(name, self) # self reminder: item is now a QAction item.setStatusTip(tip) if shortcut != "Null": item.setShortcut( shortcut ) # ;else: print("no shortcut for menu item \""+name+"\"") if isToggle != False: item.setCheckable(True) if group is not None: group.addAction(item) if isinstance(func, wrapper): def link(): func.call() # noinspection PyUnresolvedReferences item.triggered.connect(link) elif func is not None: #print(func.__name__ + " is not a wrapper. It is a " + type(func).__name__) # noinspection PyUnresolvedReferences item.triggered.connect(func) else: print("Menu item \"" + name + "\" has no function") return item # Add menus and populate them with actions def topMenu(self): config = self.settings #; self.statusBar() mainMenu = self.menuBar() # Make menu items prefs = self.menuItem( # wrapper(testPrint, "Preferences menu item selected") # , "Preferences") self.appPreferences, "Preferences", "View and edit application settings") prefs.setMenuRole(QAction.PreferencesRole) styleGroup = QActionGroup(mainMenu) windows = wrapper(self.themeControl, "Windows") winVista = wrapper(self.themeControl, "Windowsvista") winXP = wrapper(self.themeControl, "Windowsxp") fusion = wrapper(self.themeControl, "Fusion") style1 = self.menuItem(fusion, "Fusion", statusTips["fusion"], isToggle=True, group=styleGroup) style2 = self.menuItem(windows, "Windows", statusTips["windows"], isToggle=True, group=styleGroup) style3 = self.menuItem(winVista, "Windows Vista", statusTips["vista"], isToggle=True, group=styleGroup) style4 = self.menuItem(winXP, "Windows XP", statusTips["XP"], isToggle=True, group=styleGroup) for style in styleGroup.actions(): # print("style: "+str(style.text()).capitalize().replace(" ", "") + " setting: "+config.value("primaryStyle")) if (str(style.text()).capitalize().replace( " ", "")) == config.value("primaryStyle"): style.setChecked(True) # Makes sure that the configured style appears as checked on load style3.setText(style3.text() + " (Default)") colorPicker = self.menuItem(QColorDialog.getColor, "Color Picker") # TODO: Reset layout of window to default? #resetPlacement = self.menuItem(None, "Reset Window Layout", "Reset the window layout to default") # Make menus fileMenu = mainMenu.addMenu("File") editMenu = mainMenu.addMenu("Edit") viewMenu = mainMenu.addMenu("View") styleMenu = viewMenu.addMenu("Styles") layoutMenu = viewMenu.addMenu("Layout") # Add actions to menus fileMenu.addAction( self.actQuit ) # DONE:add a status tip to this, "Close the application" fileMenu.addAction( prefs ) # DONE:add a status tip to this, "View and edit application settings" editMenu.addAction(self.actCopy) editMenu.addAction(self.actCut) editMenu.addAction(self.actPaste) viewMenu.addAction(colorPicker) layoutMenu.addAction(self.menuItem( testPrint, None)) # TODO:give meaningful functions later styleMenu.addAction(style1) styleMenu.addAction(style2) styleMenu.addAction(style3) styleMenu.addAction(style4) # print(style1.trigger()) #if style2.trigger():print("FFF") #viewMenu.addAction(resetPlacement) def themeControl(self, text): print("Setting style to " + text) QApplication.setStyle(QStyleFactory.create(text)) self.settings.setValue("primaryStyle", text) # Progress bar WIP def progressBar(self, X=25, Y=75, length=100, height=30): bar = QProgressBar(self) bar.setGeometry(X, Y, length, height) return bar # A box you can enter text in WIP/TODO def textBox(self, text=None, X=200, Y=200, length=100, height=30): pass # Writes text directly onto the window WIP/TODO def displayText(self, text=None): pass # Creates a tab for page switching WIP/TODO def pageTab(self): # every tab will be a widget, and the widget is assigned a name # and added to the tab bar somewhere else pass #Section####################################### Start Settings Handling ############################################### def appPreferences(self): config = self.settings settingsPage = self.preferencesDialog settingsPage.setWindowTitle("Settings") # Refresh field values def getCurrentValues(): for setting in settingsList: if setting.isModified( ): # TODO:Handle different types, consider handling special cases print(setting.cfgName + " has been changed. Refreshing field value.") if type(setting) == QLineEdit: setting.setText(config.value(setting.cfgName)) elif type(setting) == QCheckBox: pass elif type(setting) == QPushButton: pass else: print("Setting \"" + setting.cfgName + "\" matches no handled type. Its type is " + str(type(setting))) # Update config file contents to match field values def updateModifiedValues(): for setting in settingsList: if setting.isModified( ): #TODO:Handle different types, consider handling special cases print(setting.cfgName + " has been modified. Now saving.") if type(setting) == QLineEdit: config.setValue(setting.cfgName, setting.text()) elif type(setting) == QCheckBox: pass elif type(setting) == QPushButton: pass else: print("Setting \"" + setting.cfgName + "\" matches no handled type. Its type is " + str(type(setting))) # settingsPage.update() # self.showEvent, update parentLayout = QVBoxLayout() # something to get the saved preferences responses = QDialogButtonBox(QDialogButtonBox.NoButton, Qt.Horizontal) responses.apply = responses.addButton("Accept Changes", QDialogButtonBox.AcceptRole) responses.good = responses.addButton("Okay", QDialogButtonBox.ActionRole) responses.discard = responses.addButton("Discard Changes", QDialogButtonBox.RejectRole) # Give these actual functions def accResp(): wrapper(testPrint, "Accepting Changes...").call() # Check for and save any changed settings updateModifiedValues() # print(winTitle.text()); #text, textChanged, textEdited, setValidator, setText. setTooltip. QLineEdit,displayText #settingsPage.accept() config.sync() def rejResp(): wrapper(testPrint, "Discarding Changes...").call() getCurrentValues() settingsPage.reject() def good(): # settingsPage.setResult(QDialog.accepted()) # settingsPage.done(QDialog.accepted()) settingsPage.accept() getCurrentValues() print("Leaving Settings") #responses.accepted.connect(good) #responses.accepted.connect(accResp) #responses.rejected.connect(rejResp) #Using this to allow an OK and an Accept button with separate resulting operations def onClicked(): sender = self.sender() if sender.text() == "Accept Changes": accResp() elif sender.text() == "Discard Changes": rejResp() elif sender.text() == "Okay": good() responses.apply.clicked.connect(onClicked) responses.discard.clicked.connect(onClicked) responses.good.clicked.connect(onClicked) # add content to this #DONE: probably need to use a byte array to store current settings on opening preferences window. that would be used to restore discarded changes #TODO: apply doesnt just need to sync, it needs to update too winTitle = QLineEdit(config.value("cfgWindowTitle")) winTitle.cfgName = "cfgWindowTitle" #CRITICAL FOR AUTOMATIC SETTING SAVE labelWinTitle = QLabel("Window Title:") labelWinTitle.setBuddy(winTitle) settingsList = [winTitle] #DONT FORGET TO ADD TO THIS horiz1 = QHBoxLayout() horiz1.addWidget(labelWinTitle) horiz1.addWidget(winTitle) parentLayout.addLayout(horiz1) parentLayout.addWidget(responses) # parentLayout.insertStretch(0) settingsPage.setLayout(parentLayout) settingsPage.show() #responses.receivers(PYQT_SIGNAL = accResp) #responses.clicked(responses.apply) # responses.isSignalConnected(responses.clicked(responses.apply)) # if responses.clicked(QAbstractButton = apply):print("YES") # settingsPage.closeEvent() # QDialog.customEvent(),event,eventFilter, installEventFilter, leaveEvent,mask, showEvent, signalsBlocked # responses.finished.connect(something to save?)??? sender senderSignalIndex result? signals? ##something that saves preferences when the OK button is pressed def initSettings(self): # NOTE:Is toolbar moveable or locked in place. Is it floatable. Maybe if i figure out how to let the user adjust contents, # NOTE: add an option to disable that ability? Enable/disable certain widgets? # TODO: Figure out how to add descriptive text into the config file, if at all possible config = self.settings # test=config.setValue("test", 3); print("test=" + str(config.value("test"))) self.windowFlags() flags = Qt.WindowFlags() #Style Configs cfgStyle = config.value("primaryStyle") if str(config.value("primaryStyle")).capitalize().replace( " ", "") not in validStyles: config.setValue("primaryStyle", "Windows Vista") print("Resetting style to hard default") self.themeControl(str(config.value("primaryStyle")).replace( " ", "")) #Sets the window style to the configured value #Main Toolbar Configs config.beginGroup("MainToolbar") cfgMainToolBarPos = config.value("mainToolBarPosition") if cfgMainToolBarPos == "\n" or cfgMainToolBarPos not in [ "1", "2", "4", "8" ]: config.setValue("mainToolBarPosition", Qt.LeftToolBarArea ) #Default toolbar position is on the left side # DONE: Fixed cfgMainToolBarMoveable = config.value("isMainToolBarMovable") # if cfgMainToolBarMoveable == "\n" or type(cfgMainToolBarMoveable)!=bool: if cfgMainToolBarMoveable not in extendedBools: config.setValue("isMainToolBarMovable", True) #Main toolbar is movable by default elif cfgMainToolBarMoveable in [1, "t", "T", "true", "True"]: config.setValue("isMainToolBarMovable", True) elif cfgMainToolBarMoveable in [0, "f", "F", "false", "False"]: config.setValue("isMainToolBarMovable", False) # DONE: Fixed cfgMainToolBarFloatable = config.value("isMainToolBarFloatable") if cfgMainToolBarFloatable not in extendedBools: config.setValue("isMainToolBarFloatable", True) #Main toolbar is floatable by default elif cfgMainToolBarFloatable in [1, "t", "T", "true", "True"]: config.setValue("isMainToolBarFloatable", True) elif cfgMainToolBarFloatable in [0, "f", "F", "false", "False"]: config.setValue("isMainToolBarFloatable", False) config.endGroup() #Other Configs cfgTitle = config.value("cfgWindowTitle") if cfgTitle == "\n": config.setValue("cfgWindowTitle", "I am a window") # TODO: Add checkboxes for these to config manager config.beginGroup("WindowFlags") cfgKeepOnTop = config.value("cfgKeepOnTop") if cfgKeepOnTop not in extendedBools: config.setValue("cfgKeepOnTop", False) elif cfgKeepOnTop in [1, "t", "T", "true", "True"]: config.setValue("cfgKeepOnTop", True) elif cfgKeepOnTop in [0, "f", "F", "false", "False"]: config.setValue("cfgKeepOnTop", False) cfgIsWindowFrameless = config.value("cfgIsFrameless") if cfgIsWindowFrameless not in extendedBools: config.setValue("cfgIsFrameless", False) elif cfgIsWindowFrameless in [1, "t", "T", "true", "True"]: config.setValue("cfgIsFrameless", True) elif cfgIsWindowFrameless in [0, "f", "F", "false", "False"]: config.setValue("cfgIsFrameless", False) if (config.value("cfgKeepOnTop")) == True: flags |= Qt.WindowStaysOnTopHint if (config.value("cfgIsFrameless")) == True: flags |= Qt.FramelessWindowHint self.setWindowFlags(flags) config.endGroup() #Makes sure that default window geometry value is available in case there isn't one in the config cfgWindowGeometry = config.value("mainWindowGeometry") if type( cfgWindowGeometry ) is None or cfgWindowGeometry == "\n" or cfgWindowGeometry == "": config.setValue("mainWindowGeometry", defaultWindowGeometry) print("Defaulting geometry") # if cfgWindowGeometry=='\n':print("IS BLANK") else: # print("Geo: "+str((type(cfgWindowGeometry)))); print(cfgWindowGeometry) pass pass #Little fix for a pet peeve of mine in PyCharm, where comments on the ends of functions are sometimes folded with the function # Section####################################### End Settings Handling ############################################### # Basic,does nothing much, pop-up window prompt; probably wont make a template def popup(self): choice = QMessageBox(self) choice.setText("What do you do?") # move to center of popup Boring = choice.addButton("Don't push Arnold", QMessageBox.AcceptRole) Arnold = choice.addButton("Push Arnold (you know you want to....)", QMessageBox.ActionRole) Exit = choice.addButton(QMessageBox.Cancel) Exit.hide() choice.setEscapeButton(Exit) choice.setDefaultButton(Arnold) choice.exec() if choice.clickedButton() is Arnold: print("*Heavy Austrian accent* OUCH!") elif choice.clickedButton() is Boring: print( "Well you're no fun" ) # ...yeah, I had gotten frustrated at that time, and decided to be a bit silly def editTitle(self, state): if state == Qt.Unchecked: self.setWindowTitle("Temporary Title") else: self.setWindowTitle(self.settings.value("cfgWindowTitle")) # there has to be a way to specify which progress bar this is for, but for the life of me I can't think of how. # Cross that bridge if/when I come to it def progress(self): if self.bar.value() < 100: self.bar.setValue(self.bar.value() + 1) if self.bar.value() == 100: print("Progress: Done") elif self.bar.value() % 10 == 0: print("Progress: " + str(self.bar.value())) else: pass def closeEvent(self, *args, **kwargs): self.settings.setValue("mainWindowGeometry", self.saveGeometry()) # print("Saving Geometry") # print(self.settings.value("mainWindowGeometry")) # print(self.saveGeometry()) self.close() #Section############################### Start Test Functions ####################################### def clickButton(self, text='test', func=None, tip=None, X=200, Y=200): btn = QPushButton(text, self) btn.adjustSize() btn.move(X, Y) btn.setToolTip(tip) if isinstance(func, wrapper): def link(): func.call() btn.clicked.connect(link) else: print("no function") pass return btn
def main(): try: locale.setlocale(locale.LC_ALL, '') except: # Work around system locale not specified (under Linux or Mac OS) pass app = QApplication(sys.argv) QCoreApplication.setOrganizationName(version.Company) QCoreApplication.setApplicationName(version.AppName) if OpenNumismat.PORTABLE: QCoreApplication.setOrganizationName('.') QSettings.setDefaultFormat(QSettings.IniFormat) QSettings.setPath(QSettings.IniFormat, QSettings.UserScope, OpenNumismat.PRJ_PATH) settings = Settings() if settings['error']: sys.excepthook = exceptHook if not os.path.exists(settings['reference']): # Create default dirs and files if not exists try: ref_path = os.path.dirname(settings['reference']) dst_ref = os.path.join(ref_path, 'reference.ref') if not os.path.exists(dst_ref): os.makedirs(ref_path, exist_ok=True) src_ref = os.path.join(OpenNumismat.PRJ_PATH, 'db', 'reference_%s.ref' % settings['locale']) if not os.path.exists(src_ref): src_ref = os.path.join(OpenNumismat.PRJ_PATH, 'db', 'reference_en.ref') shutil.copy(src_ref, dst_ref) dst_demo_db = os.path.join(OpenNumismat.HOME_PATH, 'demo.db') if not os.path.exists(dst_demo_db): os.makedirs(OpenNumismat.HOME_PATH, exist_ok=True) src_demo_db = os.path.join(OpenNumismat.PRJ_PATH, 'db', 'demo_%s.db' % settings['locale']) if not os.path.exists(src_demo_db): src_demo_db = os.path.join(OpenNumismat.PRJ_PATH, 'db', 'demo_en.ref') shutil.copy(src_demo_db, dst_demo_db) templates_path = os.path.join(OpenNumismat.HOME_PATH, 'templates') os.makedirs(templates_path, exist_ok=True) except: pass TemporaryDir.init(version.AppName) lang = settings['locale'] translator = QTranslator() translator.load('translations/lang_' + lang, OpenNumismat.PRJ_PATH) app.installTranslator(translator) translatorQt = QTranslator() translatorQt.load('translations/qtbase_' + lang, OpenNumismat.PRJ_PATH) app.installTranslator(translatorQt) if not settings['verify_ssl']: ssl._create_default_https_context = ssl._create_unverified_context mainWindow = MainWindow() mainWindow.show() mainWindow.raise_() # this will raise the window on Mac OS X status = app.exec_() # Clear temporary files TemporaryDir.remove() sys.exit(status)