예제 #1
0
 def setCountryCode(self, idx):
     country = self.ui.countryBox.itemData(idx)
     if country:
         locale = QLocale(Languages[self.ui.languageBox.currentIndex()], QLocale.Country(country))
         name = locale.name()
         codes = name.split('_')
         self.mainWindow.moaiWidget.runString( "MOAIEnvironment.setValue('languageCode', '%s')" % codes[0])
         self.mainWindow.moaiWidget.runString( "MOAIEnvironment.setValue('countryCode', '%s')" % codes[1])
예제 #2
0
 def __init__(self, *args, **kwargs):
     QApplication.__init__(self, *args, **kwargs)
     self.settings = QSettings("everpad", "everpad-pad")
     self.translator = QTranslator()
     if not self.translator.load("../../i18n/%s" % QLocale.system().name()):
         self.translator.load("/usr/share/everpad/i18n/%s" % QLocale.system().name())
     self.installTranslator(self.translator)
     self.icon = QIcon.fromTheme("everpad-mono", QIcon("../../everpad-mono.png"))
     self.indicator = Indicator(self, self.icon)
     self.indicator.show()
예제 #3
0
 def __init__(self, *args, **kwargs):
     QApplication.__init__(self, *args, **kwargs)
     self.settings = QSettings('everpad', 'everpad-pad')
     self.translator = QTranslator()
     if not self.translator.load('../../i18n/%s' % QLocale.system().name()):
         self.translator.load('/usr/share/everpad/i18n/%s' % QLocale.system().name())
     self.installTranslator(self.translator)
     self.indicator = Indicator(self)
     self.update_icon()
     self.indicator.show()
예제 #4
0
 def __init__(self, *args, **kwargs):
     QApplication.__init__(self, *args, **kwargs)
     self.settings = QSettings('everpad', 'everpad-pad')
     self.translator = QTranslator()
     if not self.translator.load('../../i18n/%s' % QLocale.system().name()):
         self.translator.load('/usr/share/everpad/i18n/%s' %
                              QLocale.system().name())
     self.installTranslator(self.translator)
     self.indicator = Indicator(self)
     self.update_icon()
     self.indicator.show()
예제 #5
0
파일: indicator.py 프로젝트: XelK/everpad
 def __init__(self, *args, **kwargs):
     QApplication.__init__(self, *args, **kwargs)
     self.settings = QSettings("everpad", "everpad-pad")
     self.translator = QTranslator()
     if not self.translator.load("../../i18n/%s" % QLocale.system().name()):
         self.translator.load("/usr/share/everpad/i18n/%s" % QLocale.system().name())
     # This application string can be localized to 'RTL' to switch the application layout
     # direction. See for example i18n/ar_EG.ts
     QT_TRANSLATE_NOOP("QApplication", "QT_LAYOUT_DIRECTION")
     self.installTranslator(self.translator)
     self.indicator = Indicator(self)
     self.update_icon()
     self.indicator.show()
예제 #6
0
 def __init__(self, *args, **kwargs):
     QApplication.__init__(self, *args, **kwargs)
     self.settings = QSettings('everpad', 'everpad-pad')
     self.translator = QTranslator()
     if not self.translator.load('../../i18n/%s' % QLocale.system().name()):
         self.translator.load('/usr/share/everpad/i18n/%s' % QLocale.system().name())
     # This application string can be localized to 'RTL' to switch the application layout
     # direction. See for example i18n/ar_EG.ts
     QT_TRANSLATE_NOOP('QApplication', 'QT_LAYOUT_DIRECTION')
     self.installTranslator(self.translator)
     QNetworkProxyFactory.setUseSystemConfiguration(True)
     self.indicator = Indicator(self)
     self.update_icon()
     self.indicator.show()
예제 #7
0
    def applyEnvironmentSettings(self):
        lang = Languages[self.ui.languageBox.currentIndex()]
        country = QLocale.Country(self.ui.countryBox.itemData(self.ui.countryBox.currentIndex()))

        locale = QLocale(lang, country)
        name = locale.name()
        codes = name.split('_')

        relPath = self.ui.documentsBtn.text()
        dpi = float(self.ui.dpiEdit.text())

        self.mainWindow.moaiWidget.runString( "MOAIEnvironment.setValue('languageCode', '%s')" % codes[0])
        self.mainWindow.moaiWidget.runString( "MOAIEnvironment.setValue('countryCode', '%s')" % codes[1])
        self.mainWindow.moaiWidget.runString( "MOAIEnvironment.setValue('screenDpi', %f)" % dpi )
        self.mainWindow.moaiWidget.runString( "MOAIEnvironment.setValue('documentDirectory', '%s')" % relPath )
예제 #8
0
    def about_text(self):
        self.label_3 = QLabel()
        self.label_3.setTextFormat(Qt.RichText)
        self.label_3.setOpenExternalLinks(True)
        self.label_3.setLocale(QLocale(QLocale.English, QLocale.UnitedStates))
        self.label_3.setScaledContents(True)
        self.label_3.setWordWrap(True)
        text = """
<html>
<head/>
<body>
  <p>poliBeePsync is a program written by Davide Olianas,
released under GNU GPLv3+.</p>
  <p>Feel free to contact me at <a
  href=\"mailto:[email protected]\">[email protected]</a> for
  suggestions and bug reports.</p>
  <p>More information is available on the
  <a href=\"http://www.davideolianas.com/polibeepsync\">
  <span style=\" text-decoration: underline; color:#0000ff;\">
  official website</span></a>.
  </p>
</body>
</html>
"""

        if pysideVersion == '1.2.2':
            self.label_3.setText(
                QApplication.translate("Form", text, None,
                                       QApplication.UnicodeUTF8))
        else:
            self.label_3.setText(QApplication.translate("Form", text, None))
예제 #9
0
    def __init__(self, parent=None):
        super(ProductOrderForm, self).__init__(parent)
        self.setupUi(self)
        # had to subclass this spinbox to support return grabbing
        self.edQuantity = ReturnKeySpinBox(self)
        self.edQuantityHolder.addWidget(self.edQuantity)

        self._access = statics.access_level
        # for currency formatting
        self._locale = QLocale()

        # had to hardcode these, wouldn't work otherwise:
        self.contentsLayout.setAlignment(self.groupBox, QtCore.Qt.AlignTop)
        self.contentsLayout.setAlignment(self.groupBox_2, QtCore.Qt.AlignTop)
        self.contentsLayout.setAlignment(self.groupBox_3, QtCore.Qt.AlignTop)
        self.contentsLayout.setAlignment(self.groupBox_4, QtCore.Qt.AlignTop)

        self.log = logging.getLogger("ProductOForm")

        self.setup_model()
        self.setup_fields()

        # associate present flag
        self._associate_id = None
        # product internals
        self._product_list = []
        self._total = 0.0

        # flag to indicate whether there were changes to the fields
        self._dirty = False
예제 #10
0
    def __init__(self, parent=None):
        super(BookOrderForm, self).__init__(parent)
        self.setupUi(self)

        self._access = statics.access_level
        # for currency formatting
        self._locale = QLocale()

        # had to hardcode these, wouldn't work otherwise:
        self.contentsLayout.setAlignment(self.groupBox, QtCore.Qt.AlignTop)
        self.contentsLayout.setAlignment(self.groupBox_2, QtCore.Qt.AlignTop)
        self.contentsLayout.setAlignment(self.groupBox_3, QtCore.Qt.AlignTop)
        self.contentsLayout.setAlignment(self.groupBox_4, QtCore.Qt.AlignTop)


        self.log = logging.getLogger('BookOForm')

        self.setup_model()
        self.setup_fields()

        # associate present flag
        self._associate_id = None
        # book internals
        self._book_list = []
        self._total = 0.0

        # flag to indicate whether there were changes to the fields
        self._dirty = False
예제 #11
0
파일: tablemodel.py 프로젝트: marchon/ifmon
 def formatUptime(time):
     s = ''
     loc = QLocale()
     if time.days > 0:
         d = QCoreApplication.translate('ifmon', 'days') if time.days > 1 \
                 else QCoreApplication.translate('ifmon', 'day')
         s = '%s %s, ' % (loc.toString(time.days), d)
     mm, ss = divmod(time.seconds, 60)
     hh, mm = divmod(mm, 60)
     def padded(d):
         if d < 10:
             return loc.toString(0) + loc.toString(d)
         else:
             return loc.toString(d)
     s += '%s:%s:%s' % (padded(hh), padded(mm), padded(ss))
     return s
예제 #12
0
 def __init__(self, parent=None):
     super(BookOrderTableModel, self).__init__(parent)
     self._sql_statement = "SELECT b_o.id, b_o.date, b_o.total, a.fullname as associate, SUBSTR(b_o.obs,0,50) as obs " \
             "FROM order_request b_o " \
             "LEFT JOIN associate a ON b_o.associate_id = a.id " \
             "WHERE b_o.type = 1"
     self._name = "populate_obook"
     self._locale = QLocale()
예제 #13
0
	def onLoad( self ):
		QLocale.setDefault(QLocale(QLocale.C))
		locale.setlocale(locale.LC_ALL, 'C')

		QCoreApplication.setOrganizationName("CloudTeam")
		QCoreApplication.setOrganizationDomain("cloudteam.pro")
		QCoreApplication.setApplicationName("juma-moai-editor")

		self.qtApp = QApplication( sys.argv )
		self.qtSetting = QSettings()
		
		self.setupMainWindow()		

		self.initialized = True
		self.running     = False

		return True
예제 #14
0
 def __init__(self, parent=None):
     super(ProductOrderTableModel, self).__init__(parent)
     self._sql_statement = "SELECT p_o.id, p_o.date, p_o.total, a.fullname as associate, SUBSTR(p_o.obs,0,50) as obs " \
             "FROM order_request p_o " \
             "LEFT JOIN associate a ON p_o.associate_id = a.id " \
             "WHERE p_o.type = 0"
     self._name = "populate_oproduct"
     self._locale = QLocale()
예제 #15
0
파일: pad.py 프로젝트: casualuser/everpad
 def __init__(self, *args, **kwargs):
     """Init app"""
     QApplication.__init__(self, *args, **kwargs)
     self.sync_thread = SyncThread()
     self.sync_thread.start()
     self.translator = QTranslator()
     if not self.translator.load('i18n/%s' % QLocale.system().name()):
         self.translator.load('/usr/share/everpad/lang/%s' % QLocale.system().name())
     self.provider_obj = dbus.SessionBus().get_object("com.everpad.Provider", '/EverpadProvider')
     self.provider = dbus.Interface(self.provider_obj, "com.everpad.Provider")
     self.installTranslator(self.translator)
     self.icon = QIcon.fromTheme('everpad', QIcon('../everpad.png'))
     indicator = Indicator(self, self.icon)
     indicator.show()
     self.opened = {}
     self.setApplicationName('everpad')
     self.settings = gconf.client_get_default()
예제 #16
0
class BookOrderTableModel(BaseTableModel):
    """ Model for listing book orders """

    ID, DATE, TOTAL, ASSOCIATE, OBS = range(5)

    def __init__(self, parent=None):
        super(BookOrderTableModel, self).__init__(parent)
        self._sql_statement = "SELECT b_o.id, b_o.date, b_o.total, a.fullname as associate, SUBSTR(b_o.obs,0,50) as obs " \
                "FROM order_request b_o " \
                "LEFT JOIN associate a ON b_o.associate_id = a.id " \
                "WHERE b_o.type = 1"
        self._name = "populate_obook"
        self._locale = QLocale()

    def load(self):
        self.set_query_info(self._name, self._sql_statement)
        super(BookOrderTableModel, self).load()

    def data(self, index, role=Qt.DisplayRole):
        if not index.isValid() or not (0<=index.row()<self.rowCount()):
            # invalid index
            return None
        record = self.get_record(index.row())
        column = index.column()
        if role == Qt.DisplayRole:
            if column == self.ID:
                return record.value("id")
            elif column == self.DATE:
                return record.value("date").toString("dd/MMM - HH:mm")
            elif column == self.TOTAL:
                return self._locale.toString(record.value("total"), 'f', 2).replace('.','')
            elif column == self.ASSOCIATE:
                return record.value("associate")
            elif column == self.OBS:
                return record.value("obs")
        return None

    def headerData(self, section, orientation, role=Qt.DisplayRole):
        if role == Qt.TextAlignmentRole:
            if orientation == Qt.Horizontal:
                return int(Qt.AlignLeft|Qt.AlignVCenter)
            return int(Qt.AlignRight|Qt.AlignVCenter)

        if role != Qt.DisplayRole:
            return None

        if orientation == Qt.Horizontal:
            if section == self.ID:
                return "Reg."
            elif section == self.DATE:
                return "Data e Hora"
            elif section == self.TOTAL:
                return "Total (R$)"
            elif section == self.ASSOCIATE:
                return "Associado"
            elif section == self.OBS:
                return unicode("Observações".decode('utf-8'))
        return section + 1
예제 #17
0
파일: __init__.py 프로젝트: p0i0/Hazama
def setTranslationLocale():
    global locale
    lang = settings['Main'].get('lang')
    sysLocale = QLocale.system()
    if lang and lang == sysLocale.name():
        locale = sysLocale
    elif lang and lang != sysLocale.name():
        # special case: application language is different from system's
        locale = QLocale(lang)
        QLocale.setDefault(locale)
    else:
        locale = sysLocale
        lang = settings['Main']['lang'] = locale.name()
    langPath = os.path.join(appPath, 'lang')
    logging.info('set translation(%s)', lang)
    global _trans, _transQt  # avoid being collected
    _trans = QTranslator()
    _trans.load(lang, langPath)
    _transQt = QTranslator()
    ret = _transQt.load('qt_' + lang,
                        QLibraryInfo.location(QLibraryInfo.TranslationsPath))
    if not ret:  # frozen
        _transQt.load('qt_' + lang, langPath)
    for i in [_trans, _transQt]:
        QApplication.instance().installTranslator(i)

    global dateFmt, datetimeFmt, fullDatetimeFmt
    timeFmt = settings['Main'].get('timeFormat')
    dateFmt = settings['Main'].get('dateFormat', locale.dateFormat())
    datetimeFmt = (dateFmt + ' ' + timeFmt) if timeFmt else dateFmt
    # use hh:mm because locale.timeFormat will include seconds
    fullDatetimeFmt = dateFmt + ' ' + (timeFmt or 'hh:mm')
예제 #18
0
def main():

    # application specifics
    app = QApplication(sys.argv)

    # TODO: remove this, hardcoding it for testing
    QLocale.setDefault(QLocale(QLocale.Portuguese, QLocale.Brazil))

    # login dialog
    login_dialog = Login()
    if login_dialog.exec_() == QDialog.Accepted:
        # validation complete, open main interface
        window = MainWindow(login_dialog.get_user_data())
        window.showMaximized()
        # solves mainwindow focusing on windows/xfce
        app.setActiveWindow(window)
        # start main loop
        sys.exit(app.exec_())
예제 #19
0
def main():
    """
    """
    from MainWindow import MainWindow

    translator = QTranslator() #Build the translator
    translator.load(":/locales/df_%s" % QLocale.system().name())
    qttranslator = QTranslator()#A translator for Qt standard strings
    qttranslator.load("qt_%s" % (QLocale.system().name()))
    App = QApplication(sys.argv) #Creating the app
    App.setOrganizationName(ORGNAME) #Setting organization and application's
    App.setApplicationName(NAME)#name. It's only useful for QSettings
    App.setApplicationVersion(VERSION)
    App.setOrganizationDomain(URL)
    App.installTranslator(translator)#Install translators into the application.
    App.installTranslator(qttranslator)
    mw = MainWindow(App) #Now it's time to instantiate the main window
    mw.show() #And show it
    sys.exit(App.exec_()) #When the app finishes, exit.
예제 #20
0
def main():
    """
    """
    from MainWindow import MainWindow

    translator = QTranslator()  #Build the translator
    translator.load(":/locales/df_%s" % QLocale.system().name())
    qttranslator = QTranslator()  #A translator for Qt standard strings
    qttranslator.load("qt_%s" % (QLocale.system().name()))
    App = QApplication(sys.argv)  #Creating the app
    App.setOrganizationName(ORGNAME)  #Setting organization and application's
    App.setApplicationName(NAME)  #name. It's only useful for QSettings
    App.setApplicationVersion(VERSION)
    App.setOrganizationDomain(URL)
    App.installTranslator(
        translator)  #Install translators into the application.
    App.installTranslator(qttranslator)
    mw = MainWindow(App)  #Now it's time to instantiate the main window
    mw.show()  #And show it
    sys.exit(App.exec_())  #When the app finishes, exit.
예제 #21
0
파일: app.py 프로젝트: bwprice/inselect
def main():
    parser = argparse.ArgumentParser(
        description='Runs the inselect user-interface')
    parser.add_argument("file",
                        help='The inselect document to open',
                        nargs='?')
    parser.add_argument('-d',
                        '--debug',
                        action='store_true',
                        help='Show debug messages')
    parser.add_argument('-l',
                        '--locale',
                        action='store',
                        help='Use LOCALE; intended for testing purposes only')
    parser.add_argument('-v',
                        '--version',
                        action='version',
                        version='%(prog)s ' + inselect.__version__)
    args = parser.parse_args()

    # TODO LH A command-line switch to clear all QSettings

    inselect.lib.utils.DEBUG_PRINT = args.debug

    app = QApplication(sys.argv)

    debug_print(u'Settings stored in [{0}]'.format(QSettings().fileName()))

    if args.locale:
        debug_print('Will set locale to [{0}]'.format(args.locale))
        QLocale.setDefault(QLocale(args.locale))

    debug_print(u'Locale is [{0}]'.format(QLocale().name()))

    window = MainWindow(app)
    window.show_from_geometry_settings()

    if args.file:
        window.open_file(args.file)

    sys.exit(app.exec_())
예제 #22
0
 def __init__(self, parent=None, display_mode=constants.BOOK_ALL):
     super(BookTableModel, self).__init__(parent)
     self._sql_statement = "SELECT b.id, b.title, a.name as author, s_a.name as s_author, b.price, b.stock, b.availability " \
             "FROM book b " \
             "LEFT JOIN author a ON b.author_id = a.id " \
             "LEFT JOIN s_author s_a ON b.s_author_id = s_a.id"
     if display_mode == constants.BOOK_SELL:
         self._sql_statement += " WHERE b.availability = 0 AND b.stock > 0"
     elif display_mode == constants.BOOK_RENT:
         self._sql_statement += " WHERE b.availability = 1"
     self._name = "populate_book"
     self._locale = QLocale()
예제 #23
0
파일: app.py 프로젝트: edwbaker/inselect
def main(args):
    parser = argparse.ArgumentParser(description='Runs the inselect user-interface')
    parser.add_argument("file", help='The inselect document to open', nargs='?')
    parser.add_argument('-d', '--debug', action='store_true',
                        help='Show debug messages')
    parser.add_argument('-l', '--locale', action='store',
                        help='Use LOCALE; intended for testing purposes only')
    parser.add_argument('-v', '--version', action='version',
                        version='%(prog)s ' + inselect.__version__)
    parsed = parser.parse_args(args[1:])

    # TODO LH A command-line switch to clear all QSettings

    inselect.lib.utils.DEBUG_PRINT = parsed.debug

    # Only one instance of QApplication can be created per process. The single
    # instance is stored in QtGui.qApp. When test plans are being run it is
    # likely that the QApplication will have been created by a unittest.
    app = QtGui.qApp if QtGui.qApp else QtGui.QApplication(args)

    debug_print(u'Settings stored in [{0}]'.format(QSettings().fileName()))

    if parsed.locale:
        debug_print('Will set locale to [{0}]'.format(parsed.locale))
        QLocale.setDefault(QLocale(parsed.locale))
        locale.setlocale(locale.LC_ALL, parsed.locale)
    else:
        # Set Python's locale module to the user's default locale
        locale.setlocale(locale.LC_ALL, '')

    debug_print(u'Locale is [{0}]'.format(QLocale().name()))

    window = MainWindow(app)
    window.show_from_geometry_settings()

    if parsed.file:
        window.open_file(parsed.file)

    sys.exit(app.exec_())
예제 #24
0
 def _add_field(self, param, value):
     """Add a field to the task panel."""
     name = param.name
     if param.type == "float":
         widget = QLineEdit()
         widget.setAlignment(Qt.AlignRight)
         widget.setValidator(QDoubleValidator())
         try:
             value = QLocale().toString(float(value))
         except (ValueError, TypeError):
             value = None
         widget.setText(value)
         self.fields.append(
             (name, lambda: QLocale().toDouble(widget.text())[0]))
     elif param.type == "RGB":
         if value:
             parsedvalue = parse_csv_str(value)
             if "Object" not in parsedvalue:
                 color = str2rgb(parsedvalue[0])
                 use_object_color = False
             else:
                 use_object_color = True
                 if len(parsedvalue) > 1:
                     color = str2rgb(parsedvalue[1])
                 else:
                     color = (0.8, 0.8, 0.8)
             qcolor = QColor.fromRgbF(*color)
             widget = ColorPickerExt(qcolor, use_object_color)
         else:
             widget = ColorPickerExt()
         self.fields.append((name, widget.get_value))
     else:
         widget = QLineEdit()
         self.fields.append((name, widget.text))
     widget.setToolTip(param.desc)
     layout = self.form.findChild(QLayout, "FieldsLayout")
     layout.addRow(f"{param.name}:", widget)
예제 #25
0
 def systemLocale():
   from PySide.QtCore import QLocale
   system = QLocale.system()
   lang, script = system.language(), system.script()
   if lang == QLocale.English: return 'en_US'
   if lang == QLocale.Japanese: return 'ja_JP'
   if lang == QLocale.Korean: return 'ko_KR'
   if lang == QLocale.French: return 'fr_FR'
   if lang == QLocale.German: return 'de_DE'
   if lang == QLocale.Italian: return 'it_IT'
   if lang == QLocale.Spanish: return 'es_ES'
   if lang == QLocale.Portuguese: return 'pt_PT'
   if lang == QLocale.Russian: return 'ru_RU'
   if lang == QLocale.Polish: return 'pl_PL'
   if lang == QLocale.Chinese: return 'zh_CN' if script == QLocale.SimplifiedChineseScript else 'zh_TW'
예제 #26
0
    def __init__(self, record_id, parent=None):
        super(BookEditForm, self).__init__(parent)
        self.setupUi(self)
        # had to subclass this spinbox to support return grabbing
        self.edYear = ReturnKeySpinBox(self)
        self.edYearHolder.addWidget(self.edYear)
        # configuring id's for radio group
        self.radioAvailability.setId(self.rdSell,0)
        self.radioAvailability.setId(self.rdRent,1)
        self.radioAvailability.setId(self.rdInactive,2)
        # overlaying a clean button over the image (couldn't do it in designer)
        self.btnCleanImage = QPushButton()
        self.btnCleanImage.setIcon(QIcon(":icons/clean.png"))
        self.btnCleanImage.setFixedWidth(35)
        self.btnCleanImage.clicked.connect(self.clear_image)
        self.btnCleanImage.setVisible(False)
        clean_img_layout = QVBoxLayout(self.edImage)
        clean_img_layout.addWidget(self.btnCleanImage)
        clean_img_layout.setAlignment(Qt.AlignTop | Qt.AlignLeft)
        clean_img_layout.setContentsMargins(2,2,0,0)

        self._access = statics.access_level
        # for currency formatting
        self._locale = QLocale()
        self._record_id = record_id

        # had to hardcode these, wouldn't work otherwise:
        self.contentsLayout.setAlignment(self.groupBox, QtCore.Qt.AlignTop)
        self.contentsLayout.setAlignment(self.groupBox_2, QtCore.Qt.AlignTop)

        self.log = logging.getLogger('BookEditForm')

        self._subject_list = []

        self._removed_subjects = []
        self._added_subjects = []

        self.setup_model()
        self.fill_form()
        self.setup_fields()
        self._old_data = self.extract_input(text_only=True)

        # flag to indicate whether there were changes to the fields
        self._dirty = False
        # user did input an image
        self._image_set = False
        # image changed during edit
        self._image_changed = False
예제 #27
0
파일: mainwindow.py 프로젝트: marchon/ifmon
    def updateTotal(self):
        stat = self.model.total
        total = BandwidthTableModel.smart_bytes(stat['total'])
        received = BandwidthTableModel.smart_bytes(stat['received'])
        transmitted = BandwidthTableModel.smart_bytes(stat['transmitted'])
        self.labelTotal.setText(total)
        self.labelTotalReceived.setText(received)
        self.labelTotalTransmitted.setText(transmitted)
        self.labelUptime.setText(BandwidthTableModel.formatUptime(stat['uptime']))

        tps = BandwidthTableModel.smart_bytes(self.model.tps)
        rps = BandwidthTableModel.smart_bytes(self.model.rps)
        self.labelRps.setText("%s/s" % rps)
        self.labelTps.setText("%s/s" % tps)
        now = QLocale().toString(QDateTime.currentDateTime(), u'dd MMMM, yyyy hh:mm:ss')
        self.labelTime.setText(now)
예제 #28
0
 def __init__(self, *args, **kwargs):
     QApplication.__init__(self, *args, **kwargs)
     self.settings = QSettings('everpad', 'everpad-pad')
     locale = QLocale.system().name()
     self.qtTranslator = QTranslator()
     self.qtTranslator.load("qt_" + locale, QLibraryInfo.location(QLibraryInfo.TranslationsPath))
     self.installTranslator(self.qtTranslator)
     self.appTranslator = QTranslator()
     if not self.appTranslator.load(locale, os.path.join(os.path.dirname(__file__), '../../i18n')):
         self.appTranslator.load(locale, resource_filename('share/everpad/i18n'))
     # This application string can be localized to 'RTL' to switch the application layout
     # direction. See for example i18n/ar_EG.ts
     QT_TRANSLATE_NOOP('QApplication', 'QT_LAYOUT_DIRECTION')
     self.installTranslator(self.appTranslator)
     QNetworkProxyFactory.setUseSystemConfiguration(True)
     self.indicator = Indicator()
     self.update_icon()
     self.indicator.show()
예제 #29
0
    def checknewversion(self):
        rawdata = requests.get(
            'https://pypi.python.org/pypi/poliBeePsync/json')
        latest = json.loads(rawdata.text)['info']['version']
        self.version_label.setTextFormat(Qt.RichText)
        self.version_label.setOpenExternalLinks(True)
        self.version_label.setLocale(
            QLocale(QLocale.English, QLocale.UnitedStates))
        self.version_label.setScaledContents(True)
        self.version_label.setWordWrap(True)
        if latest != __version__:
            newtext = """<p>Current version: {}.<br>
Latest version: {}. </p>
<p>Visit <a href='http://www.davideolianas.com/polibeepsync/index.html#how-to\
-install-upgrade-remove'>here</a> to find out how to upgrade.
""".format(__version__, latest)
        else:
            newtext = "Current version: {} up-to-date.".format(__version__)
        self.version_label.setText(newtext)
예제 #30
0
파일: app.py 프로젝트: marchon/ifmon
def main(argv=None):
    app = QApplication(argv or sys.argv)
    locale = QLocale.system().name()
    trans = QTranslator()
    locale_path = '%s/locale/ifmon_%s' % (os.path.dirname(
        os.path.dirname(os.path.realpath(__file__))), locale.lower())
    trans.load(locale_path)
    app.installTranslator(trans)
    try:
        setup_db()
    except:
        QMessageBox.critical(
            None, 'Database error', 'Could not find the database.\n'
            'Please install it properly by running install.py on Ubuntu.\n'
            'For other Linux distributions, check the requirements.',
            QMessageBox.Ok)
        sys.exit(app.exit())
    else:
        mw = MainWindow()
        mw.show()
    sys.exit(app.exec_())
예제 #31
0
파일: app.py 프로젝트: marchon/ifmon
def main(argv=None):
    app = QApplication(argv or sys.argv)
    locale = QLocale.system().name()
    trans = QTranslator()
    locale_path = '%s/locale/ifmon_%s' % (os.path.dirname(os.path.dirname(
        os.path.realpath(__file__))), locale.lower())
    trans.load(locale_path)
    app.installTranslator(trans)
    try:
        setup_db()
    except:
        QMessageBox.critical(None, 'Database error',
            'Could not find the database.\n'
            'Please install it properly by running install.py on Ubuntu.\n'
            'For other Linux distributions, check the requirements.',
            QMessageBox.Ok)
        sys.exit(app.exit())
    else:
        mw = MainWindow()
        mw.show()
    sys.exit(app.exec_())
예제 #32
0
 def __init__(self, *args, **kwargs):
     QApplication.__init__(self, *args, **kwargs)
     self.settings = QSettings('everpad', 'everpad-pad')
     locale = QLocale.system().name()
     self.qtTranslator = QTranslator()
     self.qtTranslator.load(
         "qt_" + locale,
         QLibraryInfo.location(QLibraryInfo.TranslationsPath))
     self.installTranslator(self.qtTranslator)
     self.appTranslator = QTranslator()
     if not self.appTranslator.load(
             locale, os.path.join(os.path.dirname(__file__), '../../i18n')):
         self.appTranslator.load(locale,
                                 resource_filename('share/everpad/i18n'))
     # This application string can be localized to 'RTL' to switch the application layout
     # direction. See for example i18n/ar_EG.ts
     QT_TRANSLATE_NOOP('QApplication', 'QT_LAYOUT_DIRECTION')
     self.installTranslator(self.appTranslator)
     QNetworkProxyFactory.setUseSystemConfiguration(True)
     self.indicator = Indicator()
     self.update_icon()
     self.indicator.show()
예제 #33
0
class DefaulterTableModel(AssociateTableModel):
    """ Model for defaulter (at fault, associates with debt) objects """

    DEBT = 8

    def __init__(self, parent=None):
        super(DefaulterTableModel, self).__init__(parent)
        self._sql_statement = "SELECT id, fullname, nickname, email, resphone, comphone, privphone, " \
                        "streetaddress, debt FROM associate WHERE debt > 0.0"
        self._name = "populate_defaulter"
        self._locale = QLocale()

    def data(self, index, role=Qt.DisplayRole):
        if not index.isValid() or not (0<=index.row()<self.rowCount()):
            # invalid index
            return None
        record = self.get_record(index.row())
        column = index.column()
        if role == Qt.DisplayRole:
            if column == self.DEBT:
                return self._locale.toString(record.value("debt"), 'f', 2).replace('.','')
            else:
                return super(DefaulterTableModel, self).data(index, role)

    def headerData(self, section, orientation, role=Qt.DisplayRole):
        if role == Qt.TextAlignmentRole:
            if orientation == Qt.Horizontal:
                return int(Qt.AlignLeft|Qt.AlignVCenter)
            return int(Qt.AlignRight|Qt.AlignVCenter)

        if role != Qt.DisplayRole:
            return None

        if orientation == Qt.Horizontal:
            if section == self.DEBT:
                return unicode("Pendência (R$)".decode('utf-8'))
            else:
                return super(DefaulterTableModel, self).headerData(section, orientation, role)
        return section + 1
예제 #34
0
    def __init__(self, parent=None):
        super(EnvironmentDock, self).__init__(parent)
        # Store Ui() as class variable self.ui
        ui = Ui()
        self.ui =  ui
        self.ui.setupUi(self)
        self.mainWindow = self.parent()

        floatValidator = PySide.QtGui.QDoubleValidator()
        floatValidator.setRange(128, 4096)
        ui.widthEdit.setValidator(floatValidator)
        ui.heightEdit.setValidator(floatValidator)

        dpiValidator = PySide.QtGui.QDoubleValidator()
        dpiValidator.setRange(20, 1000)
        ui.dpiEdit.setValidator(dpiValidator)
        
        ui.widthEdit.textChanged.connect(self.viewSizeEditingFinished)
        ui.heightEdit.textChanged.connect(self.viewSizeEditingFinished)
        
        for idx in xrange(0, len(Languages)):
            ui.languageBox.addItem(QLocale.languageToString(Languages[idx]))
예제 #35
0
class BookEditForm(QScrollArea, Ui_BookForm):
    """ Interface for book edit """

    column = {
            'id':0, 'barcode':1, 'title':2, 'author':3, 's_author':4, 'publisher':5, 'year':6, 'price':7,
            'description':8, 'stock':9, 'image':10, 'availability':11 }
    IMG_SIZE = (150, 150)

    def __init__(self, record_id, parent=None):
        super(BookEditForm, self).__init__(parent)
        self.setupUi(self)
        # had to subclass this spinbox to support return grabbing
        self.edYear = ReturnKeySpinBox(self)
        self.edYearHolder.addWidget(self.edYear)
        # configuring id's for radio group
        self.radioAvailability.setId(self.rdSell,0)
        self.radioAvailability.setId(self.rdRent,1)
        self.radioAvailability.setId(self.rdInactive,2)
        # overlaying a clean button over the image (couldn't do it in designer)
        self.btnCleanImage = QPushButton()
        self.btnCleanImage.setIcon(QIcon(":icons/clean.png"))
        self.btnCleanImage.setFixedWidth(35)
        self.btnCleanImage.clicked.connect(self.clear_image)
        self.btnCleanImage.setVisible(False)
        clean_img_layout = QVBoxLayout(self.edImage)
        clean_img_layout.addWidget(self.btnCleanImage)
        clean_img_layout.setAlignment(Qt.AlignTop | Qt.AlignLeft)
        clean_img_layout.setContentsMargins(2,2,0,0)

        self._access = statics.access_level
        # for currency formatting
        self._locale = QLocale()
        self._record_id = record_id

        # had to hardcode these, wouldn't work otherwise:
        self.contentsLayout.setAlignment(self.groupBox, QtCore.Qt.AlignTop)
        self.contentsLayout.setAlignment(self.groupBox_2, QtCore.Qt.AlignTop)

        self.log = logging.getLogger('BookEditForm')

        self._subject_list = []

        self._removed_subjects = []
        self._added_subjects = []

        self.setup_model()
        self.fill_form()
        self.setup_fields()
        self._old_data = self.extract_input(text_only=True)

        # flag to indicate whether there were changes to the fields
        self._dirty = False
        # user did input an image
        self._image_set = False
        # image changed during edit
        self._image_changed = False

    def is_dirty(self):
        return self._dirty

    def setup_fields(self):
        """ setting up validators and stuff """
        # validators
        # forcing uppercasing on these fields
        self.edTitle.setValidator(UppercaseValidator())
        self.edAuthor.setValidator(UppercaseValidator())
        self.edSAuthor.setValidator(UppercaseValidator())
        self.edPublisher.setValidator(UppercaseValidator())
        self.edPrice.setValidator(CurrencyValidator(self.edPrice))
        self.edBarcode.setValidator(NumericValidator())
        self.edYear.setMinimum(1900)
        self.edYear.setMaximum(date.today().year)
        self.edYear.setValue(date.today().year)
        # fixing tab order
        self.setTabOrder(self.edPublisher, self.edYear)
        self.setTabOrder(self.edYear, self.edPrice)
        # connecting return key to tab
        lineEditList = self.findChildren(QLineEdit)
        for lineEdit in lineEditList:
            # had some problem with C++ originated objects
            if lineEdit.objectName() not in ['qt_spinbox_lineedit', 'edSubject']:
                lineEdit.returnPressed.connect(lineEdit.focusNextChild)
            # detect changes on line edits
            lineEdit.textChanged.connect(self.check_changes)
        # different behaviour for these
        self.edBarcode.textChanged.connect(self.check_barcode)
        self.edSubject.returnPressed.connect(self.on_btnAddSubject_clicked)

        # completers
        config_completer(self.edSubject, self._subject_model, "name")
        config_completer(self.edAuthor, self._author_model, "name")
        config_completer(self.edSAuthor, self._s_author_model, "name")
        config_completer(self.edPublisher, self._publisher_model, "name")

        # making image clickable
        clickable(self.edImage).connect(self.handle_image)

    def fill_form(self):
        # retrieving book info
        self.edBarcode.setText(self._record.value("barcode"))
        self.edTitle.setText(self._record.value("title"))
        self.edYear.setValue(self._record.value("year"))
        self.edDescription.setPlainText(self._record.value("description"))
        self.radioAvailability.button(self._record.value("availability")).setChecked(True)
        # retrieving image
        ba = QByteArray(self._record.value("image"))
        if ba:
            self._image_set = True
            img = qbytearray_to_qimage(ba)
            self.set_image(img, clean_visible=True)
        # currency
        # TODO: ARRUMAR
        self.edPrice.setText(self._locale.toString(self._record.value("price"), 'f', 2).replace('.',''))
        # qcompleter fields
        self.edAuthor.setText(self._get_name_from_id("author", self._record.value("author_id")))
        self.edSAuthor.setText(self._get_name_from_id("s_author", self._record.value("s_author_id")))
        self.edPublisher.setText(self._get_name_from_id("publisher", self._record.value("publisher_id")))

        # retrieving subjects
        for subj_record in self._subj_records:
            self.add_subject([subj_record.value("id"),subj_record.value("name")])

        # clearing changes
        self._added_subjects[:] = []
        self.refresh_tableSubjects()

    def clear_image(self):
        img = QImage(":icons/no_image.png")
        self.set_image(img, clean_visible=False)
        if self._image_set:
            self._image_set = False
        self._image_changed = True

    def handle_image(self):
        image_path = QFileDialog.getOpenFileName(self, "Escolha uma imagem", os.getenv("HOME"), "Imagens (*.png, *.jpg *.bmp)")[0]
        if os.path.exists(image_path):
            self.set_image(QImage(image_path), clean_visible=True)
            self._image_set = True
            self._image_changed = True

    def set_image(self, img, clean_visible=False):
        pix = QPixmap.fromImage(img)
        pix = pix.scaled(self.IMG_SIZE[0], self.IMG_SIZE[1], Qt.KeepAspectRatio)
        self.edImage.setPixmap(pix)
        self.edImage.setScaledContents(True)
        self.btnCleanImage.setVisible(clean_visible)

    def check_changes(self, txt):
        # getting sender info
        sender = self.sender().objectName().split('ed')[1].lower()
        if sender != 'subject' and self._old_data[sender] != txt:
            self._dirty = True

    def check_barcode(self, txt):
        if len(txt) == self.edBarcode.maxLength():
            self.edBarcode.focusNextChild()

    def extract_input(self, text_only=False):
        data = {}
        data['barcode'] = self.edBarcode.text()
        data['title'] = self.edTitle.text()

        # completer fields
        for c_field, line_edit in [("author", self.edAuthor), ("s_author", self.edSAuthor), ("publisher", self.edPublisher)]:
            if not text_only:
                data[c_field] = self._get_cfield_value(c_field, line_edit.text())
            else:
                data[c_field] = line_edit.text()
        data['year'] = self.edYear.value()
        data['price'] = self._locale.toDouble(self.edPrice.text())[0]
        data['description'] = self.edDescription.toPlainText()
        if not text_only and self._image_changed and self._image_set:
            data['image'] = qpixmap_to_qbytearray(self.edImage.pixmap())

        data['availability'] = self.radioAvailability.checkedId()

        return data

    def setup_model(self):
        db = Db_Instance("edit_book").get_instance()
        if not db.open():
            self.log.error(db.lastError().text())
            message = unicode("Erro de conexão\n\n""Banco de dados indisponível".decode('utf-8'))
            QMessageBox.critical(self, unicode("Seareiros - Edição de Livro".decode('utf-8')), message)
        else:
            # book
            self._model = QSqlRelationalTableModel(self, db=db)
            self._model.setTable("book")
            self._model.setFilter("id = " + str(self._record_id))
            # self._model.setRelation(self.column["author"], QSqlRelation("author", "id", "name"))
            # self._model.setRelation(self.column["s_author"], QSqlRelation("s_author", "id", "name"))
            # self._model.setRelation(self.column["publisher"], QSqlRelation("publisher", "id", "name"))
            self._model.select()
            self._record = self._model.record(0)
            # models for setting up qcompleters:
            # book_in_subject
            self._book_in_subj_model = QSqlTableModel(self, db=db)
            self._book_in_subj_model.setTable("book_in_subject")
            # subject
            self._subject_model = QSqlTableModel(self, db=db)
            self._subject_model.setTable("subject")
            self._subject_model.select()
            # author
            self._author_model = QSqlTableModel(self, db=db)
            self._author_model.setTable("author")
            self._author_model.select()
            # s_author
            self._s_author_model = QSqlTableModel(self, db=db)
            self._s_author_model.setTable("s_author")
            self._s_author_model.select()
            # publisher
            self._publisher_model = QSqlTableModel(self, db=db)
            self._publisher_model.setTable("publisher")
            self._publisher_model.select()

            # retrieving current subjects, should probably place this elsewhere but it's related to models
            self._subject_records = []
            sql_statement = """SELECT id, name FROM subject s, book_in_subject b_s
                               WHERE s.id = b_s.subject_id AND b_s.book_id = %s
                            """ % str(self._record_id)
            read_only_subject_model = QSqlQueryModel()
            read_only_subject_model.setQuery(sql_statement, db)
            # checking query validity
            if not read_only_subject_model.lastError().isValid():
                self._subj_records = iterate_model(read_only_subject_model)

    def update_data(self):
        data = self.extract_input()
        # checking fields that aren't inserted yet
        for val, model in [('author', self._author_model), ('s_author', self._s_author_model),
                           ('publisher', self._publisher_model)]:
            if isinstance(data[val], unicode):
                # needs to be inserted
                model.insertRow(0)
                model.setData(model.index(0,1), data[val])
                data[val] = submit_and_get_id(self, model, self.log)
                if not data[val]:
                    # won't proceed if this fails
                    return False
        for key,val in data.items():
            self._model.setData(self._model.index(0, self.column[key]), val)
        if 'image' not in data and self._image_changed:
            # user cleared the image
            ok = self._model.setData(self._model.index(0, self.column['image']), None)
            print ok

        # try to commit changes
        if not self._model.submitAll():
            self.log.error(self._model.lastError().text())
            message = unicode("Erro de transação\n\n""Não foi possível salvar no banco de dados".decode('utf-8'))
            QMessageBox.critical(self, "Seareiros - Edição de Livro", message)
            return False
        else:
            # updating subjects
            error = False
            # added subjects
            for subj in self._added_subjects:
                # the list has the format [id, text] for existing subjects or [None, text] otherwise
                if not subj[0]:
                    # need to insert the subject before associating it with the book
                    self._subject_model.insertRow(0)
                    self._subject_model.setData(self._subject_model.index(0,1), subj[1])
                    subj[0] = submit_and_get_id(self, self._subject_model, self.log)
                    if not subj[0]:
                        error = True
                        break
                # have a valid record id for the subject to be associated
                self._book_in_subj_model.insertRow(0)
                self._book_in_subj_model.setData(self._book_in_subj_model.index(0,0), self._record_id)
                self._book_in_subj_model.setData(self._book_in_subj_model.index(0,1), subj[0])
                ok = self._book_in_subj_model.submitAll()
                if not ok:
                    error = True
                    self.log.error(self._book_in_subj_model.setLastError().text())
                    break
            # removed subjects
            for removed_id in self._removed_subjects:
                self._book_in_subj_model.setFilter("book_id = %s AND subject_id = %s" % (str(self._record_id),str(removed_id)))
                self._book_in_subj_model.select()
                self._book_in_subj_model.removeRow(0)
                if self._book_in_subj_model.lastError().isValid():
                    error = True
                    self.log.error(self._book_in_subj_model.lastError().text())
                    break
            if not error:
                message = unicode("Sucesso!\n\n""O livro foi atualizado com êxito no banco de dados".decode('utf-8'))
                QMessageBox.information(self, unicode("Seareiros - Edição de Livro".decode('utf-8')), message)
            else:
                message = unicode("Erro\n\n""Associado alterado, "
                                  "porém ocorreu um problema ao salvar suas atividades".decode('utf-8'))
                QMessageBox.warning(self, unicode("Seareiros - Edição de Livro".decode('utf-8')), message)
            # if I don't set this flag here it'll trigger a warning for altering data on the form
            self._dirty = False
            return True

    def _get_id_from_name(self, table, name):
        db = Db_Instance(table + "_fetch_" + name + "_id").get_instance()
        if not db.open():
            return None
        else:
            query = QSqlQuery(db)
            query.prepare("SELECT id FROM %s WHERE name = :name" % table)
            query.bindValue(":name", name)
            query.exec_()
            if query.next():
                return query.record().value("id")
            else:
                return None

    def _get_name_from_id(self, table, id):
        db = Db_Instance(table + "_fetch_" + str(id) + "_name").get_instance()
        if not db.open():
            return None
        else:
            query = QSqlQuery(db)
            query.prepare("SELECT name FROM %s WHERE id = :id" % table)
            query.bindValue(":name", id)
            query.exec_()
            if query.next():
                return query.record().value("name")
            else:
                return None

    @QtCore.Slot()
    def on_btnAddSubject_clicked(self):
        txt = self.edSubject.text()
        if txt != '':
            id = self._get_id_from_name('subject', self.edSubject.text())
            if id:
                # known register
                data = [id, txt]
            else:
                # new data
                data = [None, txt]
            not_a_duplicate = self.add_subject(data)
            if not_a_duplicate:
                self.refresh_tableSubjects()
                self.edSubject.clear()
            self.edSubject.setFocus()

    @QtCore.Slot()
    def on_btnCleanSubjects_clicked(self):
        self.clear_table()
        self.edSubject.setFocus()

    def clear_table(self):
        # can't directly change activity_list here
        itens = [i for i in self._subject_list]
        for item in itens:
            self.remove_subject(item)
        self._added_subjects[:] = []

    def add_subject(self, data):
        """ adds a subject to the list except for duplicates """
        if data in self._subject_list:
            return False
        else:
            if self.is_in_del_queue(data[0]):
                self._removed_subjects.remove(data[0])
            else:
                self._added_subjects.append(data)
            self._subject_list.append(data)
            # sorts by name
            self._subject_list.sort(key=operator.itemgetter(1))
            return True

    def refresh_tableSubjects(self):
        if len(self._subject_list) > 0:
            self.tableSubjects.setColumnCount(len(self._subject_list[0])+1)
            col_labels = ["", "Nome", ""]
            self.tableSubjects.setHorizontalHeaderLabels(col_labels)
            self.tableSubjects.setColumnHidden(0, True)
        else:
            self.tableSubjects.setColumnCount(0)
        self.tableSubjects.setRowCount(len(self._subject_list))
        for i, row in enumerate(self._subject_list):
            for j, col in enumerate(row):
                item = QTableWidgetItem(col)
                self.tableSubjects.setItem(i, j, item)
            # icon to remove rows individually
            remove_icon = QIcon(":icons/conn_failed.png")
            remove_btn = QPushButton(remove_icon, "")
            remove_btn.clicked.connect(partial(self.remove_subject, subject=row))
            self.tableSubjects.setCellWidget(i, len(row), remove_btn)
        self.tableSubjects.resizeColumnsToContents()
        self.tableSubjects.horizontalHeader().setResizeMode(1, QHeaderView.Stretch)

    def is_in_del_queue(self, id):
        return id in self._removed_subjects

    def is_in_add_queue(self, data):
        return data in self._added_subjects

    def remove_subject(self, subject):
        # remove a row based on its value
        self._subject_list.remove(subject)
        if self.is_in_add_queue(subject):
             # unqueue previously added activity
            self._added_subjects.remove(subject)
        else:
            id = subject[0]
            if id:
                self._removed_subjects.append(id)
        self.refresh_tableSubjects()

    def _get_cfield_value(self, c_field, text):
        if text == '':
            return None
        id = self._get_id_from_name(c_field, text)
        if id:
            return id
        else:
            return text
예제 #36
0
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(598, 450)
        self.icon = QIcon(":/icons/uglytheme/48x48/polibeepsync.png")
        Form.setWindowIcon(self.icon)
        Form.setLocale(QLocale(QLocale.English, QLocale.UnitedStates))
        self.verticalLayout = QVBoxLayout(Form)
        self.verticalLayout.setObjectName("verticalLayout")

        self.tabWidget = QTabWidget(Form)
        self.tabWidget.setObjectName("tabWidget")

        # Tab General Settings
        self.tab = QWidget()
        self.tab.setObjectName("tab")
        self.horizontalLayout = QHBoxLayout(self.tab)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.verticalLayout_2 = QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.gridLayout = QGridLayout()
        self.gridLayout.setObjectName("gridLayout")
        self.label_2 = QLabel(self.tab)
        self.label_2.setObjectName("label_2")
        self.gridLayout.addWidget(self.label_2, 3, 0, 1, 1)
        self.label = QLabel(self.tab)
        self.label.setObjectName("label")
        self.gridLayout.addWidget(self.label, 1, 0, 1, 1)
        self.password = QLineEdit(self.tab)
        self.password.setMaximumSize(QSize(139, 16777215))
        self.password.setEchoMode(QLineEdit.Password)
        self.password.setObjectName("password")
        self.gridLayout.addWidget(self.password, 3, 1, 1, 1)
        self.userCode = QLineEdit(self.tab)
        self.userCode.setMaximumSize(QSize(139, 16777215))
        self.userCode.setText("")
        self.userCode.setObjectName("userCode")
        self.gridLayout.addWidget(self.userCode, 1, 1, 1, 1)
        spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                 QSizePolicy.Minimum)
        self.gridLayout.addItem(spacerItem, 1, 2, 1, 1)
        self.verticalLayout_2.addLayout(self.gridLayout)
        self.trylogin = QPushButton(self.tab)
        self.trylogin.setMaximumSize(QSize(154, 16777215))
        self.trylogin.setObjectName("trylogin")
        self.verticalLayout_2.addWidget(self.trylogin)
        self.login_attempt = QLabel(self.tab)
        self.login_attempt.setText("Logging in, please wait.")
        self.login_attempt.setStyleSheet("color: rgba(0, 0, 0, 0);")
        self.login_attempt.setObjectName("login_attempt")
        self.verticalLayout_2.addWidget(self.login_attempt)
        spacerItem1 = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                  QSizePolicy.Expanding)
        self.verticalLayout_2.addItem(spacerItem1)
        self.horizontalLayout_3 = QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.label_4 = QLabel(self.tab)
        self.label_4.setObjectName("label_4")
        self.horizontalLayout_3.addWidget(self.label_4)
        self.rootfolder = QLineEdit(self.tab)
        self.rootfolder.setMinimumSize(QSize(335, 0))
        self.rootfolder.setMaximumSize(QSize(335, 16777215))
        self.rootfolder.setInputMask("")
        self.rootfolder.setReadOnly(True)
        self.rootfolder.setObjectName("rootfolder")
        self.horizontalLayout_3.addWidget(self.rootfolder)
        self.changeRootFolder = QPushButton(self.tab)
        self.changeRootFolder.setObjectName("changeRootFolder")
        self.horizontalLayout_3.addWidget(self.changeRootFolder)
        spacerItem2 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                  QSizePolicy.Minimum)
        self.horizontalLayout_3.addItem(spacerItem2)
        self.verticalLayout_2.addLayout(self.horizontalLayout_3)
        self.horizontalLayout_5 = QHBoxLayout()
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
        self.label_5 = QLabel(self.tab)
        self.label_5.setObjectName("label_5")
        self.horizontalLayout_5.addWidget(self.label_5)
        self.timerMinutes = QSpinBox(self.tab)
        self.timerMinutes.setObjectName("timerMinutes")
        self.horizontalLayout_5.addWidget(self.timerMinutes)
        self.label_6 = QLabel(self.tab)
        self.label_6.setObjectName("label_6")
        self.horizontalLayout_5.addWidget(self.label_6)
        self.syncNow = QPushButton(self.tab)
        self.syncNow.setObjectName("syncNow")
        self.horizontalLayout_5.addWidget(self.syncNow)
        spacerItem3 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                  QSizePolicy.Minimum)
        self.horizontalLayout_5.addItem(spacerItem3)
        self.verticalLayout_2.addLayout(self.horizontalLayout_5)
        self.addSyncNewCourses = QCheckBox(self.tab)
        self.addSyncNewCourses.setObjectName("addSyncNewCourses")
        self.verticalLayout_2.addWidget(self.addSyncNewCourses)
        self.horizontalLayout.addLayout(self.verticalLayout_2)
        self.tabWidget.addTab(self.tab, "")

        # Tab Courses
        self.tab_2 = QWidget()
        self.tab_2.setObjectName("tab_2")
        self.horizontalLayout_2 = QHBoxLayout(self.tab_2)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.verticalLayout_3 = QVBoxLayout()
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.horizontalLayout_6 = QHBoxLayout()
        self.horizontalLayout_6.setObjectName("horizontalLayout_6")
        self.refreshCourses = QPushButton(self.tab_2)
        self.refreshCourses.setObjectName("refreshCourses")
        self.horizontalLayout_6.addWidget(self.refreshCourses)
        spacerItem4 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                  QSizePolicy.Minimum)
        self.horizontalLayout_6.addItem(spacerItem4)
        self.verticalLayout_3.addLayout(self.horizontalLayout_6)
        self.coursesView = CoursesListView(self.tab_2)
        self.coursesView.setObjectName("coursesView")
        self.verticalLayout_3.addWidget(self.coursesView)
        self.horizontalLayout_2.addLayout(self.verticalLayout_3)
        self.tabWidget.addTab(self.tab_2, "")

        # Tab Status
        self.tab_3 = QWidget()
        self.tab_3.setObjectName("tab_3")
        self.horizontalLayout_7 = QHBoxLayout(self.tab_3)
        self.horizontalLayout_7.setObjectName("horizontalLayout_7")
        self.verticalLayout_4 = QVBoxLayout()
        self.verticalLayout_4.setObjectName("verticalLayout_4")
        self.horizontalLayout_8 = QHBoxLayout()
        self.horizontalLayout_8.setObjectName("horizontalLayout_8")
        self.about = QPushButton(self.tab_3)
        self.about.setObjectName("about")
        self.horizontalLayout_8.addWidget(self.about)
        spacerItem5 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                  QSizePolicy.Minimum)
        self.horizontalLayout_8.addItem(spacerItem5)
        self.verticalLayout_4.addLayout(self.horizontalLayout_8)
        self.status = QTextEdit(self.tab_3)
        self.status.setTextInteractionFlags(Qt.TextSelectableByKeyboard
                                            | Qt.TextSelectableByMouse)
        self.status.setObjectName("status")
        self.verticalLayout_4.addWidget(self.status)
        self.horizontalLayout_7.addLayout(self.verticalLayout_4)
        self.tabWidget.addTab(self.tab_3, "")

        self.tab_4 = QWidget()
        self.tab_4.setObjectName("tab_4")
        self.verticalLayout.addWidget(self.tabWidget)

        self.okButton = QDialogButtonBox(Form)
        self.okButton.setStandardButtons(QDialogButtonBox.Ok)
        self.okButton.setObjectName("okButton")
        self.okButton.clicked.connect(self.hide)
        self.verticalLayout.addWidget(self.okButton)

        self.statusLabel = QLabel(Form)
        self.statusLabel.setObjectName("statusLabel")
        self.verticalLayout.addWidget(self.statusLabel)

        self.retranslateUi(Form)
        self.tabWidget.setCurrentIndex(0)
        QMetaObject.connectSlotsByName(Form)
예제 #37
0
 def testToNumberULongLongNegative(self):
     obj = QLocale(QLocale.C)
     self.assert_(not obj.toULongLong('-37')[1])
예제 #38
0
 def updateCountriesCombobox(self, languageIdx):
     countries = QLocale.countriesForLanguage(Languages[languageIdx])
     countryBox = self.ui.countryBox
     countryBox.clear()
     for country in countries:
         countryBox.addItem(QLocale.countryToString(country), country)
예제 #39
0
 def testToNumberFloat(self):
     obj = QLocale(QLocale.C)
     self.assertEqual((ctypes.c_float(37.109).value, True),
                      obj.toFloat('37.109'))
예제 #40
0
 def testToNumberULongLong(self):
     obj = QLocale(QLocale.C)
     self.assertEqual((ctypes.c_ulonglong(37).value, True),
                      obj.toULongLong('37'))
예제 #41
0
 def testToNumberDouble(self):
     obj = QLocale(QLocale.C)
     self.assertEqual((ctypes.c_double(37.109).value, True),
                      obj.toDouble('37.109'))
예제 #42
0
파일: Info.py 프로젝트: ra2003/xindex
    def initialize(self):
        locale = QLocale()
        model = self.state.model
        if not bool(model):
            self.browser.setHtml("<font color=red>Information can only "
                                 "be shown if an index is open</font>")
            return

        top, total, _ = self.state.indicatorCounts()
        fullname = QDir.toNativeSeparators(os.path.abspath(model.filename))
        creator = model.config(Gconf.Key.Creator)
        created = model.config("Created")
        created = locale.toString(
            QDateTime.fromString(created, "yyyy-MM-dd HH:mm:ss"))
        updated = locale.toString(QFileInfo(model.filename).lastModified())
        size = os.path.getsize(model.filename)
        KB = 1024
        MB = KB * KB
        if size < MB:
            size = "~{:,} KB ({:,} bytes)".format(round(size / KB), size)
        else:
            size = "~{:,} MB ({:,} bytes)".format(round(size / MB), size)
        filename = re.sub(r"\.xix$", "", os.path.basename(fullname),
                          re.IGNORECASE)
        version = str(model.version())
        secs = self.state.workTime + int(time.monotonic() -
                                         self.state.startTime)
        hours, secs = divmod(secs, 3600)
        if hours:
            worktime = "{:,}h{}'".format(hours, secs // 60)
        else:
            worktime = "{}'".format(secs // 60)
        uuid = model.config(UUID)
        LEFT_STYLE = """ style="
margin-right: 0;
padding-right: 0;
spacing-right: 0;
border-right: 0;
"
"""
        RIGHT_STYLE = """ style="
margin-left: 0;
padding-left: 0;
spacing-left: 0;
border-left: 0;
"
"""
        color1 = "#DDDDFF"
        color2 = "#EEEEFF"
        STYLE = ' style="background-color: {};"'
        texts = [
            """<html><table border=0 style="
background-color: {};
">""".format(color1)
        ]
        for i, (name, value, right, debug) in enumerate((
            ("Index", filename, False, False),
            ("Creator", creator, False, False),
            ("Filename", fullname, False, False),
            ("Size", size, False, False),
            ("Created", created, False, False),
            ("Updated", updated, False, False),
            ("Total Entries", "{:,}".format(total), True, False),
            ("Main Entries", "{:,}".format(top), True, False),
            ("Subentries", "{:,}".format(total - top), True, False),
            ("Worktime", worktime, True, False),
            (None, None, False, False),
            ("Index Format", version, True, False),
            ("Index UUID", uuid, True, True),
        )):
            if debug and not self.state.window.debug:
                continue
            if name is None:
                color1 = "#EEEEEE"
                color2 = "#DDDDDD"
                continue
            style = STYLE.format(color1 if i % 2 == 0 else color2)
            align = " align=right" if right else ""
            texts.append("""<tr{}><td{}>{}&nbsp;&nbsp;</td>
<td{}{}>{}</td></tr>""".format(style, LEFT_STYLE, html.escape(name), align,
                               RIGHT_STYLE, html.escape(value)))
        texts.append("</table></html>")
        self.browser.setHtml("".join(texts))
예제 #43
0
class BookOrderForm(QScrollArea, Ui_BookOForm):
    """ Interface for ordering books """

    column = { 'associate':1, 'obs':3, 'total':4, 'paid':5, 'type':7 }


    def __init__(self, parent=None):
        super(BookOrderForm, self).__init__(parent)
        self.setupUi(self)

        self._access = statics.access_level
        # for currency formatting
        self._locale = QLocale()

        # had to hardcode these, wouldn't work otherwise:
        self.contentsLayout.setAlignment(self.groupBox, QtCore.Qt.AlignTop)
        self.contentsLayout.setAlignment(self.groupBox_2, QtCore.Qt.AlignTop)
        self.contentsLayout.setAlignment(self.groupBox_3, QtCore.Qt.AlignTop)
        self.contentsLayout.setAlignment(self.groupBox_4, QtCore.Qt.AlignTop)


        self.log = logging.getLogger('BookOForm')

        self.setup_model()
        self.setup_fields()

        # associate present flag
        self._associate_id = None
        # book internals
        self._book_list = []
        self._total = 0.0

        # flag to indicate whether there were changes to the fields
        self._dirty = False

    def is_dirty(self):
        return self._dirty

    def setup_model(self):
        db = Db_Instance("oform_book").get_instance()
        if not db.open():
            self.log.error(db.lastError().text())
            message = unicode("Erro de conexão\n\n""Banco de dados indisponível".decode('utf-8'))
            QMessageBox.critical(self, "Seareiros - Livraria", message)
        else:
            # book order
            self._model = QSqlTableModel(self, db=db)
            self._model.setTable("order_request")
            # book order items
            self._items_model = QSqlTableModel(self, db=db)
            self._items_model.setTable("book_order_item")

    def setup_fields(self):
        """ setting up validators and stuff """
        # validators
        self.edBarcode.setValidator(NumericValidator())
        # hiding associate frame and clean button
        self.frameAssociate.setVisible(False)
        self.btnCleanAssociate.setVisible(False)
        # detect changes on edBarcode for dirtiness and completion
        self.edBarcode.textChanged.connect(self.check_changes)
        self.edBarcode.textChanged.connect(self.check_barcode)

    def check_changes(self, txt):
        if txt != '':
            self._dirty = True

    def check_barcode(self, txt):
        if len(txt) == self.edBarcode.maxLength():
            db = Db_Instance("obook_barcode_search").get_instance()
            try:
                if db.open():
                    query = QSqlQuery(db)
                    query.prepare("SELECT * FROM book WHERE barcode = :barcode")
                    query.bindValue(":barcode", txt)
                    query.exec_()
                    if query.next():
                        self.add_book_from_record(query.record())
                        self.edBarcode.clear()
                    else:
                        raise RecordNotFoundException
                else:
                    raise DbUnavailableException
            except RecordNotFoundException:
                message = unicode("Código de barra inválido!\n\n"""
                              "O código informado não corresponde a nenhum livro cadastrado".decode('utf-8'))
                QMessageBox.critical(self, "Seareiros - Livraria", message)
            except DbUnavailableException:
                self.log.error(db.lastError().text())
                message = unicode("Erro de conexão\n\n""Banco de dados indisponível".decode('utf-8'))
                QMessageBox.critical(self, "Seareiros - Livraria", message)
            self.edBarcode.setFocus()

    def submit_data(self):
        if len(self._book_list) == 0:
            message = unicode("Venda vazia!\n\n"""
                              "É necessário adicionar um livro antes de concluir uma venda".decode('utf-8'))
            QMessageBox.critical(self, "Seareiros - Livraria", message)
            self.edBarcode.setFocus()
            return False
        data = self.extract_input()
        # filling a book order
        self._model.insertRow(0)
        for key,val in data.items():
            self._model.setData(self._model.index(0, self.column[key]), val)
        order_id = submit_and_get_id(self, self._model, self.log)
        if order_id:
            # order creation success, placing items
            error = False
            for item in self._book_list:
                book_id = item[0]
                book_quantity = item[3]
                self._items_model.insertRow(0)
                self._items_model.setData(self._items_model.index(0,1), order_id)
                self._items_model.setData(self._items_model.index(0,2), book_id)
                self._items_model.setData(self._items_model.index(0,3), book_quantity)
                ok = self._items_model.submitAll()
                if not ok:
                    error = True
                    break
            if error:
                self.log.error(self._items_model.lastError().text())
                message = unicode("Erro\n\n""Venda registrada e contabilizada, porém ocorreu um problema e"
                              " não será possível visualizar seus itens.".decode('utf-8'))
                QMessageBox.warning(self, "Seareiros - Livraria", message)
                return False
            else:
                # all went fine
                # retrieving some brief info of the order to display at the main window
                if 'associate' in data:
                    desc = "Venda da livraria no valor de R$ %s para %s" % \
                           (self._locale.toString(data['total'], 'f', 2).replace('.',''), self.lblNickname.text())
                else:
                    desc = "Venda da livraria no valor de R$ %s" % self._locale.toString(data['total'], 'f', 2).replace('.','')
                if not log_to_history(self._model.database(), "venda_livraria", order_id, desc):
                    self.log.error(self._model.lastError().text())
                message = unicode("Sucesso!\n\n""Venda concluída.".decode('utf-8'))
                QMessageBox.information(self, "Seareiros - Livraria", message)
                return True
        # failed to insert a row
        return False

    def clear(self):
        """ Globally cleans this form """
        self._dirty = False
        for lineEdit in self.findChildren(QLineEdit):
            lineEdit.clear()
        # book
        self.clear_table()
        self.lblTotal.setText("0,00")
        # associate
        self.clear_associate()

        self.edBarcode.setFocus()

    def clear_associate(self):
        # resets associate frame
        self.lblName.clear()
        self.lblNickname.clear()
        self._associate_id = None
        self.frameAssociate.setVisible(False)
        self.btnCleanAssociate.setVisible(False)
        # can't allow an order to be paid later without an associate to relate to
        self.rdNotPaid.setEnabled(False)
        self.rdPaid.setChecked(True)

    @QtCore.Slot()
    def on_btnSelectAssociate_clicked(self):
        associate_dialog = AssociateSelectDialog()
        if associate_dialog.exec_() == QDialog.Accepted:
            record = associate_dialog.get_record()
            self._associate_id = record.value("id")
            self.set_associate_info(record.value("fullname"), record.value("nickname"))
            self.frameAssociate.setVisible(True)
            self.btnCleanAssociate.setVisible(True)
            # a registered associate can pay later
            self.rdNotPaid.setEnabled(True)
            self.edBarcode.setFocus()

    @QtCore.Slot()
    def on_btnSelectBook_clicked(self):
        book_dialog = BookSelectDialog()
        if book_dialog.exec_() == QDialog.Accepted:
            record = book_dialog.get_record()
            self.add_book_from_record(record)

    def add_book_from_record(self, record):
        book_id = record.value("id")
        book_title = record.value("title")
        book_price = record.value("price")
        book_quantity = 1
        book_stock = record.value("stock")
        data = [book_id, book_title, book_price, book_quantity, book_stock]
        try:
            self.add_book(data)
            self.refresh_tableBooks()
            self.edBarcode.clear()
            self.edBarcode.setFocus()
        except StockOverflowException:
            message = unicode("Estoque Insuficiente!\n\n""A quantidade do item excedeu o estoque".decode('utf-8'))
            QMessageBox.critical(self, "Seareiros - Livraria", message)

    def set_associate_info(self, fullname, nickname):
        self.lblName.setText(fullname)
        self.lblNickname.setText(nickname)

    @QtCore.Slot()
    def on_btnCleanAssociate_clicked(self):
        self.clear_associate()

    def update_total(self, price, add=True):
        if add:
            self._total += price
        else:
            self._total -= price
        txt = self._locale.toString(self._total, 'f', 2).replace('.','')
        if txt == '0':
            txt = txt.replace(txt, "0,00")
        self.lblTotal.setText(txt)

    @QtCore.Slot()
    def on_btnCleanBooks_clicked(self):
        self.clear_table()
        self._total = 0.0
        self.update_total(0.0)
        self.edBarcode.clear()
        self.edBarcode.setFocus()

    def clear_table(self):
        self._book_list = []
        self.tableBooks.clear()
        self.refresh_tableBooks()

    def add_book(self, data):
        """ adds a book to the list then sort it """
        # checking for duplicate
        dup_index = [i for i,x in enumerate(self._book_list) if x[0] == data[0]]
        if not dup_index:
            # not a duplicate
            self._book_list.append(data)
        else:
            # duplicate
            idx = dup_index[0]
            # increment quantity
            new_quantity = self._book_list[idx][3] + 1
            stock = self._book_list[idx][4]
            if new_quantity > stock:
                raise StockOverflowException
            else:
                self._book_list[idx][3] += 1
        self.update_total(data[2], add=True)
        # sorts by title
        self._book_list.sort(key=operator.itemgetter(1))

    def refresh_tableBooks(self):
        if len(self._book_list) > 0:
            self.tableBooks.setColumnCount(len(self._book_list[0])-1)
            col_labels = ["Livro", unicode("Preço (R$)".decode('utf-8')), "Qtd", ""]
            self.tableBooks.setHorizontalHeaderLabels(col_labels)
        else:
            self.tableBooks.setColumnCount(0)
        self.tableBooks.setRowCount(len(self._book_list))
        for i, row in enumerate(self._book_list):
            for j, col in enumerate(row):
                if j == 1:
                    # title
                    item = QTableWidgetItem(col)
                elif j == 2:
                    # price
                    item = QTableWidgetItem(self._locale.toString(col, 'f', 2).replace('.',''))
                elif j == 3:
                    # quantity
                    edQuantity = ReturnKeySpinBox(self)
                    edQuantity.setMinimum(1)
                    edQuantity.setMaximum(row[4])
                    edQuantity.setValue(col)
                    edQuantity.valueChanged.connect(partial(self.update_quantity, book=row))
                    self.tableBooks.setCellWidget(i, j-1, edQuantity)
                if j in [1,2]:
                    # ignoring id
                    self.tableBooks.setItem(i, j-1, item)
            # remove button on last column
            remove_icon = QIcon(":icons/conn_failed.png")
            remove_btn = QPushButton(remove_icon, "")
            remove_btn.clicked.connect(partial(self.remove_book, book=row))
            self.tableBooks.setCellWidget(i, len(row)-2, remove_btn)
        self.tableBooks.resizeColumnsToContents()
        self.tableBooks.horizontalHeader().setResizeMode(0, QHeaderView.Stretch)

    def remove_book(self, book):
        # remove a row based on its value
        subtract_value = book[2] * book[3]
        self._book_list.remove(book)
        self.refresh_tableBooks()
        self.update_total(subtract_value, add=False)

    def update_quantity(self, i, book):
        new_value = i
        old_value = book[3]
        if old_value == new_value:
            # this happens sometimes when refreshing the table
            return
        price = book[1]
        index = self._book_list.index(book)
        book[3] = new_value
        self._book_list[index] = book
        if new_value > old_value:
            # incremented
            self.update_total((new_value - old_value)*book[2], add=True)
        elif new_value < old_value:
            # decremented
            self.update_total((old_value - new_value)*book[2], add=False)

    def extract_input(self):
        data = {}
        if self._associate_id:
            data['associate'] = self._associate_id
        data['obs'] = self.edObs.toPlainText()
        data['total'] = self._total
        if self.rdPaid.isChecked():
            data['paid'] = True
        else:
            data['paid'] = False
        data['type'] = constants.ORDER_BOOK
        return data
예제 #44
0
        else:
            return ""

    def __setitem__(self, key, value):
        """Méthode magique sous-jacent à l'opérateur [] en écriture"""
        self.__settings.setValue(key, value)

    def __delitem__(self, key):
        """Méthode magique sous-jacent à l'opérateur del"""
        self.__settings.remove(key)


if __name__ == "__main__":
    """Main de test"""
    import sys
    from PySide.QtGui import QApplication
    from PySide.QtCore import QLibraryInfo, QLocale, QTranslator

    app = QApplication(sys.argv)

    locale = QLocale.system().name()
    translator = QTranslator()
    translator.load("qt_" + locale,
                    QLibraryInfo.location(QLibraryInfo.TranslationsPath))
    app.installTranslator(translator)

    ui = ConfigUI()
    ui.show()
    ret = app.exec_()
    sys.exit(ret)
예제 #45
0
            return self.__settings.value(key)
        else:
            return ""

    def __setitem__(self, key, value):
        """Méthode magique sous-jacent à l'opérateur [] en écriture"""
        self.__settings.setValue(key, value)

    def __delitem__(self, key):
        """Méthode magique sous-jacent à l'opérateur del"""
        self.__settings.remove(key)

if __name__ == "__main__":
    """Main de test"""
    import sys
    from PySide.QtGui import QApplication
    from PySide.QtCore import QLibraryInfo, QLocale, QTranslator

    app = QApplication(sys.argv)

    locale = QLocale.system().name()
    translator = QTranslator()
    translator.load("qt_" + locale,
        QLibraryInfo.location(QLibraryInfo.TranslationsPath))
    app.installTranslator(translator)

    ui = ConfigUI()
    ui.show()
    ret = app.exec_()
    sys.exit(ret)
예제 #46
0
from PySide.QtCore import QTranslator
from PySide.QtCore import QLocale
from PySide.QtCore import QLibraryInfo
from PySide.QtCore import Qt

from qrmainwindow import QtReduceMainWindow

app = QApplication(sys.argv)

app.setOrganizationName("The Reduce Project")
app.setOrganizationDomain("reduce-algebra.sourceforge.net")
app.setApplicationName("QReduce")

qtTranslator = QTranslator(app)
qtTranslator.load("qt_" + QLocale.system().name(),
                  QLibraryInfo.location(QLibraryInfo.TranslationsPath))
app.installTranslator(qtTranslator)

qreduceTranslator = QTranslator(app)
qreduceTranslator.load(sys.path[0] + "/" + "qreducetr." +
                       str(locale.getdefaultlocale()[0]))
#app.installTranslator(qreduceTranslator)

# app.setStyleSheet("QStatusBar::item { border: 0px solid black }");

app.setWindowIcon(QIcon(sys.path[0] + "/" + "Bumblebee.png"))

if os.uname()[0] == "Darwin":
    app.setAttribute(Qt.AA_DontShowIconsInMenus)
예제 #47
0
 def testToNumberULongLongNegative(self):
     obj = QLocale(QLocale.C)
     self.assert_(not obj.toULongLong('-37')[1])
예제 #48
0
 def testToNumberInt(self):
     obj = QLocale(QLocale.C)
     self.assertEqual((37, True), obj.toInt('37'))
예제 #49
0
 def testToNumberShort(self):
     obj = QLocale(QLocale.C)
     self.assertEqual((ctypes.c_short(37).value, True), obj.toShort('37'))
예제 #50
0
class BookTableModel(BaseTableModel):
    """ Model for book objects """

    ID, TITLE, AUTHOR, S_AUTHOR, PRICE, STOCK, AVAILABILITY = range(7)

    def __init__(self, parent=None, display_mode=constants.BOOK_ALL):
        super(BookTableModel, self).__init__(parent)
        self._sql_statement = "SELECT b.id, b.title, a.name as author, s_a.name as s_author, b.price, b.stock, b.availability " \
                "FROM book b " \
                "LEFT JOIN author a ON b.author_id = a.id " \
                "LEFT JOIN s_author s_a ON b.s_author_id = s_a.id"
        if display_mode == constants.BOOK_SELL:
            self._sql_statement += " WHERE b.availability = 0 AND b.stock > 0"
        elif display_mode == constants.BOOK_RENT:
            self._sql_statement += " WHERE b.availability = 1"
        self._name = "populate_book"
        self._locale = QLocale()

    def load(self):
        self.set_query_info(self._name, self._sql_statement)
        super(BookTableModel, self).load()

    def data(self, index, role=Qt.DisplayRole):
        if not index.isValid() or not (0<=index.row()<self.rowCount()):
            # invalid index
            return None

        record = self.get_record(index.row())
        column = index.column()
        if role == Qt.DisplayRole:
            if column == self.ID:
                return record.value("id")
            elif column == self.TITLE:
                return record.value("title")
            elif column == self.AUTHOR:
                return record.value("author")
            elif column == self.S_AUTHOR:
                return record.value("s_author")
            elif column == self.PRICE:
                return self._locale.toString(record.value("price"), 'f', 2).replace('.','')
            elif column == self.STOCK:
                return record.value("stock")
            elif column == self.AVAILABILITY:
                return self.extend_availability(record.value("availability"))
        return None

    def headerData(self, section, orientation, role=Qt.DisplayRole):
        if role == Qt.TextAlignmentRole:
            if orientation == Qt.Horizontal:
                return int(Qt.AlignLeft|Qt.AlignVCenter)
            return int(Qt.AlignRight|Qt.AlignVCenter)

        if role != Qt.DisplayRole:
            return None

        if orientation == Qt.Horizontal:
            if section == self.ID:
                return "Reg."
            elif section == self.TITLE:
                return unicode("Título".decode('utf-8'))
            elif section == self.AUTHOR:
                return "Autor"
            elif section == self.S_AUTHOR:
                return "Autor (Esp.)"
            elif section == self.PRICE:
                return unicode("Preço (R$)".decode('utf-8'))
            elif section == self.STOCK:
                return "Estoque"
            elif section == self.AVAILABILITY:
                return "Disponibilidade"
        return section + 1

    def extend_availability(self, availability):
        avail_list = ['Venda', unicode('Locação'.decode('utf-8')), 'Inativo']
        return avail_list[availability]