Example #1
0
class AllLogsPage(QObject):
    def __init__(self):
        super().__init__()
        self.allLogsModel = ""
        self.settings = QSettings('CAIO', 'Preferences')
        self.initialRun = True
        # self.dbAllLog = QSqlDatabase.addDatabase("QSQLITE")
        # self.dbAllLog.setDatabaseName("caio.db")
        # self.dbAllLog.open()

        # AUTO REFRESH
        timer = QTimer(self)
        timer.start(1000)
        timer.timeout.connect(lambda: self.setLogs())

    def setLogs(self):
        isLogChanged = self.settings.value('logChanged')
        if isLogChanged == 1 or self.initialRun:
            self.allLogsModel = QSqlQueryModel()
            dbAllLog = QSqlDatabase.addDatabase("QSQLITE")
            dbAllLog.setDatabaseName("caio.db")
            dbAllLog.open()
            self.allLogsModel.setQuery(
                "select * from allLogs order by id desc ", dbAllLog)
            dbAllLog.close()
            print(self.allLogsModel)
            self.settings.setValue('logChanged', 0)
            QSqlDatabase.removeDatabase("QSQLITE")
            self.initialRun = False
Example #2
0
def load_translations(app):
    """Load translations

    .. note:: Init ui/locale setting
    """
    # Load locale setting if exists
    # English is the default language
    app_settings = QSettings()
    locale_name = app_settings.value("ui/locale", "en")

    # site-packages/PySide2/Qt/translations
    lib_info = QLibraryInfo.location(QLibraryInfo.TranslationsPath)

    # Qt translations
    qt_translator = QTranslator(app)
    if qt_translator.load("qt_" + locale_name, directory=lib_info):
        app.installTranslator(qt_translator)

    # qtbase_translator = QTranslator(app)
    # if qtbase_translator.load("qtbase_" + locale_name, directory=lib_info):
    #     app.installTranslator(qtbase_translator)

    # App translations
    app_translator = QTranslator(app)
    if app_translator.load(locale_name, directory=cm.DIR_TRANSLATIONS):
        app.installTranslator(app_translator)
    else:
        # Init setting
        app_settings.setValue("ui/locale", "en")
Example #3
0
class CForm(QDialog):
    def __init__(self, parent=None):
        super(CForm, self).__init__(parent)
        self.val = None
        self.le = QLineEdit()
        self.le.setObjectName(u"Default")
        self.settings = QSettings("dataset", "xxx")
        le = self.settings.value("le", "default")
        self.le.setText(le)
        self.le.textChanged.connect(self.contributor_changed)
        self.pb = QPushButton()
        self.pb.setObjectName("Enter")
        self.pb.setText("Enter")
        layout = QFormLayout()
        layout.addWidget(self.le)
        layout.addWidget(self.pb)
        self.setLayout(layout)
        self.pb.clicked.connect(lambda: self.buttonClick())
        self.setWindowTitle("Enter Contributor's Name")

    @QtCore.Slot()
    def contributor_changed(self):
        self.settings.setValue("le", self.le.text())
        self.settings.setValue("contributor", self.le.text())
        self.val = self.le.text()
        print(self.val)

    def buttonClick(self):
        print(self.val)
        self.close()
Example #4
0
 def saveLastFits(self):
     if self.tedaCommandLine.ignoreSettings:
         return
     settings = QSettings()
     settings.beginGroup("Files")
     settings.setValue("lastFile", self.filename)
     settings.endGroup()
Example #5
0
    def _browse(self):
        """Open a dialog box to set the data file

        The file is opened and we show an alert if annotations are detected.
        """
        # Reload last directory used
        app_settings = QSettings()
        last_directory = app_settings.value("last_directory", QDir.homePath())

        filepath, filetype = QFileDialog.getOpenFileName(
            self,
            self.tr("Open a file"),
            last_directory,
            self.tr(
                "VCF file (*.vcf *.vcf.gz);; CSV file (*.csv *.tsv *.txt)"),
        )

        if filepath:
            # Display and save directory
            self.file_path_edit.setText(filepath)
            app_settings.setValue("last_directory", os.path.dirname(filepath))

            if "vcf" in filepath:
                # TODO: detect annotations on other tyes of files...
                annotation_type = detect_vcf_annotation(filepath)
                if annotation_type:
                    text = self.tr(
                        "<b>%s annotations detected!</b>") % annotation_type
                else:
                    text = self.tr(
                        "<b>No annotation data has been detected!</b>")

                self.anotation_detect_label.setText(text)
Example #6
0
    def removeRecentProjectFile(self, projectFile):
        if not isinstance(projectFile, (QUrl, pyCompatibility.basestring)):
            raise TypeError("Unexpected data type: {}".format(
                projectFile.__class__))
        if isinstance(projectFile, QUrl):
            projectFileNorm = projectFile.toLocalFile()
            if not projectFileNorm:
                projectFileNorm = projectFile.toString()
        else:
            projectFileNorm = QUrl(projectFile).toLocalFile()
            if not projectFileNorm:
                projectFileNorm = QUrl.fromLocalFile(projectFile).toLocalFile()

        projects = self._recentProjectFiles()

        # remove duplicates while preserving order
        from collections import OrderedDict
        uniqueProjects = OrderedDict.fromkeys(projects)
        projects = list(uniqueProjects)
        # remove previous usage of the value
        if projectFileNorm not in uniqueProjects:
            return

        projects.remove(projectFileNorm)

        settings = QSettings()
        settings.beginGroup("RecentFiles")
        size = settings.beginWriteArray("Projects")
        for i, p in enumerate(projects):
            settings.setArrayIndex(i)
            settings.setValue("filepath", p)
        settings.endArray()
        settings.sync()

        self.recentProjectFilesChanged.emit()
Example #7
0
 def restore_settings(self):
     """Restore saved settings prior session."""
     settings = QSettings()
     self.restoreGeometry(settings.value('MainWindow/Geometry', b''))
     self.restoreState(settings.value('MainWindow/State', b''))
     self.current_configuration = (settings.value('LastPatchFile', b''))
     settings.setValue('LastPatchFile', '')
Example #8
0
 def save(self):
     self.view.save()
     settings = QSettings()
     settings.beginGroup(self.__class__.__name__)
     geom = self.saveGeometry()
     settings.setValue('geom', geom)
     settings.endGroup()
Example #9
0
    def export(self):
        settings = QSettings()
        filename = QFileDialog.getSaveFileName(self,
                                               self.tr('Export metadata'),
                                               settings.value('save_folder'),
                                               self.tr('CSV files (*.csv)'))[0]
        if not filename:
            return
        if not filename.endswith('.csv'):
            filename += '.csv'
        settings.setValue('save_folder', QFileInfo(filename).absolutePath())

        rows = self.table_widget.rowCount()
        cols = self.table_widget.columnCount()
        table = [[None for _ in range(cols)] for __ in range(rows)]
        for i in range(rows):
            for j in range(cols):
                item = self.table_widget.item(i, j)
                if item is not None:
                    table[i][j] = item.text()
        with open(filename, 'w') as file:
            writer = csv.writer(file)
            writer.writerow(self.table_headers)
            writer.writerows(table)
        self.info_message.emit(self.tr('Table contents exported to disk'))
Example #10
0
def mainwin_recentfiles():
    MainWindow.dict_modified = False
    MainWindow.max_recent_files = 2

    # resetting recent files
    settings = QSettings('PMA', 'OneHandTextEdit')
    settings.setValue('recent_files', [])

    src = 'test_words.txt'
    dest = 'test_out.json'
    words = ["may", "cat"]

    with open(src, 'w') as f:
        for word in words:
            f.write("%s\n" % word)

    create_regex_map([src], [True], dest)

    with open(dest) as f:
        regex_map = json.load(f)
    yield MainWindow(regex_map, dict_src=dest)

    os.remove(src)
    os.remove(dest)
    os.remove('document1.txt')
    os.remove('document2.txt')
    os.remove('document3.txt')
    # resetting recent files
    settings = QSettings('PMA', 'OneHandTextEdit')
    settings.setValue('recent_files', [])
Example #11
0
def _rename_step(workflow_location, old_name, new_name, new_src_uri):
    updated = False
    workflow_conf_location = os.path.join(workflow_location,
                                          DEFAULT_WORKFLOW_PROJECT_FILENAME)
    workflow_conf = QSettings(workflow_conf_location, QSettings.IniFormat)

    workflow_conf.beginGroup('nodes')
    node_count = workflow_conf.beginReadArray('nodelist')

    name_indices = []
    for i in range(node_count):
        workflow_conf.setArrayIndex(i)
        name = workflow_conf.value('name')
        if name == old_name:
            name_indices.append(i)

    workflow_conf.endArray()
    workflow_conf.beginWriteArray('nodelist')

    for i in range(node_count):
        workflow_conf.setArrayIndex(i)
        if i in name_indices:
            workflow_conf.setValue('name', new_name)
            workflow_conf.setValue('source_uri', new_src_uri)
            updated = True

    workflow_conf.endArray()
    workflow_conf.endGroup()

    return updated
Example #12
0
 def closeEvent(self, event):
     settings = QSettings()
     settings.beginGroup('main_window')
     settings.setValue('geometry', self.saveGeometry())
     settings.setValue('state', self.saveState())
     settings.endGroup()
     super(MainWindow, self).closeEvent(event)
Example #13
0
    def clear_recent_files(self):
        """Clears the recent files setting and updates menus across all main windows."""
        settings = QSettings('PMA', 'OneHandTextEdit')
        settings.setValue('recent_files', [])

        for widget in QApplication.topLevelWidgets():
            if isinstance(widget, MainWindow):
                widget.update_recent_file_actions()
Example #14
0
    def save(self) -> None:
        settings = QSettings(self.config_path)

        settings.beginWriteArray("downloads")
        for i in range(len(self.downloads)):
            settings.setArrayIndex(i)
            settings.setValue("download", Download.pack(self.downloads[i]))
        settings.endArray()
Example #15
0
    def mkdir(self, folder: str):
        assert folder
        assert "/" not in folder

        settings = QSettings()
        settings.beginGroup(f"apps/_folder/{folder}")
        settings.setValue("_dir", "true")
        self.app_change.emit()
Example #16
0
def main():
    """The main routine."""
    # Define the names of the organization and the application
    # The value is used by the QSettings class when it is constructed using
    # the empty constructor. This saves having to repeat this information
    # each time a QSettings object is created.
    # The default scope is QSettings::UserScope
    QCoreApplication.setOrganizationName("labsquare")
    QCoreApplication.setApplicationName("cutevariant")
    QCoreApplication.setApplicationVersion(__version__)

    # Process command line arguments
    app = QApplication(sys.argv)
    process_arguments(app)

    # Load app styles
    load_styles(app)

    # # Uncomment those line to clear settings
    # settings = QSettings()
    # settings.clear()

    # Set icons set
    setFontPath(cm.FONT_FILE)

    # Translations
    load_translations(app)

    # debug settings
    # from cutevariant.gui.settings import *
    # w = SettingsWidget()
    # w.show()

    # Splash screen
    splash = QSplashScreen()
    splash.setPixmap(QPixmap(cm.DIR_ICONS + "splash.png"))
    splash.showMessage(f"Version {__version__}")
    splash.show()
    app.processEvents()

    #  Drop settings if old version
    settings = QSettings()
    settings_version = settings.value("version", None)
    if settings_version is None or parse_version(
            settings_version) < parse_version(__version__):
        settings.clear()
        settings.setValue("version", __version__)

    # Display
    w = MainWindow()

    # STYLES = cm.DIR_STYLES + "frameless.qss"
    # with open(STYLES,"r") as file:
    #     w.setStyleSheet(file.read())

    w.show()
    splash.finish(w)
    app.exec_()
Example #17
0
 def set_video_path(self):
     """ update the save path for videos """
     settings = QSettings()
     res = QFileDialog.getExistingDirectory(
         self, "Select default video directory", ".")
     if (res is not None and res != ""):
         self.video_dir = res
         settings.setValue("camera_control/video_dir", res)
         logging.info(f"set default videodirectory to {res}")
Example #18
0
 def assign_project(self, project):
     self.project_name = project
     settings = QSettings("Nebula", self.project_name)
     settings.beginGroup("SignalFiles")
     if self.list_path.__len__():
         settings.setValue("Path", self.list_path)
     else:
         settings.setValue("Path", "None")
     settings.endGroup()
Example #19
0
    def save(self) -> None:
        settings = QSettings(self.config_path, QSettings.NativeFormat)

        settings.beginWriteArray("predownloads")
        for i in range(len(self.predownloads)):
            settings.setArrayIndex(i)
            settings.setValue("predownload",
                              PreDownload.pack(self.predownloads[i]))
        settings.endArray()
Example #20
0
 def writeSettings(self):
     """
     Сохранение настроек окна.
     """
     settings = QSettings()
     settings.beginGroup("CreateForm")
     settings.setValue("size", self.size())
     settings.setValue("pos", self.pos())
     settings.endGroup()
Example #21
0
 def _save_window_settings(self) -> None:
     """
     Save this window's current state for next time app is used.
     :return None:
     """
     self._logger.debug("running")
     settings = QSettings(settings_info[0], settings_info[1])
     settings.setValue(window_geometry, self.saveGeometry())
     settings.setValue(window_state, self.saveState())
     self._logger.debug("done")
Example #22
0
def load_default_external_links():
    """Load default external DB links if the list is empty"""
    app_settings = QSettings()
    app_settings.beginGroup("plugins/variant_view/links")

    # If no value: add default values
    if not app_settings.childKeys():
        for db_name, db_url in cm.WEBSITES_URLS.items():
            app_settings.setValue(db_name, db_url)
    app_settings.endGroup()
Example #23
0
def settings():
    settings = QSettings("testing", "NCui_tests")
    yield settings
    settings.setValue(FileWriterSettings.STATUS_BROKER_ADDR, "")
    settings.setValue(FileWriterSettings.COMMAND_BROKER_ADDR, "")
    settings.setValue(FileWriterSettings.FILE_NAME, "")
    settings.setValue(FileWriterSettings.USE_START_TIME, False)
    settings.setValue(FileWriterSettings.USE_STOP_TIME, False)
    settings.setValue(FileWriterSettings.FILE_BROKER_ADDR, "")
    del settings
Example #24
0
    def saveState(self):
        """
        saves the state of the main window including the dock windows of Services

        :return:
        """
        logger.info("saving main window's state")
        settings = QSettings()
        settings.setValue("MainWindowState", super().saveState())
        settings.setValue("MainWindowGeometry", self.saveGeometry())
 def get_value(name, default, settings=None):
     if settings is None:
         settings = QSettings()
     v = settings.value(name)
     if v is None:
         settings.setValue(name, default)
         v = default
     if isinstance(default, int):
         return int(v)
     return v
Example #26
0
class SettingsForm(QDialog):
    def __init__(self, parent=None):
        super(SettingsForm, self).__init__(parent)
        self.settings = QSettings()

        layout = QVBoxLayout()

        # Notification sound
        wav_file = self.settings.value("notification_sound", "when.wav")
        self.sound_lbl = QLabel("Notification sound:")
        self.sound_val = QLineEdit(wav_file)
        self.sound_btn = QPushButton("Browse")
        hl = QHBoxLayout()
        hl.addWidget(self.sound_lbl)
        hl.addWidget(self.sound_val)
        hl.addWidget(self.sound_btn)
        layout.addLayout(hl)

        # Spread sheet ID
        sheet_id = self.settings.value("sheet_id", SAMPLE_SPREADSHEET_ID)
        self.sheet_id_lbl = QLabel("Spread sheet ID: ")
        self.sheet_id_val = QLineEdit(sheet_id)
        hl = QHBoxLayout()
        hl.addWidget(self.sheet_id_lbl)
        hl.addWidget(self.sheet_id_val)
        layout.addLayout(hl)

        # Control buttons
        self.save_btn = QPushButton("Save")
        self.cancel_btn = QPushButton("Cancel")
        hl = QHBoxLayout()
        hl.addWidget(self.save_btn)
        hl.addWidget(self.cancel_btn)
        layout.addLayout(hl)

        self.setLayout(layout)

        self.sound_btn.clicked.connect(self.sound_browse)
        self.save_btn.clicked.connect(self.on_save)
        self.cancel_btn.clicked.connect(self.on_cancel)

    def sound_browse(self):
        filename, filter = QFileDialog.getOpenFileName(parent=self, caption='Select sound file for notifications',
                                                       dir='.',
                                                       filter='Waveform Audio File Format (*.wav)')
        if filename:
            self.sound_val.setText(filename)

    def on_save(self):
        self.settings.setValue("notification_sound", self.sound_val.text())
        self.settings.setValue("sheet_id", self.sheet_id_val.text())
        self.hide()

    def on_cancel(self):
        self.hide()
Example #27
0
def load_image(parent, filename=None):
    nothing = [None] * 3
    settings = QSettings()
    if filename is None:
        dialog = QFileDialog(parent, parent.tr('Load image'),
                             settings.value('load_folder'))
        dialog.setOption(QFileDialog.DontUseNativeDialog, True)
        dialog.setFileMode(QFileDialog.ExistingFile)
        dialog.setViewMode(QFileDialog.Detail)
        mime_filters = [
            "image/jpeg", "image/png", "image/tiff", "image/gif", "image/bmp",
            "image/webp", "image/x-portable-pixmap",
            "image/x-portable-graymap", "image/x-portable-bitmap"
        ]
        mime_db = QMimeDatabase()
        mime_patterns = [
            mime_db.mimeTypeForName(mime).globPatterns()
            for mime in mime_filters
        ]
        all_formats = 'Supported formats ({})'.format(' '.join(
            [item for sub in mime_patterns for item in sub]))
        dialog.setMimeTypeFilters(mime_filters)
        name_filters = dialog.nameFilters()
        dialog.setNameFilters(name_filters + [all_formats])
        dialog.selectNameFilter(all_formats)
        if dialog.exec_():
            filename = dialog.selectedFiles()[0]
        else:
            return nothing
    if filename.endswith('.gif'):
        capture = cv.VideoCapture(filename)
        frames = int(capture.get(cv.CAP_PROP_FRAME_COUNT))
        if frames > 1:
            QMessageBox.warning(
                parent, parent.tr('Warning'),
                parent.tr('Animated GIF: importing first frame'))
        result, image = capture.read()
        if not result:
            QMessageBox.critical(parent, parent.tr('Error'),
                                 parent.tr('Unable to decode GIF!'))
            return nothing
        if len(image.shape) == 2:
            image = cv.cvtColor(image, cv.COLOR_GRAY2BGR)
    else:
        image = cv.imread(filename, cv.IMREAD_COLOR)
    if image is None:
        QMessageBox.critical(parent, parent.tr('Error'),
                             parent.tr('Unable to load image!'))
        return nothing
    if image.shape[2] > 3:
        QMessageBox.warning(parent, parent.tr('Warning'),
                            parent.tr('Alpha channel discarded'))
        image = cv.cvtColor(image, cv.COLOR_BGRA2BGR)
    settings.setValue('load_folder', QFileInfo(filename).absolutePath())
    return filename, os.path.basename(filename), image
Example #28
0
 def writeSettings(self):
     """
     Сохранение настроек основного окна и БД приложения.
     """
     settings = QSettings()
     settings.beginGroup("MainForm")
     settings.setValue("size", self.size())
     settings.setValue("pos", self.pos())
     self.storage.save_storage()
     self.save_services()
     settings.endGroup()
Example #29
0
    def testDictionary(self):
        confFile = tempfile.NamedTemporaryFile(delete=False)
        s = QSettings(confFile.name, QSettings.IniFormat)
        # Save value
        s.setValue('x', {1: 'a'})
        s.sync()
        del s

        # Restore value
        s = QSettings(confFile.name, QSettings.IniFormat)
        self.assertEqual(s.value('x'), {1: 'a'})
Example #30
0
class Ui_MainWindow(SetupUIMixin, MatrixTabMixin, ValueScoreTabMixin):
    def __init__(self):
        # Make sure that mixins do not have an init method
        self.matrix = Matrix()
        self.settings = QSettings('twenty5151', 'decision_matrix_qt')
        self.cc_tab_page = None
        self.data_tab_page = DataTab(self)
        self.data_tab_groupboxes = {}

        if not self.settings.contains('confirm_delete'):
            self.settings.setValue('confirm_delete', True)
Example #31
0
 def save_session(self, settings: QSettings):
     settings.beginGroup('project_splitter')
     settings.setValue('horiz', self.main_splitter.saveState())
     settings.setValue('vert_trees', self.left_splitter.saveState())
     settings.setValue('vert_plots', self.right_splitter.saveState())
     settings.endGroup()
     settings.beginGroup('tree_columns')
     settings.setValue('params',
                       self.w_parameters_tree.header().saveState())
     settings.setValue('curves', self.w_curves_tree.header().saveState())
     settings.endGroup()
Example #32
0
class MainWindow(QMainWindow):

    def __init__(self, app, parent=None):
        super(MainWindow, self).__init__(parent)
        self.imagesDir = app.dir + '/images/'
        self.setWindowIcon(QIcon(self.imagesDir + 'icon.png'))
        self.path = ''

        self.settings = QSettings()
        self.lastDir = self.settings.value('lastDir', '')

        self.setMinimumWidth(540)

        self.supportedFormats = []
        for f in QImageReader.supportedImageFormats():
            self.supportedFormats.append(str(f.data(), encoding="utf-8"))

        self.fileWatcher = QFileSystemWatcher()
        self.fileWatcher.fileChanged.connect(self.fileChanged)

        # widgets
        self.showPixmapWidget = None

        self.tileWidthSpinBox = QSpinBox()
        self.tileWidthSpinBox.setValue(16)
        self.tileWidthSpinBox.setFixedWidth(50)
        self.tileWidthSpinBox.setMinimum(1)

        self.tileHeightSpinBox = QSpinBox()
        self.tileHeightSpinBox.setValue(16)
        self.tileHeightSpinBox.setFixedWidth(50)
        self.tileHeightSpinBox.setMinimum(1)

        self.paddingSpinBox = QSpinBox()
        self.paddingSpinBox.setFixedWidth(50)
        self.paddingSpinBox.setMinimum(1)

        self.transparentCheckbox = QCheckBox("Transparent")
        self.transparentCheckbox.setChecked(True)
        self.transparentCheckbox.stateChanged.connect(self.transparentChanged)

        self.backgroundColorEdit = ColorEdit()
        self.backgroundColorEdit.setEnabled(False)
        self.backgroundColorLabel = QLabel("Background color:")
        self.backgroundColorLabel.setEnabled(False)

        self.forcePotCheckBox = QCheckBox("Force PoT")
        self.forcePotCheckBox.setChecked(True)
        self.forcePotCheckBox.stateChanged.connect(self.forcePotChanged)

        self.reorderTilesCheckBox = QCheckBox("Reorder tiles")

        self.generateAndExportButton = QPushButton("Generate and export")
        self.generateAndExportButton.setFixedHeight(32)
        self.generateAndExportButton.clicked.connect(self.generateAndExportClicked)
        self.generateAndExportButton.setEnabled(False)

        self.pixmapWidget = PixmapWidget()
        self.pixmapWidget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.pixmapWidget.setPixmap(self.createDropTextPixmap())
        self.pixmapWidget.dropSignal.connect(self.fileDropped)
        self.pixmapWidget.setMinimumHeight(300)

        # load settings
        self.tileWidthSpinBox.setValue(int(self.settings.value('tileWidth', 16)))
        self.tileHeightSpinBox.setValue(int(self.settings.value('tileHeight', 16)))
        self.paddingSpinBox.setValue(int(self.settings.value('padding', 1)))
        self.forcePotCheckBox.setChecked(True if self.settings.value('forcePot', 'true') == 'true' else False)
        self.reorderTilesCheckBox.setChecked(True if self.settings.value('reorderTiles', 'false') == 'true' else False)
        self.transparentCheckbox.setChecked(True if self.settings.value('transparent', 'false') == 'true' else False)
        self.backgroundColorEdit.setColorText(str(self.settings.value('backgroundColor', '#FF00FF')))
        self.restoreGeometry(QByteArray(self.settings.value('MainWindow/geometry')))
        self.restoreState(QByteArray(self.settings.value('MainWindow/windowState')))

        # layout
        hl1 = QHBoxLayout()
        hl1.setContentsMargins(5, 5, 5, 5)
        hl1.addWidget(QLabel("Tile width:"))
        hl1.addSpacing(5)
        hl1.addWidget(self.tileWidthSpinBox)
        hl1.addSpacing(15)
        hl1.addWidget(QLabel("Tile height:"))
        hl1.addSpacing(5)
        hl1.addWidget(self.tileHeightSpinBox)
        hl1.addSpacing(15)
        hl1.addWidget(QLabel("Padding:"))
        hl1.addSpacing(5)
        hl1.addWidget(self.paddingSpinBox)
        hl1.addSpacing(15)
        hl1.addWidget(self.forcePotCheckBox)
        hl1.addSpacing(15)
        hl1.addWidget(self.reorderTilesCheckBox)
        hl1.addStretch()

        hl2 = QHBoxLayout()
        hl2.setContentsMargins(5, 5, 5, 5)
        hl2.addWidget(self.transparentCheckbox)
        hl2.addSpacing(15)
        hl2.addWidget(self.backgroundColorLabel)
        hl2.addSpacing(5)
        hl2.addWidget(self.backgroundColorEdit)
        hl2.addStretch()

        hl3 = QHBoxLayout()
        hl3.setContentsMargins(5, 5, 5, 5)
        hl3.addWidget(self.generateAndExportButton)

        vl = QVBoxLayout()
        vl.setContentsMargins(0, 0, 0, 0)
        vl.setSpacing(0)
        vl.addLayout(hl1)
        vl.addLayout(hl2)
        vl.addWidget(self.pixmapWidget)
        vl.addLayout(hl3)

        w = QWidget()
        w.setLayout(vl)
        self.setCentralWidget(w)

        self.setTitle()

    def setTitle(self):
        p = ' - ' + os.path.basename(self.path) if self.path else ''
        self.setWindowTitle(QCoreApplication.applicationName() + ' ' + QCoreApplication.applicationVersion() + p)

    def createDropTextPixmap(self):
        pixmap = QPixmap(481, 300)
        pixmap.fill(QColor("#333333"))
        painter = QPainter(pixmap)
        font = QFont("Arial")
        font.setPixelSize(28)
        font.setBold(True)
        fm = QFontMetrics(font)
        painter.setFont(font)
        painter.setPen(QPen(QColor("#888888"), 1))
        text = "Drop the tileset image here"
        x = (pixmap.width()-fm.width(text))/2
        y = (pixmap.height()+fm.height())/2
        painter.drawText(x, y, text)
        del painter
        return pixmap

    def fileDropped(self, path):
        path = str(path)
        name, ext = os.path.splitext(path)
        ext = ext[1:]
        if not ext in self.supportedFormats:
            QMessageBox.warning(self, "Warning", "The dropped file is not supported")
            return
        pixmap = QPixmap(path)
        if pixmap.isNull():
            QMessageBox.warning(self, "Warning", "Can't load the image")
            return
        if self.path:
            self.fileWatcher.removePath(self.path)
        self.path = path
        self.fileWatcher.addPath(self.path)
        self.pixmapWidget.setPixmap(pixmap)
        self.generateAndExportButton.setEnabled(True)
        self.setTitle()
        self.activateWindow()

    def fileChanged(self, path):
        #self.fileDropped(path)
        pass

    def transparentChanged(self):
        e = self.transparentCheckbox.isChecked()
        self.backgroundColorEdit.setEnabled(not e)
        self.backgroundColorLabel.setEnabled(not e)

    def forcePotChanged(self):
        e = self.forcePotCheckBox.isChecked()
        self.reorderTilesCheckBox.setEnabled(e)

    def generateAndExportClicked(self):

        g = Generator()
        g.tileWidth = self.tileWidthSpinBox.value()
        g.tileHeight = self.tileHeightSpinBox.value()
        g.forcePot = self.forcePotCheckBox.isChecked()
        g.isTransparent = self.transparentCheckbox.isChecked()
        g.bgColor = self.backgroundColorEdit.getColor()
        g.reorder = self.reorderTilesCheckBox.isChecked()
        g.padding = self.paddingSpinBox.value()

        target = g.create(self.pixmapWidget.pixmap);

        # export
        self.lastDir = os.path.dirname(self.path)
        targetPath = QFileDialog.getSaveFileName(self, 'Export', self.lastDir, 'PNG (*.png)')
        if targetPath:
            target.save(targetPath[0])
            showPixmap = QPixmap.fromImage(target)
            if self.showPixmapWidget:
                self.showPixmapWidget.deleteLater()
                del self.showPixmapWidget
            self.showPixmapWidget = PixmapWidget()
            self.showPixmapWidget.setWindowIcon(self.windowIcon())
            self.showPixmapWidget.setWindowTitle(os.path.basename(targetPath[0]))
            self.showPixmapWidget.resize(showPixmap.width(), showPixmap.height())
            self.showPixmapWidget.setPixmap(showPixmap)
            self.showPixmapWidget.show()

    def closeEvent(self, event):
        if self.showPixmapWidget:
            self.showPixmapWidget.close()

        # save settings
        self.settings.setValue('tileWidth', self.tileWidthSpinBox.value())
        self.settings.setValue('tileHeight', self.tileHeightSpinBox.value())
        self.settings.setValue('padding', self.paddingSpinBox.value())
        self.settings.setValue('forcePot', self.forcePotCheckBox.isChecked())
        self.settings.setValue('reorderTiles', self.reorderTilesCheckBox.isChecked())
        self.settings.setValue('transparent', self.transparentCheckbox.isChecked())
        self.settings.setValue('backgroundColor', self.backgroundColorEdit.getColor().name())
        self.settings.setValue('lastDir', self.lastDir)
        self.settings.setValue('MainWindow/geometry', self.saveGeometry())
        self.settings.setValue('MainWindow/windowState', self.saveState())

        super(MainWindow, self).closeEvent(event)
Example #33
0
 def writeSettings(self):
     settings = QSettings('Trolltech', 'MDI Example')
     settings.setValue('pos', self.pos())
     settings.setValue('size', self.size())