Ejemplo n.º 1
0
def getPixmapForImageName(name, smallIcon=True):
    """
    Returns the pixmap for the given name.
    If the pixmap can not be found a default icons will be returned.

    @param name: Name of the image.
    @type name: C{unicode}
    @param smallIcon: Flag indicating whether a small icon (16 pixels) or a large icon (24 pixels) is required.
    @type smallIcon: C{bool}

    @return: The Qt pixmap.
    @rtype: L{QPixmap<qt.QPixmap>}
    """

    result = None
    if not name is None:
        if smallIcon:
            name += "16.png"
        else:
            name += "24.png"
        result = QPixmap.fromMimeSource(name)
    if result is None or result.isNull():
        if smallIcon:
            result = QPixmap.fromMimeSource(_defaultSmallIconName)
        else:
            result = QPixmap.fromMimeSource(_defaultLargeIconName)
    return result
Ejemplo n.º 2
0
def getPixmapForImageName(name, smallIcon=True):
    """
    Returns the pixmap for the given name.
    If the pixmap can not be found a default icons will be returned.

    @param name: Name of the image.
    @type name: C{unicode}
    @param smallIcon: Flag indicating whether a small icon (16 pixels) or a large icon (24 pixels) is required.
    @type smallIcon: C{bool}

    @return: The Qt pixmap.
    @rtype: L{QPixmap<qt.QPixmap>}
    """

    result = None
    if not name is None:
        if smallIcon:
            name += "16.png"
        else:
            name += "24.png"
        result = QPixmap.fromMimeSource(name)
    if result is None or result.isNull():
        if smallIcon:
            result = QPixmap.fromMimeSource(_defaultSmallIconName)
        else:
            result = QPixmap.fromMimeSource(_defaultLargeIconName)
    return result
Ejemplo n.º 3
0
 def pixmap(self, size):
     """returns a background pixmap or None for isPlain"""
     self.__pmap = QBrush()
     if not self.isPlain:
         width = size.width()
         height = size.height()
         if self.tiled:
             width = self.imageWidth
             height = self.imageHeight
         cachekey = '{name}W{width}H{height}'.format(name=self.name,
                                                     width=width,
                                                     height=height)
         self.__pmap = QPixmapCache.find(cachekey)
         if not self.__pmap:
             renderer = QSvgRenderer(self.graphicsPath)
             if not renderer.isValid():
                 logException(
                     i18n(
                         'file <filename>%1</filename> contains no valid SVG',
                         self.graphicsPath))
             self.__pmap = QPixmap(width, height)
             self.__pmap.fill(Qt.transparent)
             painter = QPainter(self.__pmap)
             renderer.render(painter)
             QPixmapCache.insert(cachekey, self.__pmap)
     return self.__pmap
Ejemplo n.º 4
0
def main():
    if not os.path.exists(os.path.expanduser("~/.pyqlogger")):
        os.mkdir(os.path.expanduser("~/.pyqlogger"))    
    settings = Settings.Settings.load()
    UI.prepareModule(settings)
    app =  UI.API.KQApplication(sys.argv, None)
    stat = UI.API.prepareCommandLine()    
    pic = QPixmap ( 150, 50)
    pic.fill()
    loginsplash = QSplashScreen( pic )
    pixmap = QPixmap( "splash.png" )
    splash = QSplashScreen( pixmap )
    splash.show()
    splash.message( "Loading forms...",alignflag )
    qApp.processEvents()
    load_forms(splash,app,settings)
    splash.message( "Loading plugins...",alignflag )
    qApp.processEvents()
    manager = Manager.load(__FORMS__["Main"]["Impl"])
    del splash
    acc = None
    pwd = None
    if settings.AutoLogin: # check if we have auto login info
        acc = settings.accountByName(settings.AutoLogin)
        pwd = acc.Password

    while True:
        if not acc:
            wnd = __FORMS__["Login"]
            if wnd["Impl"].init(settings,__FORMS__,manager):
                if wnd["Class"].exec_loop() == QDialog.Accepted:
                    acc = wnd["Impl"].acc
                    pwd = str(wnd["Impl"].edtPassword.text())
        if not acc or not pwd:
            break
        else:
            (acc.Password,oldpwd) = (pwd,acc.Password)            
            acc.init()
            loginsplash.show()
            loginsplash.message( "Logging in...",Qt.AlignCenter)            
            logres = acc.login()
            loginsplash.hide()
            acc.Password = oldpwd
            if not logres:
                QMessageBox.warning(None,"Failed!","""Cannot login!""")
                acc = None
            else:
                wnd = __FORMS__["Main"]
                acc.init()
                wnd["Impl"].init(settings,__FORMS__, acc, pwd,\
                                 manager)
                app.setMainWidget(wnd["Class"])
                wnd["Class"].show()
                #splash.finish(wnd["Class"])
                app.exec_loop()
                if wnd["Impl"].reload:
                    acc = None
                else:
                    break
Ejemplo n.º 5
0
def main():
    if not os.path.exists(os.path.expanduser("~/.pyqlogger")):
        os.mkdir(os.path.expanduser("~/.pyqlogger"))
    settings = Settings.Settings.load()
    UI.prepareModule(settings)
    app = UI.API.KQApplication(sys.argv, None)
    stat = UI.API.prepareCommandLine()
    pic = QPixmap(150, 50)
    pic.fill()
    loginsplash = QSplashScreen(pic)
    pixmap = QPixmap("splash.png")
    splash = QSplashScreen(pixmap)
    splash.show()
    splash.message("Loading forms...", alignflag)
    qApp.processEvents()
    load_forms(splash, app, settings)
    splash.message("Loading plugins...", alignflag)
    qApp.processEvents()
    manager = Manager.load(__FORMS__["Main"]["Impl"])
    del splash
    acc = None
    pwd = None
    if settings.AutoLogin:  # check if we have auto login info
        acc = settings.accountByName(settings.AutoLogin)
        pwd = acc.Password

    while True:
        if not acc:
            wnd = __FORMS__["Login"]
            if wnd["Impl"].init(settings, __FORMS__, manager):
                if wnd["Class"].exec_loop() == QDialog.Accepted:
                    acc = wnd["Impl"].acc
                    pwd = str(wnd["Impl"].edtPassword.text())
        if not acc or not pwd:
            break
        else:
            (acc.Password, oldpwd) = (pwd, acc.Password)
            acc.init()
            loginsplash.show()
            loginsplash.message("Logging in...", Qt.AlignCenter)
            logres = acc.login()
            loginsplash.hide()
            acc.Password = oldpwd
            if not logres:
                QMessageBox.warning(None, "Failed!", """Cannot login!""")
                acc = None
            else:
                wnd = __FORMS__["Main"]
                acc.init()
                wnd["Impl"].init(settings,__FORMS__, acc, pwd,\
                                 manager)
                app.setMainWidget(wnd["Class"])
                wnd["Class"].show()
                #splash.finish(wnd["Class"])
                app.exec_loop()
                if wnd["Impl"].reload:
                    acc = None
                else:
                    break
Ejemplo n.º 6
0
 def getPixmap(self):
     image = None
     if self.icon:                
         if type(self.icon) == str:
             image = QPixmap()
             image.loadFromData(self.icon)
         elif type(self.icon) == list:
             image = QPixmap(self.icon)
     return image
 def btnRefresh_clicked(self):
     if str(self.editUrl.text()):
         try:
             img = urllib2.urlopen(str(self.editUrl.text())).read()
             pic = QPixmap()
             pic.loadFromData(img)
             if not str(self.editWidth.text()):
                 self.editWidth.setText(str(pic.width()))
             if not str(self.editHeight.text()):
                 self.editHeight.setText(str(pic.height()))
             self.previewImage.setPixmap(pic)
         except:
             QMessageBox.warning(self, "Warning", "Cannot open the image url!")
Ejemplo n.º 8
0
 def _setupTray(app, wnd):
     try:
         icons = KIconLoader()
         systray = KSystemTray(wnd["Class"])
         p = QPixmap()
         p.loadFromData(icon)
         systray.setPixmap(p)
         QToolTip.add(systray, "PyQLogger - Blogger GUI")
         systray.show()
         wnd["Impl"].systray = systray
     except Exception, inst:
         sys.stderr.write(
             "setupKDE: cannot set tray, exception: %s\n" %
             inst)
Ejemplo n.º 9
0
    def getIconName(self, iconList, preselected=None):
        """
        Show and handle dialog, and return name of selected icon.

        @param iconList: List of icons.
        @type iconList: List of strings.
        @param preselected: name of icon selected when opening dialog (opt.)
        @type preselected: C{String}

        @return: The selected items.
        @rtype: C{list} of C{unicode}.
        """

        self.iconListBox.clear()
        iconList.sort()
        for icon in iconList:
            pixmap = QPixmap.fromMimeSource(icon.largeName)
            self.iconListBox.insertItem(pixmap, icon.baseName, -1)

        if preselected:
            preselectedItem = self.iconListBox.findItem(preselected, Qt.ExactMatch | Qt.CaseSensitive)
            if preselectedItem != 0:
                self.iconListBox.setSelected(preselectedItem, True)

        self.exec_loop()

        result = list()
        if self.button == "ok":
            for index in range(0, self.iconListBox.numRows()):
                item = self.iconListBox.item(index)
                if item.isSelected():
                    result.append(unicode(item.text()))
        return result
Ejemplo n.º 10
0
 def genWindPixmap(self):
     """prepare wind tiles"""
     pwind = PlayerWind(self.__wind)
     pwind.prevailing = self.__wind == Wind.all4[min(self.__roundsFinished, 3)]
     pMap = QPixmap(40, 40)
     pMap.fill(Qt.transparent)
     painter = QPainter(pMap)
     painter.setRenderHint(QPainter.Antialiasing)
     painter.scale(0.40, 0.40)
     pwind.paint(painter, QStyleOptionGraphicsItem())
     for child in pwind.childItems():
         if isinstance(child, QGraphicsSvgItem):
             with Painter(painter):
                 painter.translate(child.mapToParent(0.0, 0.0))
                 child.paint(painter, QStyleOptionGraphicsItem())
     return pMap
Ejemplo n.º 11
0
def showSplash(splashImageName):
    """
    Function which shows a nice splash screen.

    @param splashImageName: Name of the splash screen image.
    @type splashImageName: C{unicode}
    """

    screen = QApplication.desktop().screenGeometry()

    if not _haveImagesAsModule:
        addQtImagePath(constants.LOCAL_INSTALLED_ICONS_DIRECTORY_PATH)
    dfPicture = QPixmap.fromMimeSource(splashImageName)

    dfSplash = QLabel(None, "splash",
                      Qt.WDestructiveClose | Qt.WStyle_Customize | Qt.WStyle_NoBorder |\
                      Qt.WX11BypassWM | Qt.WStyle_StaysOnTop)
    dfSplash.setFrameStyle(QFrame.WinPanel | QFrame.Raised)
    dfSplash.setPixmap(dfPicture)
    dfSplash.setCaption("DataFinder")
    dfSplash.setAutoResize(1)
    dfSplash.move(QPoint(screen.center().x() - dfSplash.width() / 2,
                         screen.center().y() - dfSplash.height() / 2))
    dfSplash.show()
    dfSplash.repaint(0)
    QApplication.flush()
    return dfSplash
Ejemplo n.º 12
0
def showSplash(splashImageName):
    """
    Function which shows a nice splash screen.

    @param splashImageName: Name of the splash screen image.
    @type splashImageName: C{unicode}
    """

    screen = QApplication.desktop().screenGeometry()

    if not _haveImagesAsModule:
        addQtImagePath(constants.LOCAL_INSTALLED_ICONS_DIRECTORY_PATH)
    dfPicture = QPixmap.fromMimeSource(splashImageName)

    dfSplash = QLabel(None, "splash",
                      Qt.WDestructiveClose | Qt.WStyle_Customize | Qt.WStyle_NoBorder |\
                      Qt.WX11BypassWM | Qt.WStyle_StaysOnTop)
    dfSplash.setFrameStyle(QFrame.WinPanel | QFrame.Raised)
    dfSplash.setPixmap(dfPicture)
    dfSplash.setCaption("DataFinder")
    dfSplash.setAutoResize(1)
    dfSplash.move(
        QPoint(screen.center().x() - dfSplash.width() / 2,
               screen.center().y() - dfSplash.height() / 2))
    dfSplash.show()
    dfSplash.repaint(0)
    QApplication.flush()
    return dfSplash
Ejemplo n.º 13
0
    def _setNodeIcon(self):
        """ Sets the node icon. """

        pixmap = utils.getPixmapForImageName(self._dataTypeModel.myIconName)
        mask = QPixmap.fromMimeSource(u"newMask16.png")
        pixmap.setMask(mask.createHeuristicMask())
        icon = QIconSet(pixmap)
        self._parentFrame.changeIconPixmap(icon, self.title, self._dataTypeModel.myTitle)
Ejemplo n.º 14
0
    def _setNodeIcon(self):
        """ Sets the node icon. """

        pixmap = utils.getPixmapForImageName(self._dataTypeModel.myIconName)
        mask = QPixmap.fromMimeSource(u"newMask16.png")
        pixmap.setMask(mask.createHeuristicMask())
        icon = QIconSet(pixmap)
        self._parentFrame.changeIconPixmap(icon, self.title,
                                           self._dataTypeModel.myTitle)
Ejemplo n.º 15
0
Archivo: board.py Proyecto: KDE/kajongg
 def genWINDPIXMAPS():
     """prepare wind tiles"""
     tileset = Tileset(Internal.Preferences.windTilesetName)
     for wind in Wind.all4:
         for prevailing in False, True:
             pwind = PlayerWind(wind, tileset, prevailing)
             pMap = QPixmap(40, 40)
             pMap.fill(Qt.transparent)
             painter = QPainter(pMap)
             painter.setRenderHint(QPainter.Antialiasing)
             painter.scale(0.40, 0.40)
             pwind.paint(painter, QStyleOptionGraphicsItem())
             for child in pwind.childItems():
                 if isinstance(child, QGraphicsSvgItem):
                     with Painter(painter):
                         painter.translate(child.mapToParent(0.0, 0.0))
                         child.paint(painter, QStyleOptionGraphicsItem())
             WINDPIXMAPS[(wind, prevailing)] = pMap
Ejemplo n.º 16
0
class SearchByItemTypePlugin:
    def __init__(self, pluginContext):
        parentMenu = pluginContext.getPulldownMenu(
            4)  # should be the Tools menu
        self.typeMenu = QPopupMenu(parentMenu)
        iconWrapper = QIconSet(SearchByItemTypePlugin.resultIcon)
        parentMenu.insertItem(iconWrapper, _('Find Items By Type'),
                              self.typeMenu)
        parentMenu.connect(self.typeMenu, SIGNAL('activated(int)'),
                           self.doSearch)
        self.context = pluginContext
        self.context.setFileOpenCallback(self.updateTypeMenu)

    def updateTypeMenu(self):
        typeNames = self.context.getNodeFormatNames()
        self.typeMenu.clear()
        index = 0
        for name in typeNames:
            self.typeMenu.insertItem(name, index)
            index += 1

    def doSearch(self, typeIndex):
        typeName = self.context.getNodeFormatNames()[typeIndex]
        rootNode = self.context.getRootNode()
        self.context.changeSelection([rootNode
                                      ])  # move selection out of the way
        rootNode.openBranch(False)  # reset tree structure
        self.searchSubtree(rootNode, typeName)  # reconfigure tree structure
        self.context.updateViews()  # initialize widgets
        self.highlightSubtree(rootNode, typeName)  # apply highlights

    def searchSubtree(self, node, typeName):
        if node.nodeFormat.name == typeName:
            node.openParents(False)
        for child in node.childList:
            self.searchSubtree(child, typeName)

    def highlightSubtree(self, node, typeName):
        if node.nodeFormat.name == typeName:
            node.viewData.setPixmap(0, SearchByItemTypePlugin.resultIcon)
        for child in node.childList:
            self.highlightSubtree(child, typeName)

    resultIcon = QPixmap([
        "16 16 22 1", ". c none", "a c #000000", "i c #202000", "t c #454500",
        "c c #505030", "y c #777777", "x c #7e7e88", "p c #808000",
        "j c #828200", "r c #858500", "n c #888800", "v c #8c8c00",
        "b c #9090a0", "u c #969600", "q c #a4a428", "m c #abab6f",
        "o c #acac20", "w c #b4b428", "k c #b7978f", "h c #caca18",
        "# c #d7a700", "d c #ffc0a0", "................", "................",
        "................", "................", "................",
        "................", "................", "...###########..",
        "abcdddddddddddh.", "aidddddddjkkkm..", "andddddddo......",
        "apddddddq.......", "arddddd#........", "atuvvnw.........",
        "ax..............", "yy.............."
    ])
Ejemplo n.º 17
0
 def __fillLastMeldComboWith(self, winnerMelds, indexedMeld, lastTile):
     """fill last meld combo with prepared content"""
     winner = self.game.winner
     faceWidth = winner.handBoard.tileset.faceSize.width() * 0.5
     faceHeight = winner.handBoard.tileset.faceSize.height() * 0.5
     restoredIdx = None
     for meld in winnerMelds:
         pixMap = QPixmap(faceWidth * len(meld), faceHeight)
         pixMap.fill(Qt.transparent)
         self.__meldPixMaps.append(pixMap)
         painter = QPainter(pixMap)
         for element in meld:
             painter.drawPixmap(
                 0,
                 0,
                 winner.handBoard.tilesByElement(element)[0].pixmapFromSvg(
                     QSize(faceWidth, faceHeight), withBorders=False
                 ),
             )
             painter.translate(QPointF(faceWidth, 0.0))
         self.cbLastMeld.addItem(QIcon(pixMap), "", toQVariant(str(meld)))
         if indexedMeld == str(meld):
             restoredIdx = self.cbLastMeld.count() - 1
     if not restoredIdx and indexedMeld:
         # try again, maybe the meld changed between concealed and exposed
         indexedMeld = indexedMeld.lower()
         for idx in range(self.cbLastMeld.count()):
             meldContent = str(variantValue(self.cbLastMeld.itemData(idx)))
             if indexedMeld == meldContent.lower():
                 restoredIdx = idx
                 if lastTile not in meldContent:
                     lastTile = lastTile.swapped
                     assert lastTile in meldContent
                     with BlockSignals(self.cbLastTile):  # we want to continue right here
                         idx = self.cbLastTile.findData(toQVariant(lastTile))
                         self.cbLastTile.setCurrentIndex(idx)
                 break
     if not restoredIdx:
         restoredIdx = 0
     self.cbLastMeld.setCurrentIndex(restoredIdx)
     self.cbLastMeld.setIconSize(QSize(faceWidth * 3, faceHeight))
 def SimpleButton(parent, title, handler, page=None, image=None):
     tabpage = parent.getPage(page)
     button = QPushButton(tabpage)
     if image : 
         bi = QPixmap()
         bi.loadFromData(image, "PNG")
         button.setIconSet(QIconSet(bi))
         w = bi.width()+3
         h = bi.height()+3
         if w < 32:
             w = 32
         if h < 32:
             h = 32
         button.setMaximumSize(QSize(w, h))
     else:
         button.setText(title)
     QToolTip.add(button, title)
     parent.connect(button, SIGNAL("clicked()"), handler)
     button.show()
     p = ToolbarPlugin(parent)
     p.getWidget = lambda: button
Ejemplo n.º 19
0
 def pixmapFromSvg(self, pmapSize=None, withBorders=None):
     """returns a pixmap with default size as given in SVG
     and optional borders/shadows"""
     if withBorders is None:
         withBorders = Internal.Preferences.showShadows
     if withBorders:
         wantSize = self.tileset.tileSize.toSize()
     else:
         wantSize = self.tileset.faceSize.toSize()
     if not pmapSize:
         pmapSize = wantSize
     result = QPixmap(pmapSize)
     result.fill(Qt.transparent)
     painter = QPainter(result)
     if not painter.isActive():
         logException(
             'painter is not active. Wanted size: %s' %
             str(pmapSize))
     try:
         xScale = float(pmapSize.width()) / wantSize.width()
         yScale = float(pmapSize.height()) / wantSize.height()
     except ZeroDivisionError:
         xScale = 1
         yScale = 1
     if not withBorders:
         painter.scale(*self.tileset.tileFaceRelation())
         painter.translate(-self.facePos())
     renderer = self.tileset.renderer()
     renderer.render(painter, self.__elementId())
     painter.resetTransform()
     self._drawDarkness(painter)
     if self.showFace():
         faceSize = self.tileset.faceSize.toSize()
         faceSize = QSize(
             faceSize.width() * xScale,
             faceSize.height() * yScale)
         painter.translate(self.facePos())
         renderer.render(painter, self.tileset.svgName[self.tile.exposed],
                         QRectF(QPointF(), QSizeF(faceSize)))
     return result
Ejemplo n.º 20
0
    def __init__(self, icnPxmp, icnLbl, icnCnvs):
        """ Constructor."""

        QCanvasRectangle.__init__(self, icnCnvs)

        self.isMarked = 0

        self.partialRelations = []
        self.iconType = 0

        self.iconLabel = icnLbl
        self.iconLabelWidth = 0
        self.iconLabelHeight = 0
        self.iconPainterWidth = 0
        self.iconPixmap = icnPxmp
        self.iconImage = None

        self.scaleMaskUnmarked = QPixmap.convertToImage(
            QPixmap.fromMimeSource("layer01.png"))
        self.scaleMaskMarked = QPixmap.convertToImage(
            QPixmap.fromMimeSource("layer02.png"))
        self.scaleMaskHighlight = QPixmap.convertToImage(
            QPixmap.fromMimeSource("layer03.png"))
        self.scaledMaskUnmarked = self.scaleMaskUnmarked
        self.scaledMaskMarked = self.scaleMaskMarked
        self.scaledMaskHighlight = self.scaleMaskHighlight

        self.setIconPixmap(icnPxmp)
        self.setIconLabel(self.iconLabel)
Ejemplo n.º 21
0
    def __init__(self, icnPxmp, icnLbl, icnCnvs):
        """ Constructor."""
        
        QCanvasRectangle.__init__(self, icnCnvs)
        
        self.isMarked = 0
        
        self.partialRelations = []
        self.iconType = 0
        
        self.iconLabel = icnLbl
        self.iconLabelWidth = 0
        self.iconLabelHeight = 0
        self.iconPainterWidth = 0
        self.iconPixmap = icnPxmp
        self.iconImage  = None

        self.scaleMaskUnmarked = QPixmap.convertToImage(QPixmap.fromMimeSource("layer01.png"))
        self.scaleMaskMarked = QPixmap.convertToImage(QPixmap.fromMimeSource("layer02.png"))
        self.scaleMaskHighlight = QPixmap.convertToImage(QPixmap.fromMimeSource("layer03.png"))
        self.scaledMaskUnmarked = self.scaleMaskUnmarked
        self.scaledMaskMarked = self.scaleMaskMarked
        self.scaledMaskHighlight = self.scaleMaskHighlight

        self.setIconPixmap(icnPxmp)
        self.setIconLabel(self.iconLabel)
Ejemplo n.º 22
0
 def pixmapFromSvg(self, pmapSize=None, withBorders=None):
     """returns a pixmap with default size as given in SVG
     and optional borders/shadows"""
     if withBorders is None:
         withBorders = Internal.Preferences.showShadows
     if withBorders:
         wantSize = self.tileset.tileSize.toSize()
     else:
         wantSize = self.tileset.faceSize.toSize()
     if not pmapSize:
         pmapSize = wantSize
     result = QPixmap(pmapSize)
     result.fill(Qt.transparent)
     painter = QPainter(result)
     if not painter.isActive():
         logException(
             'painter is not active. Wanted size: %s' %
             str(pmapSize))
     try:
         xScale = float(pmapSize.width()) / wantSize.width()
         yScale = float(pmapSize.height()) / wantSize.height()
     except ZeroDivisionError:
         xScale = 1
         yScale = 1
     if not withBorders:
         painter.scale(*self.tileset.tileFaceRelation())
         painter.translate(-self.facePos())
     renderer = self.tileset.renderer()
     renderer.render(painter, self.__elementId())
     painter.resetTransform()
     self._drawDarkness(painter)
     if self.showFace():
         faceSize = self.tileset.faceSize.toSize()
         faceSize = QSize(
             faceSize.width() * xScale,
             faceSize.height() * yScale)
         painter.translate(self.facePos())
         renderer.render(painter, self.tileset.svgName[self.tile.exposed],
                         QRectF(QPointF(), QSizeF(faceSize)))
     return result
Ejemplo n.º 23
0
 def __fillLastMeldComboWith(self, winnerMelds, indexedMeld, lastTile):
     """fill last meld combo with prepared content"""
     winner = self.game.winner
     faceWidth = winner.handBoard.tileset.faceSize.width() * 0.5
     faceHeight = winner.handBoard.tileset.faceSize.height() * 0.5
     restoredIdx = None
     for meld in winnerMelds:
         pixMap = QPixmap(faceWidth * len(meld), faceHeight)
         pixMap.fill(Qt.transparent)
         self.__meldPixMaps.append(pixMap)
         painter = QPainter(pixMap)
         for element in meld:
             painter.drawPixmap(
                 0, 0,
                 winner.handBoard.tilesByElement(element)[0].pixmapFromSvg(
                     QSize(faceWidth, faceHeight), withBorders=False))
             painter.translate(QPointF(faceWidth, 0.0))
         self.cbLastMeld.addItem(QIcon(pixMap), '', str(meld))
         if indexedMeld == str(meld):
             restoredIdx = self.cbLastMeld.count() - 1
     if not restoredIdx and indexedMeld:
         # try again, maybe the meld changed between concealed and exposed
         indexedMeld = indexedMeld.lower()
         for idx in range(self.cbLastMeld.count()):
             meldContent = str(self.cbLastMeld.itemData(idx))
             if indexedMeld == meldContent.lower():
                 restoredIdx = idx
                 if lastTile not in meldContent:
                     lastTile = lastTile.swapped
                     assert lastTile in meldContent
                     with BlockSignals(self.cbLastTile
                                       ):  # we want to continue right here
                         idx = self.cbLastTile.findData(lastTile)
                         self.cbLastTile.setCurrentIndex(idx)
                 break
     if not restoredIdx:
         restoredIdx = 0
     self.cbLastMeld.setCurrentIndex(restoredIdx)
     self.cbLastMeld.setIconSize(QSize(faceWidth * 3, faceHeight))
Ejemplo n.º 24
0
    def drawShape(self, p):
        """ Draws the icon. """

        p.setPen(QPen(QColor(100, 100, 100), 0))

        markPixmap = QPixmap(self.scaledMaskUnmarked)

        if self.isMarked == 1:
            markPixmap = QPixmap(self.scaledMaskMarked)
            p.setPen(QPen(QColor(0, 0, 0), 0))
        if self.isMarked == 2:
            markPixmap = QPixmap(self.scaledMaskHighlight)
            p.setPen(QPen(QColor(0, 0, 0), 0))

        p.drawPixmap(self.x(), self.y(), markPixmap)
        p.drawPixmap(
            self.x() + (self.iconPainterWidth - self.iconPixmap.width()) / 2,
            self.y() + 4, self.iconPixmap)
        p.drawText(
            self.x() + (self.iconPainterWidth - self.iconLabelWidth) / 2,
            self.y() + self.iconPixmap.height() + self.iconLabelHeight + 4,
            self.iconLabel)
 def __open(self, txt, btn):
     filename = str(
         QFileDialog.getOpenFileName(
             None, "Images (*.png *.jpg *.gif)", self, "open image file", "Choose a file to open"
         )
     )
     txt.setText(filename)
     ok = False
     try:
         pic = QPixmap()
         if pic.loadFromData(open(filename, "rb").read()):
             ok = True
             if not str(self.editWidth.text()):
                 self.editWidth.setText(str(pic.width()))
             if not str(self.editHeight.text()):
                 self.editHeight.setText(str(pic.height()))
             self.previewImage.setPixmap(pic)
             btn.setEnabled(True)
     except:
         ok = False
     if not ok:
         QMessageBox.warning(self, "Warning", "Cannot open the image file!")
         self.previewImage.setPixmap(QPixmap())
         btn.setEnabled(False)
Ejemplo n.º 26
0
 def btnRefresh_clicked(self):
     if str(self.editUrl.text()):
         try:
             img = urllib2.urlopen(str(self.editUrl.text())).read()
             pic = QPixmap()
             pic.loadFromData(img)
             if not str(self.editWidth.text()):
                 self.editWidth.setText(str(pic.width()))
             if not str(self.editHeight.text()):
                 self.editHeight.setText(str(pic.height()))
             self.previewImage.setPixmap(pic)
         except:
             QMessageBox.warning(self, "Warning",
                                 "Cannot open the image url!")
Ejemplo n.º 27
0
 def pixmap(self, size):
     """returns a background pixmap or None for isPlain"""
     self.__pmap = None
     if not self.isPlain:
         width = size.width()
         height = size.height()
         if self.tiled:
             width = self.imageWidth
             height = self.imageHeight
         cachekey = QString(u'{name}W{width}H{height}'.format(
             name=self.name, width=width, height=height))
         self.__pmap = QPixmapCache.find(cachekey)
         if not self.__pmap:
             renderer = QSvgRenderer(self.__graphicspath)
             if not renderer.isValid():
                 logException(BackgroundException(
                     m18n('file <filename>%1</filename> contains no valid SVG', self.__graphicspath)))
             self.__pmap = QPixmap(width, height)
             self.__pmap.fill(Qt.transparent)
             painter = QPainter(self.__pmap)
             renderer.render(painter)
             QPixmapCache.insert(cachekey, self.__pmap)
     return self.__pmap
 def SimpleButton(parent, title, handler, page=None, image=None):
     tabpage = parent.getPage(page)
     button = QPushButton(tabpage)
     if image:
         bi = QPixmap()
         bi.loadFromData(image, "PNG")
         button.setIconSet(QIconSet(bi))
         w = bi.width() + 3
         h = bi.height() + 3
         if w < 32:
             w = 32
         if h < 32:
             h = 32
         button.setMaximumSize(QSize(w, h))
     else:
         button.setText(title)
     QToolTip.add(button, title)
     parent.connect(button, SIGNAL("clicked()"), handler)
     button.show()
     p = ToolbarPlugin(parent)
     p.getWidget = lambda: button
Ejemplo n.º 29
0
 def __open(self, txt, btn):
     filename = str(QFileDialog.getOpenFileName(None , \
         "Images (*.png *.jpg *.gif)", \
         self, \
         "open image file", \
         "Choose a file to open" ))
     txt.setText(filename)
     ok = False
     try:
         pic = QPixmap()
         if pic.loadFromData(open(filename, "rb").read()):
             ok = True
             if not str(self.editWidth.text()):
                 self.editWidth.setText(str(pic.width()))
             if not str(self.editHeight.text()):
                 self.editHeight.setText(str(pic.height()))
             self.previewImage.setPixmap(pic)
             btn.setEnabled(True)
     except:
         ok = False
     if not ok:
         QMessageBox.warning(self, "Warning", "Cannot open the image file!")
         self.previewImage.setPixmap(QPixmap())
         btn.setEnabled(False)
Ejemplo n.º 30
0
def save(cache):
    for name, widget in cache.items():
        pixmap = QPixmap.grabWidget(widget)
        pixmap.save(name + ".png", "PNG")
Ejemplo n.º 31
0
    def __init__(self, repositoryManager):
        """ Constructor. """

        # Init GUI
        AdminWindow.__init__(self)

        # set icon in window-title:
        self.setIcon(QPixmap.fromMimeSource("DF_Logo_24x24.png"))
        iconSet = QIconSet(QPixmap.fromMimeSource("dataType16.png"))
        self.dataNavigator.setTabIconSet(self.dataTypes, iconSet)
        iconSet = QIconSet(QPixmap.fromMimeSource("relationType16.png"))
        self.dataNavigator.setTabIconSet(self.relationTypes, iconSet)
        iconSet = QIconSet(QPixmap.fromMimeSource("dataStore16.png"))
        self.dataNavigator.setTabIconSet(self.dataStores, iconSet)

        logger_handler.installGuiLoggingHandler(self.__logger, self.logList)

        self.myStatusBar = self.statusBar()
        self.statusLabel1 = QLabel("DataFinder", self.myStatusBar)
        self.statusLabel2 = QLabel("OK", self.myStatusBar)

        self.myStatusBar.addWidget(self.statusLabel1, 80)
        self.myStatusBar.addWidget(self.statusLabel2, 20)

        self.statusLabel1.show()
        self.statusLabel2.show()
        self.myStatusBar.show()

        # prepare "About"-dialog:
        self.dfAboutDialog = about_dialog.AboutDialog()
        self.dfAboutDialog.setPixmap(
            QPixmap.fromMimeSource("about_datafinder_admin.png"))

        # Login-dialog:
        self.dfLoginDialog = login_dialog.LoginDialog(
            repositoryManager.preferences, parent=self, showurl=True)

        # IconView:
        propertyPanelLayout = QGridLayout(self.propertyPanel, 1, 1, 2, 6,
                                          "propertyPanelLayout")

        self.iconView = canvas_view.CanvasView(self.propertyPanel, self,
                                               "iconView", 0)
        propertyPanelLayout.addWidget(self.iconView, 0, 0)

        self.iconViewCanvas = self.iconView.canvas()

        self.connect(self.dfLoginDialog.okPushButton,
                     PYSIGNAL("updateWebdavServerView"),
                     self.updateWebdavServerSlot)
        self.connect(self.dataTypeBrowser,
                     SIGNAL("doubleClicked(QListViewItem*)"),
                     self.__addDataTypeIconSlot)
        self.connect(self.relationTypeBrowser,
                     SIGNAL("doubleClicked(QListViewItem*)"),
                     self.__addRelationTypeIconSlot)
        self.connect(self.dataStoreBrowser, SIGNAL("clicked(QListViewItem*)"),
                     self.iconView.updateCanvasView)
        self.connect(self.dataStoreBrowser,
                     SIGNAL("doubleClicked(QListViewItem*)"), self.editSlot)

        # Init model
        self._repositoryManager = repositoryManager
        self.repositoryConfiguration = None
        self._preferences = self._repositoryManager.preferences
        self._lastUploadDirectory = os.path.expanduser("~")

        self._dataTypes = list()
        self._relationTypes = list()
        self._dataStores = list()

        self.__setConnectionState(False)
Ejemplo n.º 32
0
Archivo: Grab.py Proyecto: PyQwt/PyQwt4
def save(cache):
    for name, widget in cache.items():
        pixmap = QPixmap.grabWidget(widget)
        pixmap.save(name+'.png', 'PNG')
Ejemplo n.º 33
0
    def initContextMenu(self, context):
        """
        Initiates the popup menu depending on the context and
        adds appropriate menu items.
        """

        #ACTION TO ARRANGE THE ICONS IN A LINE
        arrangeIcons01Action = QAction("Lines", QKeySequence(), self,
                                       "arrangeIcons01Actions")
        arrangeIcons01Action.setIconSet(QIconSet())
        self.connect(arrangeIcons01Action, SIGNAL("activated()"),
                     self.parent().arrangeIconsInLines)

        #ACTION TO ARRANGE THE ICONS IN A CIRCLE
        arrangeIcons02Action = QAction("Circle", QKeySequence(), self,
                                       "arrangeIcons02Actions")
        arrangeIcons02Action.setIconSet(QIconSet())
        self.connect(arrangeIcons02Action, SIGNAL("activated()"),
                     self.parent().arrangeIconsInCircle)

        #SUBMENU TO CHOOSE THE WAY OF ARRANGEMENT
        #----------------------------------------
        subMenu01 = QPopupMenu(self, "Arrange Icons")
        arrangeIcons01Action.addTo(subMenu01)
        arrangeIcons02Action.addTo(subMenu01)

        #ACTION TO UPDATE THE SCREEN
        updateCanvasViewAction = QAction("Update Screen", QKeySequence(), self,
                                         "updateCanvasViewAction")
        updateCanvasViewAction.setIconSet(QIconSet())
        self.connect(updateCanvasViewAction, SIGNAL("activated()"),
                     self.parent().updateCanvasView)

        #ACTION TO ADD A NEW DATATYPE
        newDataTypeAction = QAction("New Data Type...", QKeySequence(), self,
                                    "newDataTypeAction")
        newDataTypeAction.setIconSet(
            QIconSet(QPixmap.fromMimeSource("newDataType16.png")))
        self.connect(newDataTypeAction, SIGNAL("activated()"),
                     self.myFrame.addDataTypeSlot)

        #ACTION TO ADD A NEW RELATIONTYPE
        newRelationTypeAction = QAction("New Relation Type...", QKeySequence(),
                                        self, "newRelationTypeAction")
        newRelationTypeAction.setIconSet(
            QIconSet(QPixmap.fromMimeSource("newRelationType16.png")))
        self.connect(newRelationTypeAction, SIGNAL("activated()"),
                     self.myFrame.addRelationTypeSlot)

        #ACTION TO EDIT THE MARKED DATATYPE
        editDataTypeAction = QAction("Edit Data Type...", QKeySequence(), self,
                                     "editDataTypeAction")
        editDataTypeAction.setIconSet(
            QIconSet(QPixmap.fromMimeSource("edit16.png")))

        #ACTION TO EDIT THE MARKED RELATIONTYPE
        editRelationTypeAction = QAction("Edit Relation Type...",
                                         QKeySequence(), self,
                                         "editRelationTypeAction")
        editRelationTypeAction.setIconSet(
            QIconSet(QPixmap.fromMimeSource("edit16.png")))

        #ACTION TO REMOVE THE MARKED ICON FROM SCREEN
        removeIconAction = QAction("Remove Icon", QKeySequence(), self,
                                   "removeIconAction")
        removeIconAction.setIconSet(
            QIconSet(QPixmap.fromMimeSource("delete16.png")))
        self.connect(removeIconAction, SIGNAL("activated()"),
                     self.parent().removeIcon)

        #ACTION TO DELETE THE MARKED DATATYPEICON
        deleteDataTypeAction = QAction("Delete Data Type", QKeySequence(),
                                       self, "deleteDataTypeAction")
        deleteDataTypeAction.setIconSet(
            QIconSet(QPixmap.fromMimeSource("delete16.png")))
        self.connect(deleteDataTypeAction, SIGNAL("activated()"),
                     self.myFrame.deleteSelectedDataType)

        #ACTION TO DELETE THE MARKED RELATIONTYPE
        deleteRelationTypeAction = QAction("Delete Relation Type",
                                           QKeySequence(), self,
                                           "deleteRelationTypeAction")
        deleteRelationTypeAction.setIconSet(
            QIconSet(QPixmap.fromMimeSource("delete16.png")))
        self.connect(deleteRelationTypeAction, SIGNAL("activated()"),
                     self.myFrame.deleteSelectedRelationType)

        #CONTEXT-MENU IF NOTHING IS MARKED
        if context == 0:
            newDataTypeAction.addTo(self)
            newRelationTypeAction.addTo(self)

            self.insertSeparator()

            self.insertItem("Arrange Icons...", subMenu01)
            updateCanvasViewAction.addTo(self)

        else:
            #CONTEXT-MENU IF A DATATYPE IS MARKED
            if context.iconType == 1:
                dataTypeController = data_type_dialog.DataTypeController(
                    self.myFrame, context.iconLabel,
                    self.myFrame.repositoryConfiguration)
                self.connect(editDataTypeAction, SIGNAL("activated()"),
                             dataTypeController.show)

                editDataTypeAction.addTo(self)
                deleteDataTypeAction.addTo(self)

                self.insertSeparator()

                newDataTypeAction.addTo(self)
                newRelationTypeAction.addTo(self)

                self.insertSeparator()

                removeIconAction.addTo(self)
                self.insertItem("Arrange Icons...", subMenu01)
                updateCanvasViewAction.addTo(self)

        #CONTEXT-MENU IF A RELATIONTYPE IS MARKED
            if context.iconType == 2:
                relationTypeController = relation_type_dialog.RelationTypeController(
                    self.myFrame, context.iconLabel,
                    self.myFrame.repositoryConfiguration)
                self.connect(editRelationTypeAction, SIGNAL("activated()"),
                             relationTypeController.show)

                editRelationTypeAction.addTo(self)
                deleteRelationTypeAction.addTo(self)

                self.insertSeparator()

                newDataTypeAction.addTo(self)
                newRelationTypeAction.addTo(self)

                self.insertSeparator()

                removeIconAction.addTo(self)
                self.insertItem("Arrange Icons...", subMenu01)
                updateCanvasViewAction.addTo(self)
Ejemplo n.º 34
0
def save(cache):
    for name, widget in cache.items():
        pixmap = QPixmap.grabWidget(widget)
        pixmap.save(name + '.png', 'PNG')
Ejemplo n.º 35
0
 def toggleBlink(self):
     if self.blinkFlag:
         self.sysTray.setPixmap(QPixmap())
     else:
         self.sysTray.setPixmap(self.sysTray.loadIcon("ksmarttray"))
     self.blinkFlag = not self.blinkFlag
Ejemplo n.º 36
0
class Background(object):

    """represents a background"""
    catalogDefined = False

    @staticmethod
    def defineCatalog():
        """whatever this does"""
        if not Background.catalogDefined:
            KGlobal.dirs().addResourceType("kmahjonggbackground",
                                           "data", QString("kmahjongglib/backgrounds"))
            KGlobal.locale().insertCatalog("libkmahjongglib")
            Background.catalogDefined = True

    @staticmethod
    def backgroundsAvailable():
        """returns all available backgrounds"""
        Background.defineCatalog()
        backgroundsAvailableQ = KGlobal.dirs().findAllResources(
            "kmahjonggbackground", "*.desktop", KStandardDirs.Recursive)
        # now we have a list of full paths. Use the base name minus .desktop:
        # put the result into a set, avoiding duplicates
        backgrounds = list(set(str(x).rsplit('/')[-1].split('.')[0]
                               for x in backgroundsAvailableQ))
        if 'default' in backgrounds:
            # we want default to be first in list
            sortedBackgrounds = ['default']
            sortedBackgrounds.extend(set(backgrounds) - set(['default']))
            backgrounds = sortedBackgrounds
        return [Background(x) for x in backgrounds]

    def __init__(self, desktopFileName=None):
        if desktopFileName is None:
            desktopFileName = 'default'
        self.__svg = None
        self.__pmap = None
        QPixmapCache.setCacheLimit(20480)  # the chinese landscape needs much
        self.defineCatalog()
        self.desktopFileName = desktopFileName
        self.path = locatebackground(desktopFileName + '.desktop')
        if self.path.isEmpty():
            self.path = locatebackground('default.desktop')
            if self.path.isEmpty():
                directories = '\n\n' + \
                    '\n'.join(str(x)
                              for x in KGlobal.dirs().resourceDirs("kmahjonggbackground"))
                logException(BackgroundException(m18n(
                    'cannot find any background in the following directories, is libkmahjongg installed?')
                                                 + directories))
            else:
                logWarning(
                    m18n(
                        'cannot find background %1, using default',
                        desktopFileName))
                self.desktopFileName = 'default'
        config = KConfig(self.path)
        group = config.group("KMahjonggBackground")
        self.name = group.readEntry("Name") or m18n("unknown background")

        # Version control
        backgroundversion = int(group.readEntry("VersionFormat")) or 0
        # Format is increased when we have incompatible changes, meaning that
        # older clients are not able to use the remaining information safely
        if backgroundversion > BACKGROUNDVERSIONFORMAT:
            logException(BackgroundException('backgroundversion file / program: %d/%d' %
                                             (backgroundversion, BACKGROUNDVERSIONFORMAT)))

        self.tiled = group.readEntry('Tiled') == '1'
        if self.tiled:
            self.imageWidth, entryOk = group.readEntry('Width').toInt()
            if not entryOk:
                raise Exception('cannot scan Width from background file')
            self.imageHeight, entryOk = group.readEntry('Height').toInt()
            if not entryOk:
                raise Exception('cannot scan Height from background file')
        self.isPlain = bool(group.readEntry('Plain'))
        if not self.isPlain:
            graphName = QString(group.readEntry("FileName"))
            self.__graphicspath = locatebackground(graphName)
            if self.__graphicspath.isEmpty():
                logException(BackgroundException(
                    'cannot find kmahjongglib/backgrounds/%s for %s' %
                    (graphName, self.desktopFileName)))

    def pixmap(self, size):
        """returns a background pixmap or None for isPlain"""
        self.__pmap = None
        if not self.isPlain:
            width = size.width()
            height = size.height()
            if self.tiled:
                width = self.imageWidth
                height = self.imageHeight
            cachekey = QString(u'{name}W{width}H{height}'.format(
                name=self.name, width=width, height=height))
            self.__pmap = QPixmapCache.find(cachekey)
            if not self.__pmap:
                renderer = QSvgRenderer(self.__graphicspath)
                if not renderer.isValid():
                    logException(BackgroundException(
                        m18n('file <filename>%1</filename> contains no valid SVG', self.__graphicspath)))
                self.__pmap = QPixmap(width, height)
                self.__pmap.fill(Qt.transparent)
                painter = QPainter(self.__pmap)
                renderer.render(painter)
                QPixmapCache.insert(cachekey, self.__pmap)
        return self.__pmap

    def brush(self, size):
        """background brush"""
        return QBrush(self.pixmap(size))

    def setPalette(self, onto):
        """sets a background palette for widget onto"""
        palette = QPalette()
        mybrush = self.brush(onto.size())
        palette.setBrush(QPalette.Window, mybrush)
        onto.setPalette(palette)
Ejemplo n.º 37
0
    def __init__(self, repositoryManager):
        """ Constructor. """

        # Init GUI
        AdminWindow.__init__(self)
        
        # set icon in window-title:
        self.setIcon(QPixmap.fromMimeSource("DF_Logo_24x24.png"))
        iconSet = QIconSet(QPixmap.fromMimeSource("dataType16.png"))
        self.dataNavigator.setTabIconSet(self.dataTypes, iconSet)
        iconSet = QIconSet(QPixmap.fromMimeSource("relationType16.png"))
        self.dataNavigator.setTabIconSet(self.relationTypes, iconSet)
        iconSet = QIconSet(QPixmap.fromMimeSource("dataStore16.png"))
        self.dataNavigator.setTabIconSet(self.dataStores, iconSet)

        logger_handler.installGuiLoggingHandler(self.__logger, self.logList)

        self.myStatusBar = self.statusBar()
        self.statusLabel1 = QLabel("DataFinder", self.myStatusBar)
        self.statusLabel2 = QLabel("OK", self.myStatusBar)

        self.myStatusBar.addWidget(self.statusLabel1, 80)
        self.myStatusBar.addWidget(self.statusLabel2, 20)

        self.statusLabel1.show()
        self.statusLabel2.show()
        self.myStatusBar.show()

        # prepare "About"-dialog:
        self.dfAboutDialog = about_dialog.AboutDialog()
        self.dfAboutDialog.setPixmap(QPixmap.fromMimeSource("about_datafinder_admin.png"))

        # Login-dialog:
        self.dfLoginDialog = login_dialog.LoginDialog(repositoryManager.preferences, parent=self, showurl=True)

        # IconView:
        propertyPanelLayout = QGridLayout(self.propertyPanel, 1, 1, 2, 6, "propertyPanelLayout")

        self.iconView = canvas_view.CanvasView(self.propertyPanel, self, "iconView", 0)
        propertyPanelLayout.addWidget(self.iconView, 0, 0)

        self.iconViewCanvas = self.iconView.canvas()

        self.connect(self.dfLoginDialog.okPushButton,
                     PYSIGNAL("updateWebdavServerView"),
                     self.updateWebdavServerSlot)
        self.connect(self.dataTypeBrowser, SIGNAL("doubleClicked(QListViewItem*)"), self.__addDataTypeIconSlot)
        self.connect(self.relationTypeBrowser, SIGNAL("doubleClicked(QListViewItem*)"), self.__addRelationTypeIconSlot)
        self.connect(self.dataStoreBrowser, SIGNAL("clicked(QListViewItem*)"), self.iconView.updateCanvasView)
        self.connect(self.dataStoreBrowser, SIGNAL("doubleClicked(QListViewItem*)"), self.editSlot)
        
        # Init model
        self._repositoryManager = repositoryManager
        self.repositoryConfiguration = None
        self._preferences = self._repositoryManager.preferences
        self._lastUploadDirectory = os.path.expanduser("~")

        self._dataTypes = list()
        self._relationTypes = list()
        self._dataStores = list()

        self.__setConnectionState(False)
Ejemplo n.º 38
0
    def initContextMenu(self, context):
        """
        Initiates the popup menu depending on the context and
        adds appropriate menu items.
        """

        #ACTION TO ARRANGE THE ICONS IN A LINE
        arrangeIcons01Action = QAction("Lines", QKeySequence(), self, "arrangeIcons01Actions")
        arrangeIcons01Action.setIconSet(QIconSet())
        self.connect(arrangeIcons01Action, SIGNAL("activated()"), self.parent().arrangeIconsInLines)

        #ACTION TO ARRANGE THE ICONS IN A CIRCLE
        arrangeIcons02Action = QAction("Circle", QKeySequence(), self, "arrangeIcons02Actions")
        arrangeIcons02Action.setIconSet(QIconSet())
        self.connect(arrangeIcons02Action, SIGNAL("activated()"), self.parent().arrangeIconsInCircle)

        #SUBMENU TO CHOOSE THE WAY OF ARRANGEMENT
        #----------------------------------------
        subMenu01 = QPopupMenu(self, "Arrange Icons")
        arrangeIcons01Action.addTo(subMenu01)
        arrangeIcons02Action.addTo(subMenu01)

        #ACTION TO UPDATE THE SCREEN
        updateCanvasViewAction = QAction("Update Screen", QKeySequence(), self, "updateCanvasViewAction")
        updateCanvasViewAction.setIconSet(QIconSet())
        self.connect(updateCanvasViewAction, SIGNAL("activated()"), self.parent().updateCanvasView)

        #ACTION TO ADD A NEW DATATYPE
        newDataTypeAction = QAction("New Data Type...", QKeySequence(), self, "newDataTypeAction")
        newDataTypeAction.setIconSet(QIconSet(QPixmap.fromMimeSource("newDataType16.png")))
        self.connect(newDataTypeAction, SIGNAL("activated()"), self.myFrame.addDataTypeSlot)

        #ACTION TO ADD A NEW RELATIONTYPE
        newRelationTypeAction = QAction("New Relation Type...", QKeySequence(), self, "newRelationTypeAction")
        newRelationTypeAction.setIconSet(QIconSet(QPixmap.fromMimeSource("newRelationType16.png")))
        self.connect(newRelationTypeAction, SIGNAL("activated()"), self.myFrame.addRelationTypeSlot)

        #ACTION TO EDIT THE MARKED DATATYPE
        editDataTypeAction = QAction("Edit Data Type...", QKeySequence(), self, "editDataTypeAction")
        editDataTypeAction.setIconSet(QIconSet(QPixmap.fromMimeSource("edit16.png")))

        #ACTION TO EDIT THE MARKED RELATIONTYPE
        editRelationTypeAction = QAction("Edit Relation Type...", QKeySequence(), self, "editRelationTypeAction")
        editRelationTypeAction.setIconSet(QIconSet(QPixmap.fromMimeSource("edit16.png")))

        #ACTION TO REMOVE THE MARKED ICON FROM SCREEN
        removeIconAction = QAction("Remove Icon", QKeySequence(), self, "removeIconAction")
        removeIconAction.setIconSet(QIconSet(QPixmap.fromMimeSource("delete16.png")))
        self.connect(removeIconAction, SIGNAL("activated()"), self.parent().removeIcon)

        #ACTION TO DELETE THE MARKED DATATYPEICON
        deleteDataTypeAction = QAction("Delete Data Type", QKeySequence(), self, "deleteDataTypeAction")
        deleteDataTypeAction.setIconSet(QIconSet(QPixmap.fromMimeSource("delete16.png")))
        self.connect(deleteDataTypeAction, SIGNAL("activated()"), self.myFrame.deleteSelectedDataType)

        #ACTION TO DELETE THE MARKED RELATIONTYPE
        deleteRelationTypeAction = QAction("Delete Relation Type", QKeySequence(), self, "deleteRelationTypeAction")
        deleteRelationTypeAction.setIconSet(QIconSet(QPixmap.fromMimeSource("delete16.png")))
        self.connect(deleteRelationTypeAction, SIGNAL("activated()"), self.myFrame.deleteSelectedRelationType)

        #CONTEXT-MENU IF NOTHING IS MARKED
        if context == 0:
            newDataTypeAction.addTo(self)
            newRelationTypeAction.addTo(self)

            self.insertSeparator()

            self.insertItem("Arrange Icons...", subMenu01)
            updateCanvasViewAction.addTo(self)

        else:
        #CONTEXT-MENU IF A DATATYPE IS MARKED
            if context.iconType == 1:
                dataTypeController = data_type_dialog.DataTypeController(self.myFrame, context.iconLabel, 
                                                                         self.myFrame.repositoryConfiguration)
                self.connect(editDataTypeAction, SIGNAL("activated()"), dataTypeController.show)

                editDataTypeAction.addTo(self)
                deleteDataTypeAction.addTo(self)

                self.insertSeparator()

                newDataTypeAction.addTo(self)
                newRelationTypeAction.addTo(self)

                self.insertSeparator()

                removeIconAction.addTo(self)
                self.insertItem("Arrange Icons...", subMenu01)
                updateCanvasViewAction.addTo(self)

        #CONTEXT-MENU IF A RELATIONTYPE IS MARKED
            if context.iconType == 2:
                relationTypeController = relation_type_dialog.RelationTypeController(self.myFrame, context.iconLabel, 
                                                                                     self.myFrame.repositoryConfiguration)
                self.connect(editRelationTypeAction, SIGNAL("activated()"), relationTypeController.show)

                editRelationTypeAction.addTo(self)
                deleteRelationTypeAction.addTo(self)

                self.insertSeparator()

                newDataTypeAction.addTo(self)
                newRelationTypeAction.addTo(self)

                self.insertSeparator()

                removeIconAction.addTo(self)
                self.insertItem("Arrange Icons...", subMenu01)
                updateCanvasViewAction.addTo(self)
Ejemplo n.º 39
0
class Background(Resource):
    """represents a background"""

    resourceName = 'background'
    configGroupName = 'KMahjonggBackground'
    cache = {}

    def __init__(self, name):
        """continue __build"""
        super(Background, self).__init__(name)
        self.__svg = None
        self.__pmap = None
        self.graphicsPath = None
        QPixmapCache.setCacheLimit(20480)  # the chinese landscape needs much

        self.tiled = self.group.readEntry('Tiled') == '1'
        if self.tiled:
            try:
                self.imageWidth = self.group.readInteger('Width')
                self.imageHeight = self.group.readInteger('Height')
            except Exception as exc:
                logException(
                    exc)  # TODO: simplify if we switch to twisted logger
                raise
        self.isPlain = bool(self.group.readEntry('Plain'))
        if not self.isPlain:
            graphName = self.group.readEntry("FileName")
            self.graphicsPath = self.locate(graphName)
            if not self.graphicsPath:
                logException('cannot find kmahjongglib/backgrounds/%s for %s' %
                             (graphName, self.desktopFileName))

    def pixmap(self, size):
        """returns a background pixmap or None for isPlain"""
        self.__pmap = QBrush()
        if not self.isPlain:
            width = size.width()
            height = size.height()
            if self.tiled:
                width = self.imageWidth
                height = self.imageHeight
            cachekey = '{name}W{width}H{height}'.format(name=self.name,
                                                        width=width,
                                                        height=height)
            self.__pmap = QPixmapCache.find(cachekey)
            if not self.__pmap:
                renderer = QSvgRenderer(self.graphicsPath)
                if not renderer.isValid():
                    logException(
                        i18n(
                            'file <filename>%1</filename> contains no valid SVG',
                            self.graphicsPath))
                self.__pmap = QPixmap(width, height)
                self.__pmap.fill(Qt.transparent)
                painter = QPainter(self.__pmap)
                renderer.render(painter)
                QPixmapCache.insert(cachekey, self.__pmap)
        return self.__pmap

    def brush(self, size):
        """background brush"""
        return QBrush(self.pixmap(size))

    def setPalette(self, onto):
        """sets a background palette for widget onto"""
        palette = QPalette()
        mybrush = self.brush(onto.size())
        palette.setBrush(QPalette.Window, mybrush)
        onto.setPalette(palette)