def data(self, index, role=Qt.DisplayRole): """get from model""" if not index.isValid() or not 0 <= index.row() < len(self.diffs): return toQVariant() diff = self.diffs[index.row()] column = index.column() if role == Qt.DisplayRole: return toQVariant(diff[column]) elif role == Qt.TextAlignmentRole: return toQVariant(int(Qt.AlignLeft | Qt.AlignVCenter)) return toQVariant()
def data(self, index, role=None): # pylint: disable=no-self-use,too-many-branches """score table""" # pylint: disable=too-many-return-statements if not index.isValid(): return toQVariant() column = index.column() item = index.internalPointer() if role is None: role = Qt.DisplayRole if role == Qt.DisplayRole: if isinstance(item, ScorePlayerItem): content = item.content(column) if isinstance(content, HandResult): parentRow = item.parent.row() if parentRow == 0: if not content.penalty: content = "%d %s" % (content.points, content.wind) elif parentRow == 1: content = str(content.payments) else: content = str(content.balance) return toQVariant(content) else: if column > 0: return toQVariant("") else: return toQVariant(item.content(0)) if role == Qt.TextAlignmentRole: if index.column() == 0: return toQVariant(int(Qt.AlignLeft | Qt.AlignVCenter)) else: return toQVariant(int(Qt.AlignRight | Qt.AlignVCenter)) if role == Qt.FontRole: return QFont("Monospaced") if role == Qt.ForegroundRole: if isinstance(item, ScorePlayerItem) and item.parent.row() == 3: content = item.content(column) if not isinstance(content, HandResult): return toQVariant(QBrush(ScoreItemDelegate.colors[index.row()])) if column > 0 and isinstance(item, ScorePlayerItem): content = item.content(column) # pylint: disable=maybe-no-member # pylint thinks content is a str if role == Qt.BackgroundRole: if content and content.won: return toQVariant(QColor(165, 255, 165)) if role == Qt.ToolTipRole: englishHints = content.manualrules.split("||") tooltip = "<br />".join(m18n(x) for x in englishHints) return toQVariant(tooltip) return toQVariant()
def headerData(self, section, orientation, role=Qt.DisplayRole): # pylint: disable=no-self-use """show header""" if role == Qt.TextAlignmentRole: if orientation == Qt.Horizontal: if section == 1: return toQVariant(int(Qt.AlignRight)) else: return toQVariant(int(Qt.AlignLeft)) if orientation != Qt.Horizontal: return toQVariant(int(section + 1)) if role != Qt.DisplayRole: return toQVariant() result = '' if section < self.columnCount(): result = [m18n('Time'), m18n('Player'), m18n('Message')][section] return toQVariant(result)
def fillLastMeldCombo(self): """fill the drop down list with all possible melds. If the drop down had content before try to preserve the current index. Even if the meld changed state meanwhile.""" with BlockSignals(self.cbLastMeld): # we only want to emit the changed signal once showCombo = False idx = self.cbLastMeld.currentIndex() if idx < 0: idx = 0 indexedMeld = str(variantValue(self.cbLastMeld.itemData(idx))) self.cbLastMeld.clear() self.__meldPixMaps = [] if not self.game.winner: return if self.cbLastTile.count() == 0: return lastTile = Internal.scene.computeLastTile() winnerMelds = [m for m in self.game.winner.hand.melds if len(m) < 4 and lastTile in m] assert len(winnerMelds), "lastTile %s missing in %s" % (lastTile, self.game.winner.hand.melds) if len(winnerMelds) == 1: self.cbLastMeld.addItem(QIcon(), "", toQVariant(str(winnerMelds[0]))) self.cbLastMeld.setCurrentIndex(0) return showCombo = True self.__fillLastMeldComboWith(winnerMelds, indexedMeld, lastTile) self.lblLastMeld.setVisible(showCombo) self.cbLastMeld.setVisible(showCombo) self.cbLastMeld.currentIndexChanged.emit(0)
def headerData(self, section, orientation, role): """tell the view about the wanted headers""" if Qt is None: # happens when kajongg exits unexpectedly return if role == Qt.DisplayRole and orientation == Qt.Horizontal: if section >= self.rootItem.columnCount(): return toQVariant() result = variantValue(self.rootItem.content(section)) if result == 'doubles': result = 'x2' return m18n(result) elif role == Qt.TextAlignmentRole: leftRight = Qt.AlignLeft if section == 0 else Qt.AlignRight return toQVariant(int(leftRight | Qt.AlignVCenter)) else: return toQVariant()
def data(self, index, role=Qt.DisplayRole): """score table""" result = toQVariant() if role == Qt.TextAlignmentRole: if index.column() == 1: return toQVariant(int(Qt.AlignRight)) else: return toQVariant(int(Qt.AlignLeft)) if index.isValid() and (0 <= index.row() < len(self.chatLines)): chatLine = self.chatLines[index.row()] if role == Qt.DisplayRole and index.column() == 0: local = chatLine.localtimestamp() result = toQVariant('%02d:%02d:%02d' % ( local.hour, local.minute, local.second)) elif role == Qt.DisplayRole and index.column() == 1: result = toQVariant(chatLine.fromUser) elif role == Qt.DisplayRole and index.column() == 2: result = toQVariant(m18n(chatLine.message)) elif role == Qt.ForegroundRole and index.column() == 2: palette = KApplication.palette() # pylint: disable=no-member color = 'blue' if chatLine.isStatusMessage else palette.windowText( ) result = toQVariant(QColor(color)) return result
def headerData(self, section, orientation, role): """tell the view about the wanted headers""" if role == Qt.DisplayRole and orientation == Qt.Horizontal: if section == 0: return m18n("Round/Hand") child1 = self.rootItem.children[0] if child1 and child1.children: child1 = child1.children[0] hands = child1.hands() handResult = hands[section - 1] if not handResult.penalty: return handResult.handId() elif role == Qt.TextAlignmentRole: if section == 0: return toQVariant(int(Qt.AlignLeft | Qt.AlignVCenter)) else: return toQVariant(int(Qt.AlignRight | Qt.AlignVCenter)) return toQVariant()
def scene(self, value): """if changing, updateGUI""" if not isAlive(self): return if self._scene == value: return if not value: self.actionChat.setChecked(False) self.actionExplain.setChecked(False) self.actionScoreTable.setChecked(False) self.actionExplain.setData(toQVariant(ExplainView)) self.actionScoreTable.setData(toQVariant(ScoreTable)) self._scene = value self.centralView.setScene(value) self.adjustView() self.updateGUI() self.actionChat.setEnabled(isinstance(value, PlayingScene)) self.actionExplain.setEnabled(value is not None) self.actionScoreTable.setEnabled(value is not None)
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 data(self, index, role=None): """get score table from view""" if role is None: role = Qt.DisplayRole if not (index.isValid() and role == Qt.DisplayRole): return toQVariant() if role == Qt.DisplayRole: unformatted = unicode( self._resultRows[index.row()][index.column()]) if index.column() == 2: # we do not yet use this for listing remote games but if we do # this translation is needed for robot players names = [m18n(name) for name in unformatted.split('///')] return toQVariant(', '.join(names)) elif index.column() == 1: dateVal = datetime.datetime.strptime( unformatted, '%Y-%m-%dT%H:%M:%S') return toQVariant(nativeString(dateVal.strftime('%c'))) elif index.column() == 0: return toQVariant(int(unformatted)) with RealQVariant(): return QAbstractTableModel.data(self, index, role)
def data(self, index, role): # pylint: disable=no-self-use """get data fom model""" # pylint: disable=too-many-branches,redefined-variable-type # too many branches result = None if index.isValid(): item = index.internalPointer() if role in (Qt.DisplayRole, Qt.EditRole): if index.column() == 1: if isinstance(item, RuleItem) and isinstance(item.rawContent, BoolRule): return toQVariant('') showValue = item.content(index.column()) if isinstance(showValue, unicode) and showValue.endswith('.0'): try: showValue = str(int(float(showValue))) except ValueError: pass if showValue == '0': showValue = '' result = showValue elif role == Qt.CheckStateRole: if self.isCheckboxCell(index): bData = item.content(index.column()) result = Qt.Checked if bData else Qt.Unchecked elif role == Qt.TextAlignmentRole: result = int(Qt.AlignLeft | Qt.AlignVCenter) if index.column() > 0: result = int(Qt.AlignRight | Qt.AlignVCenter) elif role == Qt.FontRole and index.column() == 0: ruleset = item.ruleset() if isinstance(ruleset, PredefinedRuleset): font = QFont() font.setItalic(True) result = font elif role == Qt.ToolTipRole: tip = u'<b></b>%s<b></b>' % m18n( item.tooltip()) if item else u'' result = tip return toQVariant(result)
def headerData( # pylint: disable=no-self-use self, section, orientation, role=Qt.DisplayRole): """show header""" if role == Qt.TextAlignmentRole: if orientation == Qt.Horizontal: if section in [3, 4]: return toQVariant(int(Qt.AlignLeft)) else: return toQVariant(int(Qt.AlignHCenter | Qt.AlignVCenter)) if role != Qt.DisplayRole: return toQVariant() if orientation != Qt.Horizontal: return toQVariant(int(section + 1)) result = '' if section < 5: result = [m18n('Table'), '', m18n('Players'), m18nc('table status', 'Status'), m18n('Ruleset')][section] return toQVariant(result)
def kajonggAction( self, name, icon, slot=None, shortcut=None, actionData=None): """simplify defining actions""" res = KAction(self) if icon: res.setIcon(KIcon(icon)) if slot: res.triggered.connect(slot) self.actionCollection().addAction(name, res) if shortcut: res.setShortcut(Qt.CTRL + shortcut) res.setShortcutContext(Qt.ApplicationShortcut) if PYQT_VERSION_STR != '4.5.2' or actionData is not None: res.setData(toQVariant(actionData)) return res
def _toggleWidget(self, checked): """user has toggled widget visibility with an action""" assert self.scene action = self.sender() actionData = variantValue(action.data()) if checked: if isinstance(actionData, type): clsName = actionData.__name__ actionData = actionData(scene=self.scene) action.setData(toQVariant(actionData)) setattr( self.scene, clsName[0].lower() + clsName[1:], actionData) actionData.show() actionData.raise_() else: assert actionData actionData.hide()
def headerData(self, section, orientation, role): """tell the view about the wanted headers""" if role == Qt.TextAlignmentRole: if orientation == Qt.Horizontal: return toQVariant(int(Qt.AlignLeft | Qt.AlignVCenter)) if role != Qt.DisplayRole: return toQVariant() if orientation == Qt.Horizontal: if section == 0: return toQVariant(m18nc("Kajongg", "Rule")) if section == 1: return toQVariant(m18n(self.view.cbRuleset1.current.name)) if section == 2: return toQVariant(m18n(self.view.cbRuleset2.current.name)) return toQVariant()
def chooseVariant(self, uiTile, lowerHalf=False): """make the user choose from a list of possible melds for the target. The melds do not contain real Tiles, just the scoring strings.""" variants = self.meldVariants(uiTile, lowerHalf) idx = 0 if len(variants) > 1: menu = QMenu(m18n('Choose from')) for idx, variant in enumerate(variants): action = menu.addAction(variant.typeName()) action.setData(toQVariant(idx)) if Internal.scene.mainWindow.centralView.dragObject: menuPoint = QCursor.pos() else: menuPoint = uiTile.board.tileFaceRect().bottomRight() view = Internal.scene.mainWindow.centralView menuPoint = view.mapToGlobal( view.mapFromScene(uiTile.mapToScene(menuPoint))) action = menu.exec_(menuPoint) if not action: return None idx = variantValue(action.data()) return variants[idx]
def data(self, index, role=Qt.DisplayRole): """score table""" # pylint: disable=too-many-branches,too-many-locals,redefined-variable-type result = toQVariant() if role == Qt.TextAlignmentRole: if index.column() == 0: result = toQVariant(int(Qt.AlignHCenter | Qt.AlignVCenter)) else: result = toQVariant(int(Qt.AlignLeft | Qt.AlignVCenter)) if index.isValid() and (0 <= index.row() < len(self.tables)): table = self.tables[index.row()] if role == Qt.DisplayRole and index.column() in (0, 1): result = toQVariant(table.tableid) elif role == Qt.DisplayRole and index.column() == 2: players = [] zipped = list(zip(table.playerNames, table.playersOnline)) for idx, pair in enumerate(zipped): name, online = pair[0], pair[1] if idx < len(zipped) - 1: name += ', ' palette = KApplication.palette() if online: color = palette.color( QPalette.Active, QPalette.WindowText).name() style = ('font-weight:normal;' 'font-style:normal;color:%s' % color) else: color = palette.color( QPalette.Disabled, QPalette.WindowText).name() style = ('font-weight:100;font-style:italic;color:%s' % color) players.append( '<nobr style="%s">' % style + name + '</nobr>') names = ''.join(players) result = toQVariant(names) elif role == Qt.DisplayRole and index.column() == 3: status = table.status() if table.suspendedAt: dateVal = u' ' + unicodeString(datetime.datetime.strptime( table.suspendedAt, '%Y-%m-%dT%H:%M:%S').strftime('%c')) status = u'Suspended' else: dateVal = u'' result = toQVariant(m18nc('table status', status) + dateVal) elif index.column() == 4: if role == Qt.DisplayRole: result = toQVariant( m18n(( table.myRuleset if table.myRuleset else table.ruleset).name)) elif role == Qt.ForegroundRole: palette = KApplication.palette() color = palette.windowText() if table.myRuleset else 'red' result = toQVariant(QColor(color)) return result
def headerData(self, section, orientation, role): """for the two visible columns""" # pylint: disable=no-self-use if orientation == Qt.Horizontal and role == Qt.DisplayRole: return toQVariant((m18n("Started"), m18n("Players"))[section - 1]) return toQVariant()
def __fillLastTileComboWith(self, lastTiles, winnerTiles): """fill last meld combo with prepared content""" self.comboTilePairs = lastTiles idx = self.cbLastTile.currentIndex() if idx < 0: idx = 0 indexedTile = variantValue(self.cbLastTile.itemData(idx)) restoredIdx = None self.cbLastTile.clear() if not winnerTiles: return pmSize = winnerTiles[0].board.tileset.faceSize pmSize = QSize(pmSize.width() * 0.5, pmSize.height() * 0.5) self.cbLastTile.setIconSize(pmSize) QPixmapCache.clear() self.__tilePixMaps = [] shownTiles = set() for tile in winnerTiles: if tile.tile in lastTiles and tile.tile not in shownTiles: shownTiles.add(tile.tile) self.cbLastTile.addItem(QIcon(tile.pixmapFromSvg(pmSize, withBorders=False)), "", toQVariant(tile.tile)) if indexedTile is tile.tile: restoredIdx = self.cbLastTile.count() - 1 if not restoredIdx and indexedTile: # try again, maybe the tile changed between concealed and exposed indexedTile = indexedTile.exposed for idx in range(self.cbLastTile.count()): if indexedTile is variantValue(self.cbLastTile.itemData(idx)).exposed: restoredIdx = idx break if not restoredIdx: restoredIdx = 0 self.cbLastTile.setCurrentIndex(restoredIdx) self.prevLastTile = self.computeLastTile()