示例#1
0
    def __init__(self, aPath, parent=None):
        super(MyWindow, self).__init__(parent)
        #QIcon.setThemeName('Mint-Y')
        QMetaObject.connectSlotsByName(self)
        self.root = os.path.dirname(sys.argv[0])
        self.logo = os.path.join(self.root, "logo_48.png")
        self.setWindowIcon(QIcon.fromTheme(self.logo))
        self.delimit = '\t'
        self.mycolumn = 0
        self.MaxRecentFiles = 5
        self.windowList = []
        self.recentFileActs = []
        self.settings = QSettings('Axel Schneider', 'CSVEditor')
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.isChanged = False
        self.fileName = ""
        self.fname = "Liste"
        self.mytext = ""
        self.colored = False
        self.copiedRow = []
        self.copiedColumn = []
        ### QTableView seetings
        self.tableView = TableWidgetDragRows()
        self.tableView.setGridStyle(1)
        self.tableView.setCornerButtonEnabled(False)
        self.tableView.setShowGrid(True)
        self.tableView.horizontalHeader().setBackgroundRole(QPalette.Window)
        #        self.tableView.setSelectionBehavior (QAbstractItemView.SelectRows )
        self.tableView.selectionModel().selectionChanged.connect(
            self.makeAllWhite)
        self.tableView.itemClicked.connect(self.getItem)
        self.tableView.setEditTriggers(QAbstractItemView.DoubleClicked)
        self.tableView.cellChanged.connect(self.finishedEdit)
        self.tableView.setDropIndicatorShown(True)

        self.findfield = QLineEdit()
        findAction = QAction(QIcon.fromTheme("edit-find"),
                             "find",
                             self,
                             triggered=self.findText)
        self.findfield.addAction(findAction, 0)
        self.findfield.setPlaceholderText("find (RETURN)")
        self.findfield.setToolTip("press RETURN to find all matches")
        self.findfield.setFixedWidth(150)
        self.findfield.returnPressed.connect(self.findText)

        self.replacefield = QLineEdit()
        replaceAction = QAction(QIcon.fromTheme("edit-find-replace"),
                                "replace",
                                self,
                                triggered=self.replaceText)
        self.replacefield.addAction(replaceAction, 0)
        self.replacefield.setPlaceholderText("replace")
        self.replacefield.setToolTip("replace (RETURN to replace first)")
        self.replacefield.setFixedWidth(150)
        self.replacefield.returnPressed.connect(self.replaceText)

        self.btnreplace = QPushButton("replace all")
        self.btnreplace.setIcon(QIcon.fromTheme("gtk-find-and-replace"))
        self.btnreplace.clicked.connect(self.replaceTextAll)
        self.btnreplace.setToolTip("replace all")
        self.btnreplace.setFixedWidth(100)

        self.editLine = QLineEdit()
        self.editLine.setToolTip("edit and press ENTER")
        self.editLine.setStatusTip("edit and press ENTER")
        self.editLine.returnPressed.connect(self.updateCell)

        grid = QGridLayout()
        grid.setSpacing(1)
        grid.addWidget(self.editLine, 0, 0)
        grid.addWidget(self.findfield, 0, 1)
        grid.addWidget(self.replacefield, 0, 2)
        grid.addWidget(self.btnreplace, 0, 3)
        grid.addWidget(self.tableView, 1, 0, 1, 4)

        mywidget = QWidget()
        mywidget.setLayout(grid)
        self.setCentralWidget(mywidget)
        self.isChanged = False
        self.createActions()
        self.createMenuBar()
        self.setStyleSheet(stylesheet(self))
        self.readSettings()
        self.msg("Welcome to CSV Reader")

        if len(sys.argv) > 1:
            print(sys.argv[1])
            self.fileName = sys.argv[1]
            self.loadCsvOnOpen(self.fileName)
            self.msg(self.fileName + "loaded")
        else:
            self.msg("Ready")
            self.addRow()
            self.isChanged = False
 def write(self, path, value):
     settings_writer = QSettings(self.organization, self.application)
     settings_writer.setValue(self.name + SPECIAL_SAVER_SEPARATOR + path, value)
示例#3
0
 def saveSettings(self):
     QSettings().setValue("helpbrowser/size", self.size())
示例#4
0
 def __init__(self, _main_window):
     self.main_window = _main_window
     self.settings = QSettings(self.main_window.root + "/settings.ini",
                               QSettings.IniFormat)
     pass
示例#5
0
 def closeEvent(self, _):
     settings = QSettings()
     #save window geometry
     settings.setValue("CalculatorGeometry", self.saveGeometry())
示例#6
0
 def createSettings(self):
     self.setting = QSettings('MySoft', 'Beautyleg Downloader')
示例#7
0
 def toggleSyncCursor(self):
     QSettings().setValue(
         "musicview/sync_cursor",
         self.actionCollection.music_sync_cursor.isChecked())
示例#8
0
 def save_settings(self):
     settings = QSettings('Brunsgen International', 'glcube')
     settings.setValue('geometry', self.saveGeometry())
     settings.setValue('windowState', self.saveState())
        self.interactor.Start()

if __name__ == '__main__':

    # Qt::AA_ShareOpenGLContexts using QCoreApplication::setAttribute

    if QApplication.startingUp():
        app = QApplication(sys.argv)
    else:
        app = QCoreApplication.instance()
    app.setApplicationName("FourPaneViewer")
    app.setOrganizationName("KitWare")
    app.setOrganizationDomain("www.kitware.com")
    main_window = FourPaneViewer()
    main_window.setGeometry(0, 40, main_window.width(), main_window.height())
    main_window.show()
    main_window.initialize()
    if len(sys.argv) > 1:
        mySettings = QSettings()
        fileDir = mySettings.value(main_window.DEFAULT_DIR_KEY)
        main_window.loadFile(os.path.join(fileDir, defaultFiles[0]))
        main_window.loadSurface(os.path.join(fileDir, defaultFiles[1]))

    sys.exit(app.exec_())

# Local variables: #
# tab-width: 2 #
# python-indent: 2 #
# indent-tabs-mode: nil #
# End: #
示例#10
0
 def clear_settings(self):
     settings = QSettings('Brunsgen International', 'glcube')
     settings.setValue('geometry', None)
     settings.setValue('windowState', None)
示例#11
0
 def read_settings(self):
     settings = QSettings('Brunsgen International', 'glcube')
     geo = settings.value('geometry')
     if geo:
         self.restoreGeometry(geo)
         self.restoreState(settings.value('windowState'))
示例#12
0
    def __init__(self):
        super().__init__()
        self.app = QApplication.instance()
        # Initiate General-Layout
        self.app.setFont(QFont('Calibri', 10))
        QToolTip.setFont(QFont('SansSerif', 10))
        self.change_style('Fusion')
        self.dark_sheet = qdarkstyle.load_stylesheet_pyqt5()
        self.setWindowTitle('MNE-Pipeline HD')

        self.setCentralWidget(QWidget(self))
        self.general_layout = QGridLayout()
        self.centralWidget().setLayout(self.general_layout)

        # Set geometry to ratio of screen-geometry
        width, height = self.get_ratio_geometry(0.9)
        self.setGeometry(0, 0, width, height)

        # Initialize QThreadpool for creating separate Threads apart from GUI-Event-Loop later
        self.threadpool = QThreadPool()
        print(
            f'Multithreading with maximum {self.threadpool.maxThreadCount()} threads'
        )

        # Initiate attributes for Main-Window
        self.home_path = ''
        self.projects_path = ''
        self.current_project = ''
        self.subjects_dir = ''
        self.custom_pkg_path = ''
        self.mw_signals = MainWinSignals()
        self.module_err_dlg = None
        self.bt_dict = dict()
        self.all_modules = {'basic': {}, 'custom': {}}
        self.subject = None
        self.available_image_formats = ['.png', '.jpg', '.tiff']

        # Load QSettings (which are stored in the OS)
        # qsettings=<everything, that's OS-dependent>
        self.qsettings = QSettings()
        # Get the Home-Path (OS-dependent)
        self.get_home_path()
        # Load settings (which are stored as .json-file in home_path)
        # settings=<everything, that's OS-independent>
        self.settings = {}
        self.load_settings()
        # Get projects and current_project (need settings for this, thus after self.load_settings()
        self.get_projects()

        # Load CSV-Files for Functions & Parameters
        # Lists of functions separated in execution groups (mri_subject, subject, grand-average)
        self.pd_funcs = pd.read_csv(join(resources.__path__[0],
                                         'functions.csv'),
                                    sep=';',
                                    index_col=0)
        # Pandas-DataFrame for Parameter-Pipeline-Data (parameter-values are stored in main_win.pr.parameters)
        self.pd_params = pd.read_csv(join(resources.__path__[0],
                                          'parameters.csv'),
                                     sep=';',
                                     index_col=0)

        # Set a dramaturgically order for the groups (which applies for func_groups and parameter_groups)
        self.group_order = {
            'General': 0,
            'Raw': 1,
            'Preprocessing': 2,
            'Events': 3,
            'Epochs': 3,
            'Evoked': 3,
            'Time-Frequency': 4,
            'Forward': 5,
            'Inverse': 6,
            'Grand-Average': 7
        }

        # Import the basic- and custom-function-modules
        self.import_custom_modules()
        # Todo: Gruppen machen Probleme mit CustomFunctions!!!
        # Todo: verbessern, um Klarheit zu schaffen bei Unterteilung in Gruppen (über einzelne Module?)
        self.mri_funcs = self.pd_funcs[
            (self.pd_funcs['group'] == 'MRI-Preprocessing')
            & (self.pd_funcs['subject_loop'] == True)]
        self.file_funcs = self.pd_funcs[
            (self.pd_funcs['group'] != 'MRI-Preprocessing')
            & (self.pd_funcs['subject_loop'] == True)]
        self.ga_funcs = self.pd_funcs[
            (self.pd_funcs['subject_loop'] == False)
            & (self.pd_funcs['func_args'].str.contains('ga_group'))]
        self.other_funcs = self.pd_funcs[
            (self.pd_funcs['subject_loop'] == False)
            & ~(self.pd_funcs['func_args'].str.contains('ga_group'))]

        # Call project-class
        self.pr = Project(self, self.current_project)

        # Set logging
        logging.basicConfig(filename=join(self.pr.pscripts_path,
                                          '_pipeline.log'),
                            filemode='w')
        logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))

        # Needs restart, otherwise error, when setting later
        if self.get_setting('mne_backend') == 'pyvista':
            mne.viz.set_3d_backend('pyvista')
        else:
            mne.viz.set_3d_backend('mayavi')

        # Call window-methods
        self.init_menu()
        self.init_main_widget()
        self.init_toolbar()
        self.add_dock_windows()
示例#13
0
"""
Declare fbs application and various contextual variables so that it can be imported in other modules.
"""

from fbs_runtime.application_context.PyQt5 import ApplicationContext
from PyQt5.QtCore import QSettings, pyqtProperty, QResource
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QWidget
from json import JSONEncoder, dumps, loads, dump, load
from os.path import join

from resources import resources  #application resources defined in resources.qrc

app = ApplicationContext()
settings = QSettings(QSettings.IniFormat, QSettings.UserScope, "FOSSEE",
                     "Chemical-PFD")
version = app.build_settings['version']


def fileImporter(*file):
    # Helper function to fetch files from src/main/resources
    return app.get_resource(join(*file))


#set application stylesheet
with open(fileImporter("app.qss"), "r") as stylesheet:
    app.app.setStyleSheet(stylesheet.read())


class JSON_Encoder:
    """
示例#14
0
    def __init__(self, parent=None):
        super(Client, self).__init__(parent)

        self.networkSession = None
        self.blockSize = 0
        self.currentFortune = ''

        hostLabel = QLabel("&Server name:")
        portLabel = QLabel("S&erver port:")

        self.hostCombo = QComboBox()
        self.hostCombo.setEditable(True)

        name = QHostInfo.localHostName()
        if name != '':
            self.hostCombo.addItem(name)

            domain = QHostInfo.localDomainName()
            if domain != '':
                self.hostCombo.addItem(name + '.' + domain)

        if name != 'localhost':
            self.hostCombo.addItem('localhost')

        ipAddressesList = QNetworkInterface.allAddresses()

        for ipAddress in ipAddressesList:
            if not ipAddress.isLoopback():
                self.hostCombo.addItem(ipAddress.toString())

        for ipAddress in ipAddressesList:
            if ipAddress.isLoopback():
                self.hostCombo.addItem(ipAddress.toString())

        self.portLineEdit = QLineEdit()
        self.portLineEdit.setValidator(QIntValidator(1, 65535, self))

        hostLabel.setBuddy(self.hostCombo)
        portLabel.setBuddy(self.portLineEdit)

        self.statusLabel = QLabel("This examples requires that you run "
                                  "the Fortune Server example as well.")

        self.getFortuneButton = QPushButton("Get Fortune")
        self.getFortuneButton.setDefault(True)
        self.getFortuneButton.setEnabled(False)

        quitButton = QPushButton("Quit")

        buttonBox = QDialogButtonBox()
        buttonBox.addButton(self.getFortuneButton, QDialogButtonBox.ActionRole)
        buttonBox.addButton(quitButton, QDialogButtonBox.RejectRole)

        self.tcpSocket = QTcpSocket(self)

        self.hostCombo.editTextChanged.connect(self.enableGetFortuneButton)
        self.portLineEdit.textChanged.connect(self.enableGetFortuneButton)
        self.getFortuneButton.clicked.connect(self.requestNewFortune)
        quitButton.clicked.connect(self.close)
        self.tcpSocket.readyRead.connect(self.readFortune)
        self.tcpSocket.error.connect(self.displayError)

        mainLayout = QGridLayout()
        mainLayout.addWidget(hostLabel, 0, 0)
        mainLayout.addWidget(self.hostCombo, 0, 1)
        mainLayout.addWidget(portLabel, 1, 0)
        mainLayout.addWidget(self.portLineEdit, 1, 1)
        mainLayout.addWidget(self.statusLabel, 2, 0, 1, 2)
        mainLayout.addWidget(buttonBox, 3, 0, 1, 2)
        self.setLayout(mainLayout)

        self.setWindowTitle("Fortune Client")
        self.portLineEdit.setFocus()

        manager = QNetworkConfigurationManager()
        if manager.capabilities(
        ) & QNetworkConfigurationManager.NetworkSessionRequired:
            settings = QSettings(QSettings.UserScope, 'QtProject')
            settings.beginGroup('QtNetwork')
            id = settings.value('DefaultNetworkConfiguration')
            settings.endGroup()

            config = manager.configurationFromIdentifier(id)
            if config.state() & QNetworkConfiguration.Discovered == 0:
                config = manager.defaultConfiguration()

            self.networkSession = QNetworkSession(config, self)
            self.networkSession.opened.connect(self.sessionOpened)

            self.getFortuneButton.setEnabled(False)
            self.statusLabel.setText("Opening network session.")
            self.networkSession.open()
示例#15
0
# SEPARATION COLORS
ONES_AREA_COLOR = QColor.fromRgb(0, 128, 128)
ZEROS_AREA_COLOR = QColor.fromRgb(90, 9, 148)
SEPARATION_OPACITY = 0.2
SEPARATION_PADDING = .05  # Prozent

# PROTOCOL TABLE COLORS
SELECTED_ROW_COLOR = QColor.fromRgb(0, 0, 255)
DIFFERENCE_CELL_COLOR = QColor.fromRgb(255, 0, 0)

PROPERTY_FOUND_COLOR = QColor.fromRgb(0, 124, 0, 100)
PROPERTY_NOT_FOUND_COLOR = QColor.fromRgb(124, 0, 0, 100)

SEPARATION_ROW_HEIGHT = 30

SETTINGS = QSettings(QSettings.IniFormat, QSettings.UserScope, 'urh', 'urh')
PROJECT_FILE = "URHProject.xml"
DECODINGS_FILE = "decodings.txt"
FIELD_TYPE_SETTINGS = os.path.realpath(
    os.path.join(SETTINGS.fileName(), "..", "fieldtypes.xml"))

# DEVICE SETTINGS
DEFAULT_IP_USRP = "192.168.10.2"
DEFAULT_IP_RTLSDRTCP = "127.0.0.1"

# DECODING NAMES
DECODING_INVERT = "Invert"
DECODING_DIFFERENTIAL = "Differential Encoding"
DECODING_REDUNDANCY = "Remove Redundancy"
DECODING_DATAWHITENING = "Remove Data Whitening (CC1101)"
DECODING_CARRIER = "Remove Carrier"
示例#16
0
        self.settings.setValue('window/size', self.size())
        self.settings.setValue('window/pos', self.pos())
        event.accept()

    def dumpXML(self):
        browser = QFileDialog(self, "Pick a file to save the XML to.")
        browser.setAcceptMode(QFileDialog.AcceptSave)
        browser.setDefaultSuffix("xml")
        if browser.exec_() == QDialog.Accepted:
            exportXML(self._model, self.libraryPath,
                      browser.selectedFiles()[0])


if __name__ == '__main__':
    app = QApplication(sys.argv)
    settings = QSettings('h0m54r', 'desutunes')
    if 'inu' in sys.argv or 'inudesu' in sys.argv:
        mode = 'inudesu'
    elif 'neko' in sys.argv or 'nekodesu' in sys.argv:
        mode = 'nekodesu'
    else:
        mode = settings.value('mode', defaultValue='nekodesu')

    if mode == 'nekodesu':
        icon = QIcon("icons/png/icon.png")
        icon.addFile("icons/png/icon_small.png")
        database = 'desutunes.db'
    else:
        icon = QIcon("icons/png/inuicon.png")
        icon.addFile("icons/png/inuicon_small.png")
        database = 'inudesutunes.db'
示例#17
0
def get_settings():
    return QSettings('blender_launcher', 'settings')
    def __init__(self, iface, populateCompositionFz=None):
        QgsMapTool.__init__(self, iface.mapCanvas())

        self.iface = iface
        projectInstance = QgsProject.instance()
        self.projectLayoutManager = projectInstance.layoutManager()
        self.rubberband = None
        self.oldrubberband = None
        self.pressPos = None
        self.printer = QPrinter()
        self.mapitem = None
        self.populateCompositionFz = populateCompositionFz

        self.dialog = InstantPrintDialog(self.iface.mainWindow())
        self.dialogui = Ui_InstantPrintDialog()
        self.dialogui.setupUi(self.dialog)
        self.dialogui.addScale.setIcon(
            QIcon(":/images/themes/default/mActionAdd.svg"))
        self.dialogui.deleteScale.setIcon(
            QIcon(":/images/themes/default/symbologyRemove.svg"))
        self.dialog.hidden.connect(self.__onDialogHidden)
        self.exportButton = self.dialogui.buttonBox.addButton(
            self.tr("Export"), QDialogButtonBox.ActionRole)
        self.printButton = self.dialogui.buttonBox.addButton(
            self.tr("Print"), QDialogButtonBox.ActionRole)
        self.helpButton = self.dialogui.buttonBox.addButton(
            self.tr("Help"), QDialogButtonBox.HelpRole)
        self.dialogui.comboBox_fileformat.addItem(
            "PDF", self.tr("PDF Document (*.pdf);;"))
        self.dialogui.comboBox_fileformat.addItem(
            "JPG", self.tr("JPG Image (*.jpg);;"))
        self.dialogui.comboBox_fileformat.addItem(
            "BMP", self.tr("BMP Image (*.bmp);;"))
        self.dialogui.comboBox_fileformat.addItem(
            "PNG", self.tr("PNG Image (*.png);;"))
        self.iface.layoutDesignerOpened.connect(
            lambda view: self.__reloadLayouts())
        self.iface.layoutDesignerWillBeClosed.connect(self.__reloadLayouts)
        self.dialogui.comboBox_layouts.currentIndexChanged.connect(
            self.__selectLayout)
        self.dialogui.comboBox_scale.lineEdit().textChanged.connect(
            self.__changeScale)
        self.dialogui.comboBox_scale.scaleChanged.connect(self.__changeScale)
        self.exportButton.clicked.connect(self.__export)
        self.printButton.clicked.connect(self.__print)
        self.helpButton.clicked.connect(self.__help)
        self.dialogui.buttonBox.button(
            QDialogButtonBox.Close).clicked.connect(lambda: self.dialog.hide())
        self.dialogui.addScale.clicked.connect(self.add_new_scale)
        self.dialogui.deleteScale.clicked.connect(self.remove_scale)
        self.deactivated.connect(self.__cleanup)
        self.setCursor(Qt.OpenHandCursor)

        settings = QSettings()
        if settings.value("instantprint/geometry") is not None:
            self.dialog.restoreGeometry(
                settings.value("instantprint/geometry"))
        if settings.value("instantprint/scales") is not None:
            for scale in settings.value("instantprint/scales").split(";"):
                if scale:
                    self.retrieve_scales(scale)
        self.check_scales()
示例#19
0
 def __init__(self):
     self.settings = QSettings()
     self.name = "namemem"
示例#20
0

def chunks(l, n):
    for i in range(0, len(l), n):
        yield l[i:i + n]


QCoreApplication.setOrganizationName("QGIS")
QCoreApplication.setOrganizationDomain("qgis.org")
QCoreApplication.setApplicationName("QGIS3")

if len(sys.argv) == 1:
    print("Usage: ./scripts/mkuidefaults.py \"location_to_ini\"")
    sys.exit(1)

s = QSettings(sys.argv[1], QSettings.IniFormat)

ba = bytes(s.value("/UI/geometry"))
print

with open("src/app/ui_defaults.h", "w") as f:

    f.write("#ifndef UI_DEFAULTS_H\n#define UI_DEFAULTS_H\n" +
            "\nstatic const unsigned char defaultUIgeometry[] =\n{\n")

    for chunk in chunks(ba, 16):
        f.write('  {},\n'.format(
            ', '.join(map(hex, struct.unpack('B' * len(chunk), chunk)))))

    f.write("};\n\nstatic const unsigned char defaultUIstate[] =\n{\n")
示例#21
0
from PyQt5.QtGui import QIcon, QMouseEvent
from PyQt5.QtWidgets import (QAction, QApplication, QCheckBox, QComboBox,
        QDialog, QGridLayout, QGroupBox, QHBoxLayout, QLabel, QLineEdit,
        QMessageBox, QMenu, QPushButton, QSpinBox, QStyle, QSystemTrayIcon,
        QTextEdit, QVBoxLayout, QSizeGrip, QFileDialog)
from PyQt5.QtCore import (QThread, QTimer, QFile, QSettings,Qt, QPoint )
import resources_rc
from ui_main import Ui_PhotoFrame
from ui_settings import Ui_Settings
from PyQt5 import QtCore, QtGui, QtWidgets
import os
import random
import fnmatch

programSettings = QSettings(os.path.expanduser("~")+"/.config/photoframe/settings.conf", QSettings.NativeFormat)
MainWindowType = QtCore.Qt.Tool

def SettingsExist():
    if (programSettings.contains("SizeX") and
        programSettings.contains("SizeY") and
        programSettings.contains("directory") and
        programSettings.contains("PosX") and
        programSettings.contains("PosY") and
        programSettings.contains("UpdateInterval")):
        return True
    else:
        return False

def SettingsSave():
    programSettings.setValue("SizeX",window.geometry().width())
示例#22
0
    def __init__(self, parent=None, aw=None):
        super(backgroundDlg, self).__init__(parent, aw)
        self.setWindowTitle(
            QApplication.translate("Form Caption", "Profile Background", None))
        self.setModal(True)

        settings = QSettings()
        if settings.contains("BackgroundGeometry"):
            self.restoreGeometry(settings.value("BackgroundGeometry"))

        #TAB 1
        self.pathedit = QLineEdit(self.aw.qmc.backgroundpath)
        self.pathedit.setStyleSheet("background-color:'lightgrey';")
        self.pathedit.setReadOnly(True)
        self.pathedit.setFocusPolicy(Qt.NoFocus)
        self.filename = ""
        self.backgroundCheck = QCheckBox(
            QApplication.translate("CheckBox", "Show", None))
        self.backgroundDetails = QCheckBox(
            QApplication.translate("CheckBox", "Annotations", None))
        self.backgroundeventsflag = QCheckBox(
            QApplication.translate("CheckBox", "Events", None))
        self.backgroundDeltaETflag = QCheckBox()
        backgroundDeltaETflagLabel = QLabel(
            deltaLabelPrefix + QApplication.translate("Label", "ET", None))
        self.backgroundDeltaBTflag = QCheckBox()
        backgroundDeltaBTflagLabel = QLabel(
            deltaLabelPrefix + QApplication.translate("Label", "BT", None))
        self.backgroundETflag = QCheckBox(
            QApplication.translate("CheckBox", "ET", None))
        self.backgroundBTflag = QCheckBox(
            QApplication.translate("CheckBox", "BT", None))
        self.backgroundCheck.setChecked(self.aw.qmc.background)
        self.backgroundDetails.setChecked(self.aw.qmc.backgroundDetails)
        self.backgroundeventsflag.setChecked(self.aw.qmc.backgroundeventsflag)
        self.backgroundDeltaETflag.setChecked(self.aw.qmc.DeltaETBflag)
        self.backgroundDeltaBTflag.setChecked(self.aw.qmc.DeltaBTBflag)
        self.backgroundETflag.setChecked(self.aw.qmc.backgroundETcurve)
        self.backgroundBTflag.setChecked(self.aw.qmc.backgroundBTcurve)
        loadButton = QPushButton(QApplication.translate(
            "Button", "Load", None))
        loadButton.setFocusPolicy(Qt.NoFocus)
        delButton = QPushButton(
            QApplication.translate("Button", "Delete", None))
        delButton.setFocusPolicy(Qt.NoFocus)

        # connect the ArtisanDialog standard OK/Cancel buttons
        self.dialogbuttons.accepted.connect(self.accept)
        self.dialogbuttons.removeButton(
            self.dialogbuttons.button(QDialogButtonBox.Cancel))

        alignButton = QPushButton(
            QApplication.translate("Button", "Align", None))
        alignButton.setFocusPolicy(Qt.NoFocus)
        self.alignComboBox = QComboBox()
        alignnames = [
            QApplication.translate("Label", "CHARGE", None),
            QApplication.translate("Label", "DRY", None),
            QApplication.translate("Label", "FCs", None),
            QApplication.translate("Label", "FCe", None),
            QApplication.translate("Label", "SCs", None),
            QApplication.translate("Label", "SCe", None),
            QApplication.translate("Label", "DROP", None),
            QApplication.translate("Label", "ALL", None),
        ]
        self.alignComboBox.addItems(alignnames)
        self.alignComboBox.setCurrentIndex(self.aw.qmc.alignEvent)
        self.alignComboBox.currentIndexChanged.connect(
            self.changeAlignEventidx)
        loadButton.clicked.connect(self.load)
        alignButton.clicked.connect(self.timealign)

        self.speedSpinBox = QSpinBox()
        self.speedSpinBox.setAlignment(Qt.AlignRight)
        self.speedSpinBox.setRange(1, 90)
        self.speedSpinBox.setSingleStep(5)
        self.speedSpinBox.setValue(self.aw.qmc.backgroundmovespeed)
        self.xtcurvelabel = QLabel(
            QApplication.translate("Label", "Extra", None))
        self.xtcurveComboBox = QComboBox()
        self.xtcurveComboBox.setToolTip(
            QApplication.translate(
                "Tooltip", "For loaded backgrounds with extra devices only",
                None))
        self.xtcurveComboBox.setMinimumWidth(120)
        curvenames = [
            ""
        ]  # first entry is the empty one, no extra curve displayed
        for i in range(
                min(len(self.aw.qmc.extraname1B), len(self.aw.qmc.extraname2B),
                    len(self.aw.qmc.extratimexB))):
            curvenames.append("B" + str(2 * i + 3) + ": " +
                              self.aw.qmc.extraname1B[i])
            curvenames.append("B" + str(2 * i + 4) + ": " +
                              self.aw.qmc.extraname2B[i])
        self.xtcurveComboBox.addItems(curvenames)
        if self.aw.qmc.xtcurveidx < len(curvenames):
            self.xtcurveComboBox.setCurrentIndex(self.aw.qmc.xtcurveidx)
        self.xtcurveComboBox.currentIndexChanged.connect(self.changeXTcurveidx)
        self.upButton = QPushButton(
            QApplication.translate("Button", "Up", None))
        self.upButton.setFocusPolicy(Qt.NoFocus)
        self.downButton = QPushButton(
            QApplication.translate("Button", "Down", None))
        self.downButton.setFocusPolicy(Qt.NoFocus)
        self.leftButton = QPushButton(
            QApplication.translate("Button", "Left", None))
        self.leftButton.setFocusPolicy(Qt.NoFocus)
        self.rightButton = QPushButton(
            QApplication.translate("Button", "Right", None))
        self.rightButton.setFocusPolicy(Qt.NoFocus)
        self.backgroundCheck.clicked.connect(self.readChecks)
        self.backgroundDetails.clicked.connect(self.readChecks)
        self.backgroundeventsflag.clicked.connect(self.readChecks)
        self.backgroundDeltaETflag.clicked.connect(self.readChecks)
        self.backgroundDeltaBTflag.clicked.connect(self.readChecks)
        self.backgroundETflag.clicked.connect(self.readChecks)
        self.backgroundBTflag.clicked.connect(self.readChecks)
        delButton.clicked.connect(self.delete)
        self.upButton.clicked.connect(self.moveUp)
        self.downButton.clicked.connect(self.moveDown)
        self.leftButton.clicked.connect(self.moveLeft)
        self.rightButton.clicked.connect(self.moveRight)
        #TAB 2 EVENTS
        #table for showing events
        self.eventtable = QTableWidget()
        self.eventtable.setTabKeyNavigation(True)
        self.createEventTable()
        self.copyeventTableButton = QPushButton(
            QApplication.translate("Button", "Copy Table", None))
        self.copyeventTableButton.setToolTip(
            QApplication.translate(
                "Tooltip",
                "Copy table to clipboard, OPTION or ALT click for tabular text",
                None))
        self.copyeventTableButton.setFocusPolicy(Qt.NoFocus)
        self.copyeventTableButton.setMaximumSize(
            self.copyeventTableButton.sizeHint())
        self.copyeventTableButton.setMinimumSize(
            self.copyeventTableButton.minimumSizeHint())
        self.copyeventTableButton.clicked.connect(
            self.copyEventTabletoClipboard)
        #TAB 3 DATA
        #table for showing data
        self.datatable = QTableWidget()
        self.datatable.setTabKeyNavigation(True)
        self.createDataTable()
        self.copydataTableButton = QPushButton(
            QApplication.translate("Button", "Copy Table", None))
        self.copydataTableButton.setToolTip(
            QApplication.translate(
                "Tooltip",
                "Copy table to clipboard, OPTION or ALT click for tabular text",
                None))
        self.copydataTableButton.setFocusPolicy(Qt.NoFocus)
        self.copydataTableButton.setMaximumSize(
            self.copydataTableButton.sizeHint())
        self.copydataTableButton.setMinimumSize(
            self.copydataTableButton.minimumSizeHint())
        self.copydataTableButton.clicked.connect(self.copyDataTabletoClipboard)
        #TAB 4
        self.replayComboBox = QComboBox()
        replayVariants = [
            QApplication.translate("Label", "by time", None),
            QApplication.translate("Label", "by BT", None),
            QApplication.translate("Label", "by ET", None),
        ]
        self.replayComboBox.addItems(replayVariants)
        self.replayComboBox.setCurrentIndex(self.aw.qmc.replayType)
        self.replayComboBox.currentIndexChanged.connect(
            self.changeReplayTypeidx)

        self.backgroundReproduce = QCheckBox(
            QApplication.translate("CheckBox", "Playback Aid", None))
        self.backgroundReproduce.setChecked(self.aw.qmc.backgroundReproduce)
        self.backgroundReproduce.setFocusPolicy(Qt.NoFocus)
        self.backgroundReproduce.stateChanged.connect(self.setreproduce)
        self.backgroundReproduceBeep = QCheckBox(
            QApplication.translate("CheckBox", "Beep", None))
        self.backgroundReproduceBeep.setChecked(
            self.aw.qmc.backgroundReproduce)
        self.backgroundReproduceBeep.setFocusPolicy(Qt.NoFocus)
        self.backgroundReproduceBeep.stateChanged.connect(
            self.setreproduceBeep)
        self.backgroundPlaybackEvents = QCheckBox(
            QApplication.translate("CheckBox", "Playback Events", None))
        self.backgroundPlaybackEvents.setChecked(
            self.aw.qmc.backgroundPlaybackEvents)
        self.backgroundPlaybackEvents.setFocusPolicy(Qt.NoFocus)
        self.backgroundPlaybackEvents.stateChanged.connect(
            self.setplaybackevent)
        self.backgroundPlaybackDROP = QCheckBox(
            QApplication.translate("CheckBox", "Playback DROP", None))
        self.backgroundPlaybackDROP.setChecked(
            self.aw.qmc.backgroundPlaybackDROP)
        self.backgroundPlaybackDROP.setFocusPolicy(Qt.NoFocus)
        self.backgroundPlaybackDROP.stateChanged.connect(self.setplaybackdrop)
        etimelabel = QLabel(
            QApplication.translate("Label", "Text Warning", None))
        etimeunit = QLabel(QApplication.translate("Label", "sec", None))
        self.etimeSpinBox = QSpinBox()
        self.etimeSpinBox.setRange(1, 60)
        self.etimeSpinBox.setValue(self.aw.qmc.detectBackgroundEventTime)
        self.etimeSpinBox.valueChanged.connect(self.setreproduce)
        #LAYOUT MANAGERS
        movelayout = QGridLayout()
        movelayout.addWidget(self.upButton, 0, 1)
        movelayout.addWidget(self.leftButton, 1, 0)
        movelayout.addWidget(self.speedSpinBox, 1, 1)
        movelayout.addWidget(self.rightButton, 1, 2)
        movelayout.addWidget(self.downButton, 2, 1)
        movelayout.setSpacing(20)
        checkslayout1 = QHBoxLayout()
        checkslayout1.addStretch()
        checkslayout1.addWidget(self.backgroundCheck)
        checkslayout1.addSpacing(5)
        checkslayout1.addWidget(self.backgroundDetails)
        checkslayout1.addSpacing(5)
        checkslayout1.addWidget(self.backgroundeventsflag)
        checkslayout1.addSpacing(5)
        checkslayout1.addWidget(self.backgroundETflag)
        checkslayout1.addSpacing(5)
        checkslayout1.addWidget(self.backgroundBTflag)
        checkslayout1.addSpacing(5)
        checkslayout1.addWidget(self.backgroundDeltaETflag)
        checkslayout1.addWidget(backgroundDeltaETflagLabel)
        checkslayout1.addSpacing(5)
        checkslayout1.addWidget(self.backgroundDeltaBTflag)
        checkslayout1.addWidget(backgroundDeltaBTflagLabel)
        checkslayout1.addStretch()
        checkslayout1.setSpacing(15)
        layout = QGridLayout()
        layoutBoxedH = QHBoxLayout()
        layoutBoxedH.addStretch()
        layoutBoxedH.addLayout(movelayout)
        layoutBoxedH.addLayout(layout)
        layoutBoxedH.addStretch()
        layoutBoxed = QVBoxLayout()
        layoutBoxed.addStretch()
        layoutBoxed.addLayout(checkslayout1)
        layoutBoxed.addStretch()
        layoutBoxed.addLayout(layoutBoxedH)
        layoutBoxed.addStretch()
        alignButtonBoxed = QHBoxLayout()
        alignButtonBoxed.addWidget(self.xtcurvelabel)
        alignButtonBoxed.addWidget(self.xtcurveComboBox)
        alignButtonBoxed.addStretch()
        alignButtonBoxed.addWidget(alignButton)
        alignButtonBoxed.addWidget(self.alignComboBox)
        tab4content = QHBoxLayout()
        tab4content.addWidget(self.backgroundReproduce)
        tab4content.addSpacing(10)
        tab4content.addWidget(self.backgroundReproduceBeep)
        tab4content.addSpacing(10)
        tab4content.addWidget(etimelabel)
        tab4content.addWidget(self.etimeSpinBox)
        tab4content.addWidget(etimeunit)
        tab4content.addSpacing(20)
        tab4content.addStretch()
        tab4content.addWidget(self.backgroundPlaybackEvents)
        tab4content.addSpacing(10)
        tab4content.addWidget(self.backgroundPlaybackDROP)
        tab4content.addSpacing(10)
        tab4content.addWidget(self.replayComboBox)
        tab1layout = QVBoxLayout()
        tab1layout.addLayout(layoutBoxed)
        #        tab1layout.addStretch()
        tab1layout.addLayout(alignButtonBoxed)
        tab1layout.addLayout(tab4content)
        tab1layout.setContentsMargins(5, 0, 5, 0)  # left, top, right, bottom
        eventbuttonLayout = QHBoxLayout()
        eventbuttonLayout.addWidget(self.copyeventTableButton)
        eventbuttonLayout.addStretch()
        tab2layout = QVBoxLayout()
        tab2layout.addWidget(self.eventtable)
        tab2layout.addLayout(eventbuttonLayout)
        tab2layout.setContentsMargins(5, 0, 5, 0)  # left, top, right, bottom
        databuttonLayout = QHBoxLayout()
        databuttonLayout.addWidget(self.copydataTableButton)
        databuttonLayout.addStretch()
        tab3layout = QVBoxLayout()
        tab3layout.addWidget(self.datatable)
        tab3layout.addLayout(databuttonLayout)
        tab3layout.setContentsMargins(5, 0, 5, 0)  # left, top, right, bottom
        #tab layout
        tab1layout.setSpacing(5)
        self.TabWidget = QTabWidget()
        C1Widget = QWidget()
        C1Widget.setLayout(tab1layout)
        self.TabWidget.addTab(C1Widget,
                              QApplication.translate("Tab", "Config", None))
        C2Widget = QWidget()
        C2Widget.setLayout(tab2layout)
        self.TabWidget.addTab(C2Widget,
                              QApplication.translate("Tab", "Events", None))
        C3Widget = QWidget()
        C3Widget.setLayout(tab3layout)
        self.TabWidget.addTab(C3Widget,
                              QApplication.translate("Tab", "Data", None))
        buttonLayout = QHBoxLayout()
        buttonLayout.addWidget(loadButton)
        buttonLayout.addWidget(delButton)
        buttonLayout.addStretch()
        buttonLayout.addWidget(self.dialogbuttons)
        mainLayout = QVBoxLayout()
        mainLayout.addWidget(self.TabWidget)
        mainLayout.addWidget(self.pathedit)
        mainLayout.addLayout(buttonLayout)
        mainLayout.setContentsMargins(5, 10, 5, 5)  # left, top, right, bottom
        self.setLayout(mainLayout)
        if platform.system() == 'Windows':
            self.dialogbuttons.button(QDialogButtonBox.Ok)
        else:
            self.dialogbuttons.button(QDialogButtonBox.Ok).setFocus()
示例#23
0
    def __init__(self, parent=None, aw=None):
        super(calculatorDlg, self).__init__(parent, aw)
        self.setModal(True)
        self.setWindowTitle(
            QApplication.translate("Form Caption", "Roast Calculator", None))

        settings = QSettings()
        if settings.contains("CalculatorGeometry"):
            self.restoreGeometry(settings.value("CalculatorGeometry"))

        #RATE OF CHANGE
        self.result1 = QLabel(
            QApplication.translate("Label", "Enter two times along profile",
                                   None))
        self.result2 = QLabel()
        self.result2.setStyleSheet("background-color:'lightgrey';")
        startlabel = QLabel(
            QApplication.translate("Label", "Start (00:00)", None))
        endlabel = QLabel(QApplication.translate("Label", "End (00:00)", None))
        self.startEdit = QLineEdit()
        self.endEdit = QLineEdit()
        regextime = QRegExp(r"^[0-5][0-9]:[0-5][0-9]$")
        self.startEdit.setValidator(QRegExpValidator(regextime, self))
        self.endEdit.setValidator(QRegExpValidator(regextime, self))
        self.startEdit.editingFinished.connect(self.calculateRC)
        self.endEdit.editingFinished.connect(self.calculateRC)
        nevents = len(self.aw.qmc.specialevents)
        events_found = [QApplication.translate("ComboBox", "Event #0", None)]
        for i in range(nevents):
            events_found.append(
                QApplication.translate("ComboBox", "Event #{0}",
                                       None).format(str(i + 1)))
        self.eventAComboBox = QComboBox()
        self.eventAComboBox.addItems(events_found)
        self.eventAComboBox.currentIndexChanged.connect(self.calcEventRC)
        self.eventBComboBox = QComboBox()
        self.eventBComboBox.addItems(events_found)
        self.eventBComboBox.currentIndexChanged.connect(self.calcEventRC)
        #TEMPERATURE CONVERSION
        flabel = QLabel(QApplication.translate("Label", "Fahrenheit", None))
        clabel = QLabel(QApplication.translate("Label", "Celsius", None))
        self.faEdit = QLineEdit()
        self.ceEdit = QLineEdit()
        self.faEdit.setValidator(
            self.aw.createCLocaleDoubleValidator(-999999., 9999999., 2,
                                                 self.faEdit))
        self.ceEdit.setValidator(
            self.aw.createCLocaleDoubleValidator(-999999., 9999999., 2,
                                                 self.ceEdit))
        self.faEdit.editingFinished.connect(self.convertTempFtoC)
        self.ceEdit.editingFinished.connect(self.convertTempCtoF)
        #WEIGHT CONVERSION
        self.WinComboBox = QComboBox()
        self.WinComboBox.addItems(self.aw.qmc.weight_units)
        self.WinComboBox.setMaximumWidth(80)
        self.WinComboBox.setMinimumWidth(80)
        self.WoutComboBox = QComboBox()
        self.WoutComboBox.setMaximumWidth(80)
        self.WoutComboBox.setMinimumWidth(80)
        self.WoutComboBox.addItems(self.aw.qmc.weight_units)
        self.WoutComboBox.setCurrentIndex(2)
        self.WinEdit = QLineEdit()
        self.WoutEdit = QLineEdit()
        self.WinEdit.setMaximumWidth(70)
        self.WoutEdit.setMaximumWidth(70)
        #self.WinEdit.setMinimumWidth(60)
        #self.WoutEdit.setMinimumWidth(60)
        self.WinEdit.setValidator(
            self.aw.createCLocaleDoubleValidator(0., 99999., 4, self.WinEdit))
        self.WoutEdit.setValidator(
            self.aw.createCLocaleDoubleValidator(0., 99999., 4, self.WoutEdit))
        self.WinEdit.editingFinished.connect(self.convertWeightItoO)
        self.WoutEdit.editingFinished.connect(self.convertWeightOtoI)
        #VOLUME CONVERSION
        self.VinComboBox = QComboBox()
        volumeunits = [
            QApplication.translate("ComboBox", "liter", None),
            QApplication.translate("ComboBox", "gallon", None),
            QApplication.translate("ComboBox", "quart", None),
            QApplication.translate("ComboBox", "pint", None),
            QApplication.translate("ComboBox", "cup", None),
            QApplication.translate("ComboBox", "cm^3", None)
        ]
        self.VinComboBox.addItems(volumeunits)
        self.VinComboBox.setMaximumWidth(80)
        self.VinComboBox.setMinimumWidth(80)
        self.VoutComboBox = QComboBox()
        self.VoutComboBox.setMaximumWidth(80)
        self.VoutComboBox.setMinimumWidth(80)
        self.VoutComboBox.addItems(volumeunits)
        self.VoutComboBox.setCurrentIndex(4)
        self.VinEdit = QLineEdit()
        self.VoutEdit = QLineEdit()
        self.VinEdit.setMaximumWidth(70)
        self.VoutEdit.setMaximumWidth(70)
        #self.VinEdit.setMinimumWidth(60)
        #self.VoutEdit.setMinimumWidth(60)
        self.VinEdit.setValidator(
            self.aw.createCLocaleDoubleValidator(0., 99999., 4, self.VinEdit))
        self.VoutEdit.setValidator(
            self.aw.createCLocaleDoubleValidator(0., 99999., 4, self.VoutEdit))
        self.VinEdit.editingFinished.connect(self.convertVolumeItoO)
        self.VoutEdit.editingFinished.connect(self.convertVolumeOtoI)
        #EXTRACTION YIELD
        yieldlabel = QLabel(QApplication.translate("Label", "Yield (%)", None))
        groundslabel = QLabel(
            QApplication.translate("Label", "Grounds (g)", None))
        tdslabel = QLabel(QApplication.translate("Label", "TDS (%)", None))
        coffeelabel = QLabel(
            QApplication.translate("Label", "Coffee (g)", None))
        self.groundsEdit = QLineEdit()
        self.coffeeEdit = QLineEdit()
        self.tdsEdit = QLineEdit()
        self.yieldEdit = QLineEdit()
        self.yieldEdit.setReadOnly(True)
        self.groundsEdit.setValidator(
            self.aw.createCLocaleDoubleValidator(1., 999999., 2,
                                                 self.groundsEdit))
        self.coffeeEdit.setValidator(
            self.aw.createCLocaleDoubleValidator(1., 999999., 2,
                                                 self.coffeeEdit))
        self.tdsEdit.setValidator(
            self.aw.createCLocaleDoubleValidator(0., 100., 2, self.tdsEdit))
        for e in [self.groundsEdit, self.coffeeEdit, self.tdsEdit]:
            e.editingFinished.connect(self.calculateYield)
        #LAYOUTS
        #Rate of chage
        calrcLayout = QGridLayout()
        calrcLayout.addWidget(startlabel, 0, 0)
        calrcLayout.addWidget(endlabel, 0, 1)
        calrcLayout.addWidget(self.startEdit, 1, 0)
        calrcLayout.addWidget(self.endEdit, 1, 1)
        calrcLayout.addWidget(self.eventAComboBox, 2, 0)
        calrcLayout.addWidget(self.eventBComboBox, 2, 1)
        rclayout = QVBoxLayout()
        rclayout.addWidget(self.result1, 0)
        rclayout.addWidget(self.result2, 1)
        rclayout.addLayout(calrcLayout, 2)
        #temperature conversion
        tempLayout = QGridLayout()
        tempLayout.addWidget(flabel, 0, 0)
        tempLayout.addWidget(clabel, 0, 1)
        tempLayout.addWidget(self.faEdit, 1, 0)
        tempLayout.addWidget(self.ceEdit, 1, 1)
        #weight conversions
        weightLayout = QHBoxLayout()
        weightLayout.addWidget(self.WinComboBox)
        weightLayout.addWidget(self.WinEdit)
        weightLayout.addWidget(self.WoutEdit)
        weightLayout.addWidget(self.WoutComboBox)
        #volume conversions
        volumeLayout = QHBoxLayout()
        volumeLayout.addWidget(self.VinComboBox)
        volumeLayout.addWidget(self.VinEdit)
        volumeLayout.addWidget(self.VoutEdit)
        volumeLayout.addWidget(self.VoutComboBox)
        #extraction yield
        extractionLayout = QGridLayout()
        extractionLayout.addWidget(groundslabel, 0, 0)
        extractionLayout.addWidget(self.groundsEdit, 1, 0)
        extractionLayout.addWidget(coffeelabel, 0, 1)
        extractionLayout.addWidget(self.coffeeEdit, 1, 1)
        extractionLayout.addWidget(tdslabel, 0, 2)
        extractionLayout.addWidget(self.tdsEdit, 1, 2)
        extractionLayout.addWidget(yieldlabel, 0, 3)
        extractionLayout.addWidget(self.yieldEdit, 1, 3)

        RoCGroup = QGroupBox(
            QApplication.translate("GroupBox", "Rate of Change", None))
        RoCGroup.setLayout(rclayout)
        tempConvGroup = QGroupBox(
            QApplication.translate("GroupBox", "Temperature Conversion", None))
        tempConvGroup.setLayout(tempLayout)
        weightConvGroup = QGroupBox(
            QApplication.translate("GroupBox", "Weight Conversion", None))
        weightConvGroup.setLayout(weightLayout)
        volumeConvGroup = QGroupBox(
            QApplication.translate("GroupBox", "Volume Conversion", None))
        volumeConvGroup.setLayout(volumeLayout)
        extractionYieldGroup = QGroupBox(
            QApplication.translate("GroupBox", "Extraction Yield", None))
        extractionYieldGroup.setLayout(extractionLayout)
        #left side
        leftSide = QVBoxLayout()
        leftSide.addWidget(RoCGroup)
        #right side
        rightSide = QVBoxLayout()
        rightSide.addWidget(tempConvGroup)
        rightSide.addWidget(extractionYieldGroup)
        #rightSide.addStretch()
        topLayout = QHBoxLayout()
        topLayout.addLayout(leftSide)
        topLayout.addLayout(rightSide)
        botLayout = QHBoxLayout()
        botLayout.addWidget(weightConvGroup)
        botLayout.addWidget(volumeConvGroup)
        #main
        mainlayout = QVBoxLayout()
        mainlayout.addLayout(topLayout)
        mainlayout.addLayout(botLayout)
        self.setLayout(mainlayout)
示例#24
0
 def closeEvent(self, _):
     settings = QSettings()
     #save window geometry
     settings.setValue("BackgroundGeometry", self.saveGeometry())
 def read(self, path):
     settings_reader = QSettings(self.organization, self.application)
     return settings_reader.value(self.name + SPECIAL_SAVER_SEPARATOR + path)
示例#26
0
    def load(self, filename):

        if not self.isVisible():
            self.show()

        try:
            self.modelDescription = md = read_model_description(filename)
        except Exception as e:
            QMessageBox.warning(self, "Failed to load FMU", "Failed to load %s. %s" % (filename, e))
            return

        self.filename = filename
        platforms = supported_platforms(self.filename)

        self.variables.clear()
        self.selectedVariables.clear()
        self.startValues.clear()

        for v in md.modelVariables:
            self.variables[v.name] = v
            if v.causality == 'output':
                self.selectedVariables.add(v)

        fmi_types = []
        if md.coSimulation:
            fmi_types.append('Co-Simulation')
        if md.modelExchange:
            fmi_types.append('Model Exchange')

        # toolbar
        if md.defaultExperiment is not None:
            if md.defaultExperiment.stopTime is not None:
                self.stopTimeLineEdit.setText(str(md.defaultExperiment.stopTime))

        # actions
        can_compile = md.fmiVersion == '2.0' and 'c-code' in platforms
        self.ui.actionCompilePlatformBinary.setEnabled(can_compile)
        self.ui.actionCreateCMakeProject.setEnabled(can_compile)

        # variables view
        self.treeModel.setModelDescription(md)
        self.tableModel.setModelDescription(md)
        self.treeFilterModel.invalidate()
        self.tableFilterModel.invalidate()
        self.ui.treeView.reset()
        self.ui.tableView.reset()

        # settings page
        self.ui.fmiVersionLabel.setText(md.fmiVersion)
        self.ui.fmiTypeLabel.setText(', '.join(fmi_types))
        self.ui.platformsLabel.setText(', '.join(platforms))
        self.ui.modelNameLabel.setText(md.modelName)
        self.ui.descriptionLabel.setText(md.description)
        self.ui.numberOfContinuousStatesLabel.setText(str(md.numberOfContinuousStates))
        self.ui.numberOfEventIndicatorsLabel.setText(str(md.numberOfEventIndicators))
        self.ui.numberOfVariablesLabel.setText(str(len(md.modelVariables)))
        self.ui.generationToolLabel.setText(md.generationTool)
        self.ui.generationDateAndTimeLabel.setText(md.generationDateAndTime)

        self.fmiTypeComboBox.clear()
        self.fmiTypeComboBox.addItems(fmi_types)

        self.updateSimulationSettings()

        self.setCurrentPage(self.ui.settingsPage)

        self.ui.dockWidget.show()

        self.ui.actionSettings.setEnabled(True)
        self.ui.actionShowLog.setEnabled(True)
        self.ui.actionShowResults.setEnabled(False)

        can_simulate = platform in platforms

        self.ui.actionSimulate.setEnabled(can_simulate)
        self.stopTimeLineEdit.setEnabled(can_simulate)
        self.fmiTypeComboBox.setEnabled(can_simulate and len(fmi_types) > 1)
        self.ui.settingsGroupBox.setEnabled(can_simulate)

        settings = QSettings()
        recent_files = settings.value("recentFiles", defaultValue=[])
        recent_files = self.removeDuplicates([filename] + recent_files)

        # save the 10 most recent files
        settings.setValue('recentFiles', recent_files[:10])

        self.setWindowTitle("%s - FMPy" % os.path.normpath(filename))

        self.createGraphics()
示例#27
0
 def loadSettings(self):
     self.resize(QSettings().value("helpbrowser/size", QSize(400, 300),
                                   QSize))
示例#28
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        # save from garbage collection
        self.windows.append(self)

        # state
        self.filename = None
        self.result = None
        self.modelDescription = None
        self.variables = dict()
        self.selectedVariables = set()
        self.startValues = dict()
        self.simulationThread = None
        # self.progressDialog = None
        self.plotUpdateTimer = QTimer(self)
        self.plotUpdateTimer.timeout.connect(self.updatePlotData)
        self.curves = []

        # UI
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # use a smaller default font size on Mac and Linux
        if sys.platform in ['darwin', 'linux']:
            defaultFont = QFont()
            defaultFont.setPixelSize(11)
            QApplication.setFont(defaultFont)
            self.setStyleSheet("QWidget { font-size: 11px; }")

        self.ui.treeView.setAttribute(Qt.WA_MacShowFocusRect, False)
        self.ui.tableView.setAttribute(Qt.WA_MacShowFocusRect, False)
        self.ui.logTreeView.setAttribute(Qt.WA_MacShowFocusRect, False)

        # set the window size to 85% of the available space
        geo = QApplication.desktop().availableGeometry()
        width = min(geo.width() * 0.85, 1100.0)
        height = min(geo.height() * 0.85, 900.0)
        self.resize(width, height)

        # hide the variables
        self.ui.dockWidget.hide()

        # toolbar
        self.stopTimeLineEdit = QLineEdit("1")
        self.stopTimeLineEdit.setToolTip("Stop time")
        self.stopTimeLineEdit.setFixedWidth(50)
        self.stopTimeValidator = QDoubleValidator(self)
        self.stopTimeValidator.setBottom(0)
        self.stopTimeLineEdit.setValidator(self.stopTimeValidator)

        self.ui.toolBar.addWidget(self.stopTimeLineEdit)

        spacer = QWidget(self)
        spacer.setFixedWidth(10)
        self.ui.toolBar.addWidget(spacer)

        self.fmiTypeComboBox = QComboBox(self)
        self.fmiTypeComboBox.addItem("Co-Simulation")
        self.fmiTypeComboBox.setToolTip("FMI type")
        self.fmiTypeComboBox.setSizeAdjustPolicy(QComboBox.AdjustToContents)
        self.ui.toolBar.addWidget(self.fmiTypeComboBox)

        # disable widgets
        self.ui.actionSettings.setEnabled(False)
        self.ui.actionShowLog.setEnabled(False)
        self.ui.actionShowResults.setEnabled(False)
        self.ui.actionSimulate.setEnabled(False)
        self.ui.actionSaveResult.setEnabled(False)
        self.ui.actionSavePlottedResult.setEnabled(False)
        self.stopTimeLineEdit.setEnabled(False)
        self.fmiTypeComboBox.setEnabled(False)

        # hide the dock's title bar
        self.ui.dockWidget.setTitleBarWidget(QWidget())

        self.ui.dockWidgetContents.setMinimumWidth(500)

        self.tableModel = VariablesTableModel(self.selectedVariables, self.startValues)
        self.tableFilterModel = VariablesFilterModel()
        self.tableFilterModel.setSourceModel(self.tableModel)
        self.tableFilterModel.setFilterCaseSensitivity(Qt.CaseInsensitive)
        self.ui.tableView.setModel(self.tableFilterModel)

        self.treeModel = VariablesTreeModel(self.selectedVariables, self.startValues)
        self.treeFilterModel = VariablesFilterModel()
        self.treeFilterModel.setSourceModel(self.treeModel)
        self.treeFilterModel.setFilterCaseSensitivity(Qt.CaseInsensitive)
        self.ui.treeView.setModel(self.treeFilterModel)

        for i, (w, n) in enumerate(zip(VariablesModel.COLUMN_WIDTHS, VariablesModel.COLUMN_NAMES)):
            self.ui.treeView.setColumnWidth(i, w)
            self.ui.tableView.setColumnWidth(i, w)

            if n in ['Value Reference', 'Initial', 'Causality', 'Variability']:
                self.ui.treeView.setColumnHidden(i, True)
                self.ui.tableView.setColumnHidden(i, True)

        # populate the recent files list
        settings = QSettings()
        recent_files = settings.value("recentFiles", defaultValue=[])
        recent_files = self.removeDuplicates(recent_files)
        vbox = QVBoxLayout()

        if recent_files:
            added = set()
            for file in recent_files[:5]:
                link = QLabel('<a href="%s" style="text-decoration: none">%s</a>' % (file, os.path.basename(file)))
                link.setToolTip(file)
                link.linkActivated.connect(self.load)
                vbox.addWidget(link)
                added.add(file)

        self.ui.recentFilesGroupBox.setLayout(vbox)
        self.ui.recentFilesGroupBox.setVisible(len(recent_files) > 0)

        # settings page
        self.inputFileMenu = QMenu()
        self.inputFileMenu.addAction("New input file...", self.createInputFile)
        self.inputFileMenu.addSeparator()
        self.inputFileMenu.addAction("Show in Explorer", self.showInputFileInExplorer)
        self.inputFileMenu.addAction("Open in default application", self.openInputFile)
        self.ui.selectInputButton.setMenu(self.inputFileMenu)

        # log page
        self.log = Log(self)
        self.logFilterModel = LogMessagesFilterProxyModel(self)
        self.logFilterModel.setSourceModel(self.log)
        self.logFilterModel.setFilterCaseSensitivity(Qt.CaseInsensitive)
        self.ui.logTreeView.setModel(self.logFilterModel)
        self.ui.clearLogButton.clicked.connect(self.log.clear)

        self.log.numberOfDebugMessagesChanged.connect(lambda n: self.ui.showDebugMessagesButton.setText(str(n)))
        self.log.numberOfInfoMessagesChanged.connect(lambda n: self.ui.showInfoMessagesButton.setText(str(n)))
        self.log.numberOfWarningMessagesChanged.connect(lambda n: self.ui.showWarningMessagesButton.setText(str(n)))
        self.log.numberOfErrorMessagesChanged.connect(lambda n: self.ui.showErrorMessagesButton.setText(str(n)))

        self.ui.logFilterLineEdit.textChanged.connect(self.logFilterModel.setFilterFixedString)

        self.ui.showDebugMessagesButton.toggled.connect(self.logFilterModel.setShowDebugMessages)
        self.ui.showInfoMessagesButton.toggled.connect(self.logFilterModel.setShowInfoMessages)
        self.ui.showWarningMessagesButton.toggled.connect(self.logFilterModel.setShowWarningMessages)
        self.ui.showErrorMessagesButton.toggled.connect(self.logFilterModel.setShowErrorMessages)

        # context menu
        self.contextMenu = QMenu()
        self.actionExpandAll = self.contextMenu.addAction("Expand all")
        self.actionExpandAll.triggered.connect(self.ui.treeView.expandAll)
        self.actionCollapseAll = self.contextMenu.addAction("Collapse all")
        self.actionCollapseAll.triggered.connect(self.ui.treeView.collapseAll)
        self.contextMenu.addSeparator()
        self.actionCopyVariableName = self.contextMenu.addAction("Copy Variable Name", self.copyVariableName)
        self.actionCopyValueReference = self.contextMenu.addAction("Copy Value Reference", self.copyValueReference)
        self.contextMenu.addSeparator()
        self.actionEditTable = self.contextMenu.addAction("Edit Table", self.editTable)
        self.contextMenu.addSeparator()
        self.columnsMenu = self.contextMenu.addMenu('Columns')
        for column in ['Value Reference', 'Initial', 'Causality', 'Variability']:
            action = self.columnsMenu.addAction(column)
            action.setCheckable(True)
            action.toggled.connect(lambda show, col=column: self.showColumn(col, show))

        # file menu
        self.ui.actionExit.triggered.connect(QApplication.closeAllWindows)
        self.ui.actionLoadStartValues.triggered.connect(self.loadStartValues)
        self.ui.actionReload.triggered.connect(lambda: self.load(self.filename))
        self.ui.actionSaveChanges.triggered.connect(self.saveChanges)

        # help menu
        self.ui.actionOpenFMI1SpecCS.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://svn.modelica.org/fmi/branches/public/specifications/v1.0/FMI_for_CoSimulation_v1.0.1.pdf')))
        self.ui.actionOpenFMI1SpecME.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://svn.modelica.org/fmi/branches/public/specifications/v1.0/FMI_for_ModelExchange_v1.0.1.pdf')))
        self.ui.actionOpenFMI2Spec.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://svn.modelica.org/fmi/branches/public/specifications/v2.0/FMI_for_ModelExchange_and_CoSimulation_v2.0.pdf')))
        self.ui.actionOpenTestFMUs.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://github.com/modelica/fmi-cross-check/tree/master/fmus')))
        self.ui.actionOpenWebsite.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://github.com/CATIA-Systems/FMPy')))
        self.ui.actionShowReleaseNotes.triggered.connect(lambda: QDesktopServices.openUrl(QUrl('https://fmpy.readthedocs.io/en/latest/changelog/')))
        self.ui.actionCompilePlatformBinary.triggered.connect(self.compilePlatformBinary)
        self.ui.actionCreateCMakeProject.triggered.connect(self.createCMakeProject)

        # filter menu
        self.filterMenu = QMenu()
        self.filterMenu.addAction(self.ui.actionFilterInputs)
        self.filterMenu.addAction(self.ui.actionFilterOutputs)
        self.filterMenu.addAction(self.ui.actionFilterParameters)
        self.filterMenu.addAction(self.ui.actionFilterCalculatedParameters)
        self.filterMenu.addAction(self.ui.actionFilterIndependentVariables)
        self.filterMenu.addAction(self.ui.actionFilterLocalVariables)
        self.ui.filterToolButton.setMenu(self.filterMenu)

        # status bar
        self.statusIconLabel = ClickableLabel(self)
        self.statusIconLabel.setStyleSheet("QLabel { margin-left: 5px; }")
        self.statusIconLabel.clicked.connect(lambda: self.setCurrentPage(self.ui.logPage))
        self.ui.statusBar.addPermanentWidget(self.statusIconLabel)

        self.statusTextLabel = ClickableLabel(self)
        self.statusTextLabel.setMinimumWidth(10)
        self.statusTextLabel.clicked.connect(lambda: self.setCurrentPage(self.ui.logPage))
        self.ui.statusBar.addPermanentWidget(self.statusTextLabel)

        self.ui.statusBar.addPermanentWidget(QWidget(self), 1)  # spacer

        self.simulationProgressBar = QProgressBar(self)
        self.simulationProgressBar.setFixedHeight(18)
        self.ui.statusBar.addPermanentWidget(self.simulationProgressBar)
        self.simulationProgressBar.setVisible(False)

        # connect signals and slots
        self.ui.actionNewWindow.triggered.connect(self.newWindow)
        self.ui.openButton.clicked.connect(self.open)
        self.ui.actionOpen.triggered.connect(self.open)
        self.ui.actionSaveResult.triggered.connect(self.saveResult)
        self.ui.actionSavePlottedResult.triggered.connect(lambda: self.saveResult(plotted=True))
        self.ui.actionSimulate.triggered.connect(self.startSimulation)
        self.ui.actionSettings.triggered.connect(lambda: self.setCurrentPage(self.ui.settingsPage))
        self.ui.actionShowLog.triggered.connect(lambda: self.setCurrentPage(self.ui.logPage))
        self.ui.actionShowResults.triggered.connect(lambda: self.setCurrentPage(self.ui.resultPage))
        self.fmiTypeComboBox.currentTextChanged.connect(self.updateSimulationSettings)
        self.ui.solverComboBox.currentTextChanged.connect(self.updateSimulationSettings)
        self.variableSelected.connect(self.updatePlotLayout)
        self.variableDeselected.connect(self.updatePlotLayout)
        self.tableModel.variableSelected.connect(self.selectVariable)
        self.tableModel.variableDeselected.connect(self.deselectVariable)
        self.treeModel.variableSelected.connect(self.selectVariable)
        self.treeModel.variableDeselected.connect(self.deselectVariable)
        self.ui.filterLineEdit.textChanged.connect(self.treeFilterModel.setFilterFixedString)
        self.ui.filterLineEdit.textChanged.connect(self.tableFilterModel.setFilterFixedString)
        self.ui.filterToolButton.toggled.connect(self.treeFilterModel.setFilterByCausality)
        self.ui.filterToolButton.toggled.connect(self.tableFilterModel.setFilterByCausality)
        self.log.currentMessageChanged.connect(self.setStatusMessage)
        self.ui.selectInputButton.clicked.connect(self.selectInputFile)
        self.ui.actionShowAboutDialog.triggered.connect(self.showAboutDialog)

        if os.name == 'nt':
            self.ui.actionCreateDesktopShortcut.triggered.connect(self.createDesktopShortcut)
            self.ui.actionAddFileAssociation.triggered.connect(self.addFileAssociation)
        else:
            self.ui.actionCreateDesktopShortcut.setEnabled(False)
            self.ui.actionAddFileAssociation.setEnabled(False)

        self.ui.tableViewToolButton.toggled.connect(lambda show: self.ui.variablesStackedWidget.setCurrentWidget(self.ui.tablePage if show else self.ui.treePage))

        for model in [self.treeFilterModel, self.tableFilterModel]:
            self.ui.actionFilterInputs.triggered.connect(model.setFilterInputs)
            self.ui.actionFilterOutputs.triggered.connect(model.setFilterOutputs)
            self.ui.actionFilterParameters.triggered.connect(model.setFilterParameters)
            self.ui.actionFilterCalculatedParameters.triggered.connect(model.setFilterCalculatedParameters)
            self.ui.actionFilterIndependentVariables.triggered.connect(model.setFilterIndependentVariables)
            self.ui.actionFilterLocalVariables.triggered.connect(model.setFilterLocalVariables)

        self.ui.treeView.customContextMenuRequested.connect(self.showContextMenu)
        self.ui.tableView.customContextMenuRequested.connect(self.showContextMenu)
示例#29
0
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import sys
import markups
import markups.common
from os.path import dirname, exists, join

from PyQt5.QtCore import QByteArray, QLocale, QSettings, QStandardPaths
from PyQt5.QtGui import QFont

app_version = "7.1.0 (Git)"

settings = QSettings('ReText project', 'ReText')

if not str(settings.fileName()).endswith('.conf'):
    # We are on Windows probably
    settings = QSettings(QSettings.IniFormat, QSettings.UserScope,
                         'ReText project', 'ReText')

datadirs = []


def initializeDataDirs():
    assert not datadirs

    if '__file__' in locals():
        datadirs.append(dirname(dirname(__file__)))
示例#30
0
def print_(doc, filename=None, widget=None):
    """Prints the popplerqt5.Poppler.Document.

    The filename is used in the dialog and print job name.
    If the filename is not given, it defaults to a translation of "PDF Document".
    The widget is a widget to use as parent for the print dialog etc.

    """
    # Decide how we will print.
    # on Windows and Mac OS X a print command must be specified, otherwise
    # we'll use raster printing
    s = QSettings()
    s.beginGroup("helper_applications")
    cmd = s.value("printcommand", "", str)
    use_dialog = s.value("printcommand/dialog", False, bool)
    resolution = s.value("printcommand/dpi", 300, int)
    linux_lpr = False

    if os.name != 'nt' and not sys.platform.startswith('darwin'):
        # we're probably on Linux
        if not cmd:
            cmd = fileprinter.lprCommand()
            if cmd:
                linux_lpr = True
        elif cmd.split('/')[-1] in fileprinter.lpr_commands:
            linux_lpr = True

    print_file = filename
    title = os.path.basename(filename) if filename else _("PDF Document")

    if widget:
        try:
            printer = _printers[widget]
        except KeyError:
            printer = _printers[widget] = QPrinter()
        else:
            printer.setCopyCount(1)
    else:
        printer = QPrinter()

    printer.setDocName(title)
    printer.setPrintRange(QPrinter.AllPages)

    if linux_lpr or use_dialog or not cmd:
        dlg = QPrintDialog(printer, widget)
        dlg.setMinMax(1, doc.numPages())
        dlg.setOption(QPrintDialog.PrintToFile, False)
        dlg.setWindowTitle(
            app.caption(_("Print {filename}").format(filename=title)))

        result = dlg.exec_()
        if widget:
            dlg.deleteLater()  # because it has a parent
        if not result:
            return  # cancelled

    if linux_lpr or '$ps' in cmd:
        # make a PostScript file with the desired paper size
        ps = QTemporaryFile()
        if ps.open() and qpopplerview.printer.psfile(doc, printer, ps):
            ps.close()
            print_file = ps.fileName()
    elif cmd:
        if printer.printRange() != QPrinter.AllPages:
            cmd = None  # we can't cut out pages from a PDF file
        elif '$pdf' not in cmd:
            cmd += ' $pdf'

    command = []
    if linux_lpr:
        # let all converted pages print
        printer.setPrintRange(QPrinter.AllPages)
        command = fileprinter.printCommand(cmd, printer, ps.fileName())
    elif cmd and print_file:
        for arg in helpers.shell_split(cmd):
            if arg in ('$ps', '$pdf'):
                command.append(print_file)
            else:
                arg = arg.replace('$printer', printer.printerName())
                command.append(arg)
    if command:
        if subprocess.call(command):
            QMessageBox.warning(
                widget, _("Printing Error"),
                _("Could not send the document to the printer."))
        return
    else:
        # Fall back printing of rendered raster images.
        # It is unsure if the Poppler ArthurBackend ever will be ready for
        # good rendering directly to a painter, so we'll fall back to using
        # raster images.

        p = Printer()
        p.setDocument(doc)
        p.setPrinter(printer)
        p.setResolution(resolution)

        d = QProgressDialog()
        d.setModal(True)
        d.setMinimumDuration(0)
        d.setRange(0, len(p.pageList()) + 1)
        d.canceled.connect(p.abort)

        def progress(num, total, page):
            d.setValue(num)
            d.setLabelText(
                _("Printing page {page} ({num} of {total})...").format(
                    page=page, num=num, total=total))

        def finished():
            p.deleteLater()
            d.deleteLater()
            d.hide()
            if not p.success and not p.aborted():
                QMessageBox.warning(
                    widget, _("Printing Error"),
                    _("Could not send the document to the printer."))

        p.finished.connect(finished)
        p.printing.connect(progress)
        p.start()