def onMonoFontChange(self, propagate=True): font = QFont(self.monoFontComboBox.currentFont()) font.setPointSize(self.monoFontSizeSpinBox.value()) if propagate and bool(self.state.model): self.state.model.setConfig(Gconf.Key.MonoFont, font.family()) self.state.model.setConfig(Gconf.Key.MonoFontSize, font.pointSize())
def setTitleFont(self): ''' Sets font for the widget text ''' fontValue = QFont('Times New Roman') fontValue.setPointSize(fontValue.pointSize() + 15) self.setFont(fontValue)
def initUI(self): self.setWindowTitle('TickTackToe 2000') self.resize(350, 350) self.center() self.main_layout = QVBoxLayout() self.form_layout = QGridLayout() self.main_layout.addLayout(self.form_layout) splitter = QSplitter(QtCore.Qt.Horizontal) self.main_layout.addWidget(splitter) self.game_layout = QGridLayout() self.main_layout.addLayout(self.game_layout) self.server_label = QLabel("Server: ") self.server_input = QLineEdit("127.0.0.1") self.form_layout.addWidget(self.server_label, 0, 0) self.form_layout.addWidget(self.server_input, 0, 1) self.port_label = QLabel("Port: ") self.port_input = QLineEdit("1632") self.form_layout.addWidget(self.port_label, 1, 0) self.form_layout.addWidget(self.port_input, 1, 1) self.connect_button = QPushButton("Connect") self.connect_button.setMinimumHeight(60) self.connect_button.pressed.connect(self.reconnect) self.form_layout.addWidget(self.connect_button, 0, 2, 2, 1) self.game_fields = {} tile_font = QFont() tile_font.setPointSize(30) for x in range(0, GAME_SIZE): for y in range(0, GAME_SIZE): f = QPushButton(" ") f.setMinimumHeight(90) f.setDisabled(True) f.setFont(tile_font) f.clicked.connect(self.onGameButtonClicked) if x in self.game_fields: self.game_fields[x][y] = f else: self.game_fields[x] = { 0: f } self.game_layout.addWidget(f, y, x) central_widget = QtGui.QWidget() central_widget.setLayout(self.main_layout) self.setCentralWidget(central_widget) self.statusBar().showMessage("") self.show()
def onDisplayMonoFontChange(self, propagate=True): font = QFont(self.displaymonoFontComboBox.currentFont()) font.setPointSize(self.displaymonoFontSizeSpinBox.value()) if propagate: settings = QSettings() settings.setValue(Gopt.Key.MonoFont, font.family()) settings.setValue(Gopt.Key.MonoFontSize, font.pointSize()) self.state.updateDisplayFonts()
def drawPaused(self, painter): """ Draw the Paused Message """ font = QFont() font.setPointSize(48) penColor = QColor(238, 250, 12) painter.setFont(font) painter.setPen(penColor) painter.drawText(self.contentsRect(), Qt.AlignCenter, "Paused")
def drawScore(self, painter): """ Draw the Score label """ font = QFont() font.setPointSize(24) penColor = QColor(238, 250, 12) painter.setFont(font) painter.setPen(penColor) painter.drawText(10, 50, "Score: {0:,}".format(self.level.score))
def setReset(self, m): self.pushButton_2 = QPushButton("Reset it") font = QFont() font.setPointSize(17) font.setWeight(75) font.setBold(True) self.pushButton_2.setFont(font) self.pushButton_2.clicked.connect(self.setbut_reset) m.addWidget(self.pushButton_2)
def drawGameOver(self, painter): """ Draw the Game Over Message """ font = QFont() font.setPointSize(48) penColor = QColor(255, 0, 0) painter.setFont(font) painter.setPen(penColor) painter.drawText(self.contentsRect(), Qt.AlignCenter, "Game Over")
class AdjacencyClueView(QFrame): # Prolly could use a better name """ Represents the Adjacency Clue View """ TRANSPARENCY = 100 def __init__(self, adjacencyClue, fragilityClue, parent=None): """ Initialize the Adjacency Clue View """ QFrame.__init__(self, parent) self.adjacencyClue = adjacencyClue self.fragilityClue = fragilityClue self.resize(34, 32) self.setupClueLabel() def setupFont(self): """ Setup the Font """ self.font = QFont() self.font.setPointSize(15) def setupClueLabel(self): """ Setup the Clue Label """ self.setupFont() self.clueLabel = QLabel('', self) self.clueLabel.setFont(self.font) self.clueLabel.move(0, 0) def updateView(self): """ Update the View """ self.clueLabel.setText(self.getLabelText()) self.setColorBasedOnFragility() self.clueLabel.resize(34, self.clueLabel.contentsRect().height()) def getLabelText(self): """ Get the CLue Reading Text """ adjacentMines = self.adjacencyClue.getAdjacentMinesClue() if adjacentMines == 0: return '' else: return str(adjacentMines) def setColorBasedOnFragility(self): """ Set color of the clue based on adjacency to Fragile Mines """ color = "rgba({0}, {1}%)".format(self.getColor(), self.TRANSPARENCY) self.clueLabel.setStyleSheet("QLabel { color : %s }" % color) def getColor(self): """ Return color """ if self.fragilityClue.distance is None: return "0, 0, 0" elif self.fragilityClue.distance <= 1: if self.fragilityClue.count == 1: return "227, 68, 20" else: return "196, 0, 0" elif self.fragilityClue.distance > 1 and self.fragilityClue.distance < 4: return "244, 244, 0" elif self.fragilityClue.distance >= 4: return "0, 154, 0"
def __init__(self, txt=None): super(ConfigTableHeaderItem, self).__init__(txt) # first we customize the appearance self.setTextAlignment(Qt.AlignCenter) this_font = QFont() this_font.setBold(True) this_font.setPointSize(7) self.setBackground(QBrush(Qt.white)) self.setFont(this_font) self.setForeground(Qt.black) self.setFlags(Qt.ItemIsEnabled) return
def __init__(self, parent=None): super(AutoInfo, self).__init__(parent) self.setupUi(self) # Remove the question mark widget from dialog # self.setWindowFlags(self.windowFlags() ^ # Qt.WindowContextHelpButtonHint) self.setWindowFlags(Qt.Tool | Qt.FramelessWindowHint) self.hide() font = QFont() font.setBold(True) font.setPointSize(QFont.pointSize(QFont()) + 3) self.label.setFont(font)
def __init__(self, cpu): QDialog.__init__(self) self._cpu = cpu load_ui(self, 'dialog_memory.ui') win_remove_context_help(self) self.update() self.adjustSize() font = QFont('Monospace') font.setStyleHint(QFont.TypeWriter) font.setPointSize(12) self._textMem.setFont(font)
def __init__(self, txt, value, tooltip=None): super(ConfigTableItem, self).__init__(txt) self.__value = value # first we customize the appearance self.setTextAlignment(Qt.AlignCenter) this_font = QFont() this_font.setBold(False) this_font.setPointSize(7) self.setBackground(QBrush(Qt.white)) self.setFont(this_font) self.setForeground(Qt.black) if tooltip is not None: self.setToolTip(tooltip) # self.setFlags(Qt.ItemIsEnabled | Qt.ItemIsDragEnabled | Qt.ItemIsUserCheckable | Qt.ItemIsSelectable) self.setFlags(Qt.ItemIsSelectable) return
class LevelOverviewView(QFrame): """ Represents the View of the Level Overview """ WIDTH = 120 HEIGHT = 64 def __init__(self, parent, level, levelSelection): """ Initialize the Level Overview View """ QFrame.__init__(self, parent) self.resize(self.WIDTH, self.HEIGHT) self.level = level self.levelSelection = levelSelection self.bigFont = QFont() self.bigFont.setPointSize(32) self.smallFont = QFont() self.smallFont.setPointSize(24) self.label = self.getLabel(self.smallFont) def getLabel(self, font): """ Get a Level Label witht he apropriate Font """ label = QLabel(self.level.name, self) label.setFont(self.smallFont) label.setAlignment(Qt.AlignCenter) label.resize(self.WIDTH, self.HEIGHT) return label def updateView(self): """ Update the View """ if self.levelSelection.getLevel() is self.level: self.label.setFont(self.bigFont) else: self.label.setFont(self.smallFont) self.update() def getWidth(self): """ Return the Width of the Level Overview View """ return self.label.contentsRect().width()
def setMW(self, ml): ll = QVBoxLayout() self.mIcon = QLabel() self.mIcon.setAlignment(Qt.AlignCenter) mmicon = self.logo.pixmap(250, 230, QIcon.Active, QIcon.On) self.mIcon.setPixmap(mmicon) self.mInst = QLabel( # u"<center>(Drag and drop files or folders to encrypt them)<br>" + u"<center>(마우스로 끌어다 놓으십시오)<br>" + u"<u>최대 2GB 파일 또는 디렉토리만 가능</u></center>") font = QFont() font.setPointSize(13) font.setBold(True) font.setWeight(75) self.fInst = QLabel('<center></center>') self.mInst.setFont(font) ll.addWidget(self.mIcon) ll.addWidget(self.mInst) ll.addWidget(self.fInst) ml.addLayout(ll)
def setMW(self, ml): ll = QVBoxLayout() self.mIcon = QLabel() self.mIcon.setAlignment(Qt.AlignCenter) mmicon = self.logo.pixmap(250, 230, QIcon.Active, QIcon.On) self.mIcon.setPixmap(mmicon) self.mInst = QLabel( "<center>(Drag and drop files or folders to encrypt them)<br>" + "(Drap and drop .sld file to decrypt it)<br>" + "<u>2GB max single file size to encrypt</u></center>") font = QFont() font.setPointSize(13) font.setBold(True) font.setWeight(75) self.fInst = QLabel('<center>| Double-Click for about |</center>') self.mInst.setFont(font) ll.addWidget(self.mIcon) ll.addWidget(self.mInst) ll.addWidget(self.fInst) ml.addLayout(ll)
def __init__(self, parent=None): super(managebkm, self).__init__(parent) appicom = QIcon(":/icons/njnlogo.png") self.setWindowIcon(appicom) self.setWindowTitle("Nigandu | Manage Book Marks") self.setFixedSize(463, 242) self.verticalLayoutWidget = QWidget(self) self.verticalLayoutWidget.setGeometry(QRect(350, 30, 101, 201)) self.verticalLayoutWidget.setObjectName("verticalLayoutWidget") self.verticalLayout = QVBoxLayout(self.verticalLayoutWidget) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName("verticalLayout") self.sortbtn = QPushButton(self.verticalLayoutWidget) self.sortbtn.setText("&Sort") self.verticalLayout.addWidget(self.sortbtn) self.deletebtn = QPushButton(self.verticalLayoutWidget) self.deletebtn.setText("&Delete") self.verticalLayout.addWidget(self.deletebtn) self.deleteallbtn = QPushButton(self.verticalLayoutWidget) self.deleteallbtn.setText("Delete &All") self.verticalLayout.addWidget(self.deleteallbtn) self.closebtn = QPushButton(self.verticalLayoutWidget) self.closebtn.setText("&Close") self.verticalLayout.addWidget(self.closebtn) self.listWidget = QListWidget(self) self.listWidget.setGeometry(QRect(10, 30, 331, 201)) self.label = QLabel(self) self.label.setGeometry(QRect(20, 10, 91, 25)) font = QFont() font.setPointSize(10) self.label.setFont(font) self.label.setBuddy(self.listWidget) self.label.setText("Book Mark List:")
from sys import argv, exit from PySide.QtGui import QApplication, QFont, QFontMetrics from mainwindow import MainWindow app = QApplication(argv) font = QFont(QApplication.font()) font.setPointSize(14) w = MainWindow() metrics = QFontMetrics(font) w.resize(metrics.width('M') * 80, metrics.height() * 24) w.show() exit(app.exec_())
class GameStatusView(QFrame): """ It's the game status view """ def __init__(self, level, width, height, parent=None): """ """ QFrame.__init__(self, parent) self.level = level self.setup() self.updateView() self.color = QColor(200, 200, 200) self.setStyleSheet("QFrame { background-color: %s }" % self.color.name()) self.resize(width, height) def setup(self): """ Setup the View """ self.setupFont() self.setupPowerLabel() self.setupMovesLabel() self.setupRemainingDefensesLabels() def setupFont(self): """ Setup the Font """ self.font = QFont() self.font.setPointSize(14) def setupPowerLabel(self): """ Setup the Power Label """ self.powerLabel = QLabel("", self) self.powerLabel.move(32, 16) self.powerLabel.setFont(self.font) def setupMovesLabel(self): """ Setup the Moves Label """ self.movesLabel = QLabel("", self) self.movesLabel.move(32, 16 + 48) self.movesLabel.setFont(self.font) def setupRemainingDefensesLabels(self): """ Setup the Remaining Defenses Labels """ self.remainingDefensesLabels = {} labelNumber = 1 remainingDefenses = self.level.getRemainingDefenses() for defenseClass in remainingDefenses: label = QLabel("", self) label.move(32, 16 + 48 * (labelNumber + 1)) label.setFont(self.font) self.remainingDefensesLabels[defenseClass] = label labelNumber += 1 def updateView(self): """ Update the View """ self.updatePowerLabel() self.updateMovesLabel() self.updateRemainingDefensesLabels() def updatePowerLabel(self): """ Update the Power Label """ self.powerLabel.setText("Power: {0}".format( self.level.drone.powerRating.power)) def updateMovesLabel(self): """ Update the Moves Label """ self.movesLabel.setText("Moves: {0}".format( self.level.moveRating.moveCount)) self.movesLabel.resize(self.movesLabel.contentsRect().width(), self.movesLabel.contentsRect().height()) def updateRemainingDefensesLabels(self): """ Update the Remaining Mines Label """ remainingDefenses = self.level.getRemainingDefenses() for defenseClass in remainingDefenses: label = self.remainingDefensesLabels[defenseClass] label.setText("{0} Left: {1}".format( defenseClass.friendlyName, remainingDefenses[defenseClass]))
class MyDelegate(QStyledItemDelegate): def __init__(self): super(MyDelegate, self).__init__() self.bgColor = QBrush(QColor("#333333")) self.outlineColor = QPen(QColor("#555555")) self.posterBrush = QBrush(QColor("#000000")) self.posterOutline = QPen(QColor("#ffffff")) self.selectedColor = QBrush(QColor("#777777")) self.selectedOutline = QPen(QColor("#999999")) self.transparentBG = QBrush(QColor(255, 255, 255, 60)) self.watchedBG = QBrush(QColor(0, 0, 0, 180)) self.unWatchedBG = QBrush(QColor(0, 0, 0, 0)) # self.selectedOutline.setWidth(4) # buggy line drawing self.font = QFont() self.font.setPointSize(13) def paint(self, painter, option, index): """ Overrideoljuk a saját igényeinkre""" rect = option.rect movieObj = index.data(Qt.UserRole) # BACKGROUND rect painter.setPen(Qt.NoPen) if option.state & QStyle.State_Selected: painter.setBrush(self.selectedColor) else: painter.setBrush(self.bgColor) painter.drawRect(rect) # POSTER rect painter.setBrush(self.posterBrush) painter.setPen(self.posterOutline) # Posert image rect pixmap = QPixmap(movieObj.poster) pixmapRect = QRect(rect.x() + 5, rect.y() + 5, pixmap.width(), pixmap.height()) painter.drawPixmap(pixmapRect, pixmap) # TITLE rect painter.setFont(self.font) titleRect = QRect(pixmapRect.left(), pixmapRect.bottom(), pixmapRect.width(), 40) painter.drawText(titleRect, Qt.AlignVCenter | Qt.AlignHCenter, movieObj.name) if option.state & QStyle.State_Selected: painter.setPen(Qt.NoPen) painter.setBrush(self.transparentBG) painter.drawRect(rect) if movieObj.getMovieWatchedStatus() == 1: watchedRect = QRect(rect.x() + 2, rect.y() + 2, 25, 25) watchedIcon = QPixmap(fileUtils.get_icon("watchedfiltericon")) painter.setBrush(self.watchedBG) painter.drawPixmap(watchedRect, watchedIcon) painter.setBrush(self.watchedBG) painter.setPen(Qt.NoPen) painter.drawRect( QRect(rect.x() - 2, rect.y() - 2, rect.width() + 4, rect.height() + 4)) elif movieObj.getMovieWatchedStatus() == 0: painter.setBrush(self.unWatchedBG) painter.setPen(Qt.NoPen) painter.drawRect( QRect(rect.x() - 2, rect.y() - 2, rect.width() + 4, rect.height() + 4))
class ScriptSetVal(QMainWindow): def __init__(self, tabID, subWinHandle, parent=None): super(ScriptSetVal, self).__init__(parent) self.tabID = tabID self.subWinHandle = subWinHandle self.tableHandle = subWinHandle.widget().centralWidget() self.initUI() self.initToolBar() self.initDocker() def initUI(self): self.t = QTextEdit() self.initFont() self.setCentralWidget(self.t) self.setGeometry(QRect(200, 200, 410, 610)) self.setAttribute(Qt.WA_DeleteOnClose) self.show() def initToolBar(self): self.scriptbar = QToolBar('plot options') self.addToolBar( Qt.BottomToolBarArea , self.scriptbar) scriptAction = QAction('set script', self) self.scriptbar.addAction(scriptAction) scriptAction.triggered.connect(self.RelectRng) def initFont(self): self.tabStop = 4 self.font = QFont('Courier') self.metrics = QFontMetrics(self.font) self.t.setTabStopWidth(self.tabStop * self.metrics.width(' ')); self.font.setStyleHint(QFont.Monospace); self.font.setFixedPitch(True); self.font.setPointSize(12) self.p = self.t.palette() self.p.setColor(QPalette.Base, QColor(0, 0, 0)) self.p.setColor(QPalette.Text, QColor(255, 255, 255)) self.t.setPalette(self.p) self.t.setFont(self.font) self.highlighter = Highlighter(self.t.document()) def initDocker(self): self.elog = QTextEdit() self.elogDockWidget = QDockWidget(" :: error log ::", self) self.elogDockWidget.setFeatures(QDockWidget.DockWidgetMovable) self.elogDockWidget.setAllowedAreas(Qt.TopDockWidgetArea and Qt.BottomDockWidgetArea) self.addDockWidget(Qt.BottomDockWidgetArea, self.elogDockWidget) self.elogDockWidget.setWidget(self.elog) self.p = self.elog.palette() self.p.setColor(QPalette.Base, QColor(0, 0, 0)) self.p.setColor(QPalette.Text, QColor(255, 0, 0)) self.elog.setPalette(self.p) self.elog.setReadOnly(True) def RelectRng(self): try: self.selectAry = [] if len(self.tableHandle.selectedRanges()) != 0: for i in range( len(self.tableHandle.selectedRanges())): self.leftCol = self.tableHandle.selectedRanges()[i].leftColumn() self.colCount = self.tableHandle.selectedRanges()[i].columnCount() for currentCol in range( self.leftCol, self.leftCol + self.colCount ): self.selectAry.append( currentCol ) self.leftCol = self.tableHandle.selectedRanges()[0].leftColumn() self.colCount = self.tableHandle.selectedRanges()[0].columnCount() self.topRow = self.tableHandle.selectedRanges()[0].topRow() self.rowCount = self.tableHandle.selectedRanges()[0].rowCount() rows = [] cols = [] for i in range(self.topRow, self.topRow + self.rowCount, 1): rows.append(i) for i in range(self.leftCol, self.leftCol + self.colCount, 1): cols.append(i) try: exec(self.t.toPlainText()) except Exception, e: self.elog.moveCursor(QTextCursor.End) self.elog.textCursor().insertHtml('<span style="color:#FF0000">Error: '+str(e)+'</span><br>') print str(e) else:
class LevelDetailsView(QFrame): """ Represents the View of the Level Details """ DEFENSE_ORDER = [Mine, ReverseMine, FragileMine, Worm, AntiDroneMine] def __init__(self, levelSelection, parent=None): """ Initialize the Level Details View """ QFrame.__init__(self, parent) #self.resize(self.WIDTH, self.HEIGHT) self.levelSelection = levelSelection self.smallFont = QFont() self.smallFont.setPointSize(14) self.bigFont = QFont() self.bigFont.setPointSize(24) self.detailsLabel = self.getLabel("Level Details", self.bigFont, alignment=Qt.AlignCenter) self.detailsLabel.move(32, 16) self.setupGridLabel() self.setupDefensesLabels() self.setupRatingsLabel() def getLabel(self, text, font, alignment=None): """ Get a Level Label with the text """ label = QLabel(text, self) label.setFont(font) if alignment: label.setAlignment(alignment) return label def setupGridLabel(self): """ Setup the Grid Label """ self.gridLabel = self.getLabel("", self.smallFont) self.gridLabel.move(32, 48+16) self.gridLabel.resize(200, 32) def setupRatingsLabel(self): """ Setup the Ratings Label """ self.ratingsLabel = self.getLabel("", self.smallFont) self.ratingsLabel.move(32, 48+16) self.ratingsLabel.resize(200, 32) def setupDefensesLabels(self): """ Setup the Remaining Defenses Labels """ self.defensesLabels = {} for defenseClass in self.DEFENSE_ORDER: label = self.getLabel("", self.smallFont) label.setVisible(False) label.resize(200, 32) self.defensesLabels[defenseClass] = label def updateView(self): """ Update the View """ self.updateGridLabel() self.updateDefenseLabels() self.updateRatingsLabel() self.update() def updateGridLabel(self): """ Update the Grid Label """ level = self.levelSelection.getLevel() self.gridLabel.setText("{0} x {1}".format(level.rows, level.columns)) def updateDefenseLabels(self): """ Update the Defense Label """ defenses = self.levelSelection.getLevel().defenses labelNumber = 1 for defenseClass in self.DEFENSE_ORDER: label = self.defensesLabels[defenseClass] if defenseClass in defenses: label.setVisible(True) label.setText("{0}: {1}".format(defenseClass.friendlyName, defenses[defenseClass])) label.move(32, 48+32*(labelNumber+1)) labelNumber += 1 else: label.setVisible(False) def updateRatingsLabel(self): """ Update the Ratings Label """ self.ratingsLabel.move(32, 48+32*(len(self.levelSelection.getLevel().defenses)+3)) text = "" if CURRENT_PROFILE.completedLevel(self.levelSelection.getLevel()): text += "C" if CURRENT_PROFILE.acheivedMoveAwardOnLevel(self.levelSelection.getLevel()): text += "M" if CURRENT_PROFILE.acheivedPowerAwardOnLevel(self.levelSelection.getLevel()): text += "P" self.ratingsLabel.setText(text)
class OrderWorkflowDialog(QDialog): def _makeArrow( self, ra, rb, both_ways=True): ca = QPointF( ra.x() + float(ra.width()) / 2.0, ra.y() + float(ra.height()) / 2.0) cb = QPointF( rb.x() + rb.width() / 2.0, rb.y() + rb.height() / 2.0) dx = cb.x() - ca.x() dy = cb.y() - ca.y() d = dist(dx,dy) a = math.atan2(float(dy),float(dx)) # The result is between -pi and pi # ra_rad = dist(ra.width() / 2, ra.height() / 2) # rb_rad = dist(rb.width() / 2, rb.height() / 2) x,y = squircle(ra.width() / 2, ra.height() / 2, to_squircle_angle(ra.width() / 2, ra.height() / 2,a)) ra_rad = dist(x,y) + 10 # painter.drawLine(ca,QPoint(ca.x() + x, ca.y() + y)) na = a if a < 0: na += math.pi else: na -= math.pi x,y = squircle(float(rb.width()) / 2.0, float(rb.height()) / 2.0, to_squircle_angle(float(rb.width()) / 2.0, float(rb.height()) / 2.0,na)) rb_rad = dist(x,y)+10 # ra_rad = rb_rad = 0 # painter.drawLine(ca,cb) # painter.drawRect(ra) # painter.setPen(Qt.GlobalColor.red) # painter.drawRect(rb) # painter.setPen(Qt.GlobalColor.black) # for t in range(100): # ang = 6.28/100.0*float(t) # x,y = squircle( 200,50,ang) # painter.drawPoint(300 + x,100 + y) qp = QPolygonF() h = 5 v = [] v.append(QPointF(ra_rad,0)) if not both_ways: v.append(QPointF(ra_rad,-h/2)) else: v.append(QPointF(ra_rad + 2*h,-2*h)) v.append(QPointF(ra_rad + 2*h,-h/2)) v.append(QPointF(d - rb_rad - 2*h,-h/2)) v.append(QPointF(d - rb_rad - 2*h,-2*h)) v.append(QPointF(d - rb_rad, 0)) v.append(QPointF(d - rb_rad - 2*h,+2*h)) v.append(QPointF(d - rb_rad - 2*h,+h/2)) if not both_ways: v.append(QPointF(ra_rad,+h/2)) else: v.append(QPointF(ra_rad + 2*h,+h/2)) v.append(QPointF(ra_rad + 2*h,+2*h)) v.append(QPointF(ra_rad,0)) p = QPolygonF(v) item = QGraphicsPolygonItem(p) item.translate(ca.x(),ca.y()) item.rotate(math.degrees(a)) return item def _drawNodes(self,scene,selected_state,initial_state): for i in scene.items(): scene.removeItem(i) pos = dict() sx = 1 sy = 1 if configuration.font_select: sx = sx * 2 sy = sy pos[OrderStatusType.preorder_definition] = (200*sx,200*sy) pos[OrderStatusType.order_definition] = (10*sx,300*sy) pos[OrderStatusType.order_ready_for_production] = (300*sx,300*sy) pos[OrderStatusType.order_production_paused] = (200*sx,550*sy) pos[OrderStatusType.order_completed] = (400*sx,600*sy) pos[OrderStatusType.order_aborted] = (10*sx,600*sy) mainlog.debug("_drawNodes : selected_state {}".format(selected_state)) mainlog.debug("_drawNodes : initial_state {}".format(initial_state)) for org in OrderStatusType.symbols(): x,y = pos[org] item = QGraphicsSimpleTextItem(org.description) if (selected_state and org in OrderStatusType.next_states(selected_state)) or org == initial_state or org == selected_state: item = MyQGraphicsSimpleTextItem(org, self) item.setFlags( item.flags() | QGraphicsItem.ItemIsSelectable) if org == selected_state: mainlog.debug("Preselcting {}".format(org)) item.setSelected(True) item.setFont(self.thinfont) item.setPos(x,y) scene.addItem(item) pos[org] = item.boundingRegion( item.sceneTransform()).boundingRect() # scene.addRect(pos[org]) g_orgs = dict() for org in OrderStatusType.symbols(): g_orgs[org] = OrderStatusType.next_states(org) # Draw all arrows which don't end up or leave the selected_state drawn = [] for org,dests in g_orgs.iteritems(): for dest in dests: if selected_state != org and ((org,dest) not in drawn) and ((dest,org) not in drawn): # If an arrow must have two directions, we draw it # like that directly. item = self._makeArrow( pos[org],pos[dest],dest in g_orgs and org in g_orgs[dest]) item.setPen(self.grey_pen) scene.addItem( item) drawn.append((org,dest)) if initial_state: scene.addRect(pos[initial_state]) if selected_state: for dest in OrderStatusType.next_states(selected_state): item = self._makeArrow( pos[selected_state],pos[dest],False) item.setBrush(QBrush(Qt.green)) scene.addItem( item) drawn.append((org,dest)) @Slot() def selectionChanged(self): pass def __init__(self,parent): global configuration super(OrderWorkflowDialog,self).__init__(parent) self.grey_pen = QPen(Qt.gray) title = _("Order workflow") self.setWindowTitle(title) self.title_widget = TitleWidget(title,self) self.buttons = QDialogButtonBox() self.buttons.addButton( QDialogButtonBox.Ok) self.buttons.addButton( QDialogButtonBox.Cancel) self.thinfont = QFont() if configuration.font_select: self.thinfont.setPointSize(self.thinfont.pointSize()*2) self.scene = QGraphicsScene() self.scene.selectionChanged.connect(self.selectionChanged) self.view = QGraphicsView(self) self.view.setRenderHint(QPainter.Antialiasing) self.view.setScene(self.scene) top_layout = QVBoxLayout() top_layout.addWidget(self.title_widget) top_layout.addWidget(self.view) top_layout.addWidget(self.buttons) self.setLayout(top_layout) # QWidget takes ownership of the layout self.buttons.accepted.connect(self.save_and_accept) self.buttons.rejected.connect(self.cancel) self.initial_state = None self.selected_state = None self._drawNodes(self.scene,self.selected_state,self.initial_state) def set_selected_state(self,selected_state,initial_state): mainlog.debug("selected_state {}".format(selected_state)) mainlog.debug("initial_state {}".format(initial_state)) self.initial_state = initial_state self.selected_state = selected_state self._drawNodes(self.scene,selected_state,self.initial_state) @Slot() def cancel(self): return super(OrderWorkflowDialog,self).reject() @Slot() def save_and_accept(self): super(OrderWorkflowDialog,self).accept() s = self.scene.selectedItems() if s: # In cas there are more than one item selected, # we pick the first one (arbitrarily) self.selected_state = s[0].state else: self.selected_state = self.initial_state
def __init__(self, parent=None): super(Truss, self).__init__(parent) self.resize(800, 600) self.filename = None self.filetuple = None self.dirty = False # Refers to Data Page only. centralwidget = QWidget(self) gridLayout = QGridLayout(centralwidget) self.tabWidget = QTabWidget(centralwidget) self.tab = QWidget() font = QFont() font.setFamily("Courier 10 Pitch") font.setPointSize(12) self.tab.setFont(font) gridLayout_3 = QGridLayout(self.tab) self.plainTextEdit = QPlainTextEdit(self.tab) gridLayout_3.addWidget(self.plainTextEdit, 0, 0, 1, 1) self.tabWidget.addTab(self.tab, "") self.tab_2 = QWidget() self.tab_2.setFont(font) gridLayout_2 = QGridLayout(self.tab_2) self.plainTextEdit_2 = QPlainTextEdit(self.tab_2) gridLayout_2.addWidget(self.plainTextEdit_2, 0, 0, 1, 1) self.tabWidget.addTab(self.tab_2, "") gridLayout.addWidget(self.tabWidget, 0, 0, 1, 1) self.setCentralWidget(centralwidget) menubar = QMenuBar(self) menubar.setGeometry(QRect(0, 0, 800, 29)) menu_File = QMenu(menubar) self.menu_Solve = QMenu(menubar) self.menu_Help = QMenu(menubar) self.setMenuBar(menubar) self.statusbar = QStatusBar(self) self.setStatusBar(self.statusbar) self.action_New = QAction(self) self.actionSave_As = QAction(self) self.action_Save = QAction(self) self.action_Open = QAction(self) self.action_Quit = QAction(self) self.action_About = QAction(self) self.actionShow_CCPL = QAction(self) self.action_Solve = QAction(self) self.action_CCPL = QAction(self) self.action_Help = QAction(self) menu_File.addAction(self.action_New) menu_File.addAction(self.action_Open) menu_File.addAction(self.actionSave_As) menu_File.addAction(self.action_Save) menu_File.addSeparator() menu_File.addAction(self.action_Quit) self.menu_Solve.addAction(self.action_Solve) self.menu_Help.addAction(self.action_About) self.menu_Help.addAction(self.action_CCPL) self.menu_Help.addAction(self.action_Help) menubar.addAction(menu_File.menuAction()) menubar.addAction(self.menu_Solve.menuAction()) menubar.addAction(self.menu_Help.menuAction()) self.setWindowTitle("Main Window") self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab),\ "Data Page") self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2),\ "Solution Page") menu_File.setTitle("&File") self.menu_Solve.setTitle("&Solve") self.menu_Help.setTitle("&Help") self.tabWidget.setCurrentIndex(0) self.action_New.setText("&New") self.action_Open.setText("&Open") self.actionSave_As.setText("Save &As") self.action_Save.setText("&Save") self.action_Quit.setText("&Quit") self.action_Solve.setText("&Solve") self.action_About.setText("&About") self.action_CCPL.setText("&CCPL") self.action_Help.setText("&Help") self.action_Quit.triggered.connect(self.close) allToolBar = self.addToolBar("AllToolBar") allToolBar.setObjectName("AllToolBar") self.addActions(allToolBar, (self.action_Open, self.actionSave_As,\ self.action_Save, self.action_Solve,\ self.action_Quit )) self.action_New.triggered.connect(self.fileNew) self.action_Open.triggered.connect(self.fileOpen) self.actionSave_As.triggered.connect(self.fileSaveAs) self.action_Save.triggered.connect(self.fileSave) self.action_Solve.triggered.connect(self.trussSolve) self.action_About.triggered.connect(self.aboutBox) self.action_CCPL.triggered.connect(self.displayCCPL) self.action_Help.triggered.connect(self.help) self.plainTextEdit.textChanged.connect(self.setDirty) self.action_New = self.editAction(self.action_New, None,\ 'ctrl+N', 'filenew', 'New File.') self.action_Open = self.editAction(self.action_Open, None, 'ctrl+O', 'fileopen', 'Open File.') self.actionSave_As = self.editAction(self.actionSave_As,\ None, 'ctrl+A', 'filesaveas',\ 'Save and Name File.') self.action_Save = self.editAction(self.action_Save, None, 'ctrl+S', 'filesave', 'Save File.') self.action_Solve = self.editAction(self.action_Solve, None, 'ctrl+L', 'solve', 'Solve Structure.') self.action_About = self.editAction(self.action_About, None, 'ctrl+B', 'about','Pop About Box.') self.action_CCPL = self.editAction(self.action_CCPL, None, 'ctrl+G', 'licence', 'Show Licence') self.action_Help = self.editAction(self.action_Help, None, 'ctrl+H', 'help', 'Show Help Page.') self.action_Quit = self.editAction(self.action_Quit, None, 'ctrl+Q', 'quit', 'Quit the program.') self.plainTextEdit_2.setReadOnly(True)
class PostViewScene(QGraphicsScene): def set_cursor_on(self, opdef_id): if opdef_id in self.posts_offsets: coord = self.posts_offsets[opdef_id] cover = self.cursor.rect().united(coord) self.cursor.setRect(coord) self.update(cover) def _operation_hoover_description(self, op): # order_part = op.production_file.order_part txt = [ u"{} {}".format(op.order_part_human_identifier, date_to_dmy(op.deadline)), # order_part.deadline op.order_part_description or "", op.description or "", _("{}x{}={}h, rest:{}h").format( op.qty, nice_round(op.planned_hours), nice_round(op.qty * op.planned_hours), nice_round(op.planned_hours * op.qty - op.done_hours)) ] return txt def reload(self, order_overview_widget, all_ops, all_operations, sort=1): # mainlog.debug("reload...") progress = QProgressDialog(_("Collecting data..."), None, 0, len(all_ops) + 3, order_overview_widget) progress.setWindowTitle("Horse") progress.setMinimumDuration(0) progress.setWindowModality(Qt.WindowModal) progress.setValue(progress.value() + 1) progress.show() for i in self.items(): self.removeItem(i) self.posts_offsets = dict() self.drawn_operations_data = dict() self.cursor = QGraphicsRectItem(0, 0, 50, 300) self.cursor.setBrush(QBrush(QColor(208, 208, 255, 255))) self.cursor.setPen(QPen(Qt.transparent)) self.addItem(self.cursor) bar_width = 8 bar_height = int(bar_width * 60.0 / 8.0) ascent = QFontMetrics(self.base_font).ascent() ascent_big = QFontMetrics(self.base_font_big).ascent() post_ops = {} # mainlog.debug("reload...2") # z = 0 # for op,order_part,parts in all_operations: # z = op.planned_hours # z = order_part.deadline # z = order_part.qty # z = order_part.human_identifier # all_operations = map(lambda i:i[0],all_operations) y = 0 for opdef in all_ops: progress.setValue(progress.value() + 1) operations = filter( lambda op: op.operation_definition_id == opdef. operation_definition_id, all_operations) # We're only interested in the effort/time that remains # to be put on an operation. We're only interested in # the future. # We want the oeprations that are either # - ongoing # - ready to start. # In all cases we're only interested in operations # that are "active" if sort == 1: operations = sorted( operations, key=lambda op: op.deadline or date(3000, 1, 1)) elif sort == 2: operations = sorted( operations, key=lambda op: op.planned_hours * op.qty - op.done_hours) else: # Don't sort pass maximum = 16.0 #float ! small_hours = 0 op_ndx = 0 current_x = 50 bar_drawn = False total_done_hours = total_estimated = 0 # -------------------------------------------------------------- # Started operations bars_line = BarsLine(16, bar_width, bar_height, current_x, y, self, order_overview_widget) total_hours_to_do = 0 for op in filter(lambda op: op.done_hours > 0, operations): hours_to_do = max( 0, op.planned_hours * op.qty - op.done_hours) # max protects against reporting errors total_hours_to_do += hours_to_do total_estimated += op.planned_hours * op.qty total_done_hours += op.done_hours bars_line.add_bar(hours_to_do, QBrush(Qt.green), self._operation_hoover_description(op), False, None) # op.production_file.order_part) # -------------------------------------------------------------- bars_line_unstarted_operations = BarsLine(16, bar_width, bar_height, current_x + 30, y, self, order_overview_widget) total_hours_to_do_on_unstarted_operations = 0 for op in filter(lambda op: op.done_hours == 0, operations): hours_to_do = op.planned_hours * op.qty total_hours_to_do_on_unstarted_operations += hours_to_do total_estimated += hours_to_do bars_line_unstarted_operations.add_bar( hours_to_do, QBrush(Qt.yellow), self._operation_hoover_description(op), False, None) #op.production_file.order_part) y_start = y total = total_hours_to_do + total_hours_to_do_on_unstarted_operations if total > 0: self.drawn_operations_data[ opdef.operation_definition_id] = "{}h".format( int(round(total_estimated))) gi = QGraphicsSimpleTextItem( _("{} - Estimated to do : {}h; done : {}h").format( opdef.description, int(round(total)), int(round(total_done_hours)))) gi.setFont(self.base_font_big) gi.setPos(0, y - gi.boundingRect().height()) self.addItem(gi) th = gi.boundingRect().height() gi = QGraphicsLineItem(-ascent_big, y, 1024 + 2 * ascent_big, y) gi.setPen(QPen(Qt.black)) self.addItem(gi) y += th else: continue y_bars = y if total_hours_to_do > 0: # There's something to draw head = QGraphicsSimpleTextItem(_("Started")) head.setFont(self.base_font) head.setPos(current_x, y) self.addItem(head) y += head.boundingRect().height() y += bar_height bars_line.set_start_pos(current_x, y) bars_line.finish_bar() foot = QGraphicsSimpleTextItem( _("{}h").format(int(total_hours_to_do + 0.5))) foot.setFont(self.base_font) foot.setPos(current_x, y) self.addItem(foot) y += foot.boundingRect().height() current_x = max(current_x + bars_line.estimate_width(), head.boundingRect().right(), foot.boundingRect().right()) bar_drawn = True if total_hours_to_do_on_unstarted_operations > 0: if bars_line_unstarted_operations.estimate_width( ) + current_x > 1200: x = 50 y += ascent_big else: y = y_bars x = current_x + 50 head = QGraphicsSimpleTextItem(_("Not started yet")) head.setFont(self.base_font) head.setPos(x, y) self.addItem(head) y += head.boundingRect().height() y += bar_height bars_line_unstarted_operations.set_start_pos(x, y) bars_line_unstarted_operations.finish_bar() foot = QGraphicsSimpleTextItem( _("{}h").format( int(total_hours_to_do_on_unstarted_operations + 0.5))) foot.setFont(self.base_font) foot.setPos(x, y) self.addItem(foot) y += foot.boundingRect().height() bar_drawn = True y += 3 * ascent_big r = self.sceneRect() self.posts_offsets[opdef.operation_definition_id] = \ QRectF(r.x() - 2*ascent_big, y_start - 1.5*ascent_big, r.width() + 4*ascent_big, (y - ascent_big) - (y_start - 1.5*ascent_big) ) y += ascent_big # mainlog.debug("reload...3") import functools max_width = functools.reduce(lambda acc, po: max(acc, po.width()), self.posts_offsets.values(), 0) map(lambda po: po.setWidth(max_width), self.posts_offsets.values()) # for r in self.posts_offsets.values(): # gi = QGraphicsLineItem(r.x(),r.y(),r.x()+r.width(),r.y()) # gi.setPen(QPen(Qt.lightGray)) # self.addItem(gi) progress.close() def __init__(self, parent, order_overview_widget): global configuration super(PostViewScene, self).__init__(parent) self.base_font = QFont() self.base_font_big = QFont() self.base_font_big.setPointSize(self.base_font.pointSize() * 1.5) if configuration.font_select: self.base_font_big.setPointSize(self.base_font.pointSize() * 2)
class HooverBar(QGraphicsRectItem): def __init__(self, x, y, w, h, hoover_text, doubleclick_callback_widget, order_part_id): """ doubleclick_callback_widget : we will call the set_on_orderpart method of that object if a doubleclik happens here. """ super(HooverBar, self).__init__(x, y, w, h) self.setAcceptHoverEvents(True) self.gi = None self.hoover_text = hoover_text self.description = None self.doubleclick_callback_widget = doubleclick_callback_widget self.order_part_id = order_part_id self.base_font = QFont() if configuration.font_select: self.base_font.setPointSize(self.base_font.pointSize() * 2) def hoverEnterEvent(self, event): # QGraphicsSceneHoverEvent * event ) # BUG I had a crash running this, I suspect ownership issues regarding # graphics items... global configuration #mainlog.debug("hoverEnterEvent pos={}-{}".format(event.scenePos().x(),event.scenePos().y())) # mainlog.debug("hoverEnterEvent data={}".format(self.data)) super(HooverBar, self).hoverEnterEvent(event) if self.gi == None: if self.hoover_text: self.gi = QGraphicsRectItem(0, 0, 100, 100) self.gi.setBrush(QBrush(QColor(0, 64, 0, 192))) self.gi.setPen(QPen(Qt.transparent)) self.gi.setPos(event.scenePos().x() + 20, event.scenePos().y() + 20) # txt = [ "" ] # txt = [ u"{} {}".format(self.data.production_file.order_part.human_identifier, # date_to_dmy(self.data.production_file.order_part.deadline)), # nstr(self.data.production_file.order_part.description), # nstr(self.data.description), # _("{}x{}={}h, rest:{}h").format(self.data.production_file.order_part.qty, # nice_round(self.data.planned_hours), # nice_round(self.data.production_file.order_part.qty*self.data.planned_hours), # nice_round(self.data.planned_hours*self.data.production_file.order_part.qty - self.data.done_hours))] x = y = 10 w = 0 for t in self.hoover_text: description = QGraphicsSimpleTextItem() description.setFont(self.base_font) description.setBrush(QBrush(Qt.white)) description.setText(t) description.setParentItem(self.gi) description.setPos(x, y) y += description.boundingRect().height() w = max(w, description.boundingRect().width()) y += x w += 2 * x # description.setHtml(u"|{}| <b>{}</b><br/>{}<br>{}x{}={}h".format( # self.data.production_file.order_part.human_identifier, # self.data.production_file.order_part.description, # self.data.description, # self.data.production_file.order_part.qty, self.data.planned_hours, self.data.production_file.order_part.qty*self.data.planned_hours)) # description.setDefaultTextColor(Qt.white) # br = description.boundingRect() self.gi.setRect(0, 0, w, y) self.scene().addItem(self.gi) #mainlog.debug("hoverEnterEvent GI={}".format(self.gi)) # mainlog.debug("hoverEnterEvent Done") def hoverMoveEvent(self, event): super(HooverBar, self).hoverMoveEvent(event) # if self.gi: # mainlog.debug("hoverMoveEvent GI pos={}-{}".format(self.gi.pos().x(),self.gi.pos().y())) # mainlog.debug("hoverMoveEvent pos={}-{}".format(event.scenePos().x(),event.scenePos().y())) if self.gi: self.gi.setPos(event.scenePos().x() + 20, event.scenePos().y() + 20) def hoverLeaveEvent(self, event): super(HooverBar, self).hoverLeaveEvent(event) if self.gi: # mainlog.debug("hoverLeaveEvent GI={}".format(self.gi)) # self.gi.setActive(False) # self.gi.setVisible(False) # return if self.description: # I do this so that I can handle the destruction of description # graphics item myself (i.e. description won't be deleted # as a children of self.gi) self.description.setParentItem(None) self.description = None # and delete... # QtDoc : Removes the item item and all its children from the scene. # The ownership of item is passed on to the caller self.gi.setParentItem(None) # self.scene().removeItem(self.gi) self.gi = None # mainlog.debug("hoverLeaveEvent -- done") # order_part_double_clicked = Signal(int) def mouseDoubleClickEvent(self, event): # QGraphicsSceneHoverEvent * event ) # mainlog.debug("mouseDoubleClickEvent {}".format(self.data)) super(HooverBar, self).mouseDoubleClickEvent(event) self.doubleclick_callback_widget.set_on_order_part(self.order_part_id)
class EditorWindow(QMainWindow): """initialize editor""" def __init__(self, tixi, xmlFilename, cpacs_scheme=Config.path_cpacs_21_schema): super(EditorWindow, self).__init__() self.cur_file_path = "" self.cur_schema_path = "" self.setupEditor() self.setupButtonMenu() self.setupSearchBox() self.setupStatusbar() self.setupMenubar() self.setupNumbar() self.popUpWidget = None self.flag_layout = False self.hbox = QHBoxLayout() self.hbox.setSpacing(0) self.hbox.setContentsMargins(0,0,0,0) self.hbox.addWidget(self.number_bar) self.hbox.addWidget(self.editor) self.layout = QGridLayout() self.layout.addWidget(self.searchbox, 0, 0, 1, 4) self.layout.addWidget(self.button1, 0, 4, 1, 1) self.layout.addWidget(self.button2, 0, 5, 1, 1) self.layout.addLayout(self.hbox, 2, 0, 1, 8) self.layout.addWidget(self.fontsizeSpinBox, 0, 6, 1, 1) self.layout.addWidget(self.label1, 0, 7, 1, 1) self.window = QWidget() self.window.setLayout(self.layout) self.setWindowTitle('Simple XML editor') self.setCentralWidget(self.window) self.resize(800, 800) self.show() self.tixi = tixi self.loadFile(xmlFilename, cpacs_scheme) ''' loads cpacs file and validates it against the cpacs_schema @param xmlFilename: input file @param cpacs_scheme: validation scheme ''' def loadFile(self, xmlFilename=None, cpacs_scheme=Config.path_cpacs_21_schema): if xmlFilename and cpacs_scheme : try: self.tixi.open(xmlFilename) #self.tixi.openDocument(xmlFilename) #self.tixi.schemaValidateFromFile(cpacs_scheme) self.editor.setPlainText(self.tixi.exportDocumentAsString()) self.cur_file_path = xmlFilename self.cur_schema_path = cpacs_scheme except TixiException as e: self.statusBar().showMessage('CPACS ERROR: ' + e.error) ''' update the dictionary by the cpacs scheme @param path_dict: path to directory @param path_scheme: path to cpacs_scheme ''' def updatedictionary(self, path_dict=Config.path_code_completion_dict, path_scheme=Config.path_cpacs_21_schema): found = False olddict = open(path_dict) scheme_file = open(path_scheme, 'r') with open(path_dict, "a") as newdict : for line in scheme_file : word = re.search("(?<=\<xsd:complexType name=\").*(?=\"\>)", line) if word != None : for tmp in olddict : if tmp == word.group(0) +"\n" : found = True break if(not found) : newdict.write(word.group(0)+"\n") olddict.seek(0) found = False olddict.close() newdict.close() scheme_file.close() ''' validate xml file and write result to statusBar ''' def validate(self): try: etree.fromstring(str(self.editor.toPlainText())) self.statusBar().showMessage("Valid XML") except etree.XMLSyntaxError as e: if e.error_log.last_error is not None: msg = e.error_log.last_error.message line = e.error_log.last_error.line col = e.error_log.last_error.column self.statusBar().showMessage("Invalid XML: Line %s, Col %s: %s"%(line,col,msg)) except: self.statusBar().showMessage("Invalid XML: Unknown error") ''' close and cleanup tixi ''' def __del__(self): pass #self.tixi.close() #self.tixi.cleanup() ''' set and connect the search buttons ''' def setupButtonMenu(self): self.button1 = QPushButton("previous" ) self.button2 = QPushButton("next" ) self.label1 = QLabel("font") self.fontsizeSpinBox = QSpinBox() self.button1.hide() self.button2.hide() self.label1.hide() self.fontsizeSpinBox.hide() self.button1.clicked.connect(self.fire_search_backward) self.button2.clicked.connect(self.fire_search_foreward) self.fontsizeSpinBox.setRange(4, 30) self.fontsizeSpinBox.setSingleStep(1) self.fontsizeSpinBox.setSuffix('pt') self.fontsizeSpinBox.setValue(10) self.fontsizeSpinBox.valueChanged.connect(self.setfontsize) def setfontsize(self, value): self.font.setPointSize(value) self.editor.setFont(self.font) def setupEditor(self): self.font = QFont() self.font.setFamily('Courier') self.font.setFixedPitch(True) self.font.setPointSize(10) self.editor = EditorCodeCompletion(Config().path_code_completion_dict) self.editor.setFont(self.font) self.editor.setTabStopWidth(20) self.editor.setAcceptRichText(False) self.editor.setLineWrapMode(QTextEdit.NoWrap) self.editor.textChanged.connect(self.validate) self.highlighter = Highlighter(self.editor.document()) def setupNumbar(self): self.number_bar = NumberBar() self.number_bar.setTextEdit(self.getStates()) self.editor.cursorPositionChanged.connect(self.fireUpdateNumbar) self.connect(self.editor.verticalScrollBar(), SIGNAL("valueChanged(int)"), self.fireUpdateNumbar) #self.editor.verticalScrollBar.valueChanged.connect(self.fireUpdateNumbar) def setupStatusbar(self): self.lineNumber = -1 self.colNumber = -1 self.m_statusRight = QLabel("row: " + str(self.lineNumber) + ", col:" + str(self.colNumber), self) self.statusBar().addPermanentWidget(self.m_statusRight, 0) def setupSearchBox(self): self.searchbox = SearchField() self.searchbox.hide() def setupMenubar(self): commentAction = QAction('Comment', self) commentAction.setShortcut('Ctrl+K') commentAction.setStatusTip('Comment Block') commentAction.triggered.connect(self.fireComment) uncommentAction = QAction('Uncomment', self) uncommentAction.setShortcut('Ctrl+Shift+K') uncommentAction.setStatusTip('Comment Block') uncommentAction.triggered.connect(self.fireUnComment) searchAction = QAction('search', self) searchAction.setShortcut('Ctrl+F') searchAction.setStatusTip('search') searchAction.triggered.connect(self.fireSearchView) newAction = QAction('New', self) newAction.setShortcut('Ctrl+N') newAction.setStatusTip('creats empty cpacs-file') newAction.triggered.connect(self.fireNewAction) self.updateAction = QAction('Update', self) self.updateAction.setShortcut('Ctrl+U') self.updateAction.setStatusTip('Update CPACS') self.updateAction.triggered.connect(self.fireUpdate) revertAction = QAction('Revert', self) revertAction.setShortcut('Ctrl+R') revertAction.triggered.connect(self.fireRevert) clearAction = QAction('Clear', self) clearAction.setStatusTip('Clear Editor') clearAction.triggered.connect(self.editor.clear) numbarAction = QAction('Line Number', self) numbarAction.triggered.connect(self.fireSwitchLayout) self.xpathAction = QAction('Current XPath', self) self.xpathAction.triggered.connect(self.getCursorXPath) link_to_node_YesAction = QAction('yes', self) link_to_node_YesAction.triggered.connect(self.dummyFuction) link_to_node_NoAction = QAction('no', self) link_to_node_NoAction.triggered.connect(self.dummyFuction) toolXAction = QAction('Tool X',self) toolXAction.triggered.connect(self.fireToolX) menubar = self.menuBar() filemenu = menubar.addMenu("File") filemenu.addAction(newAction) filemenu.addAction(self.updateAction) filemenu.addAction(revertAction) sourcemenu = menubar.addMenu("Source") sourcemenu.addAction(commentAction) sourcemenu.addAction(uncommentAction) sourcemenu.addAction(searchAction) editormenu = menubar.addMenu("Editor") editormenu.addAction(clearAction) editormenu.addSeparator() editormenu.addAction(numbarAction) editormenu.addAction(self.xpathAction) editormenu_child1 = editormenu.addMenu('Link to node') editormenu_child1.addAction(link_to_node_YesAction) editormenu_child1.addAction(link_to_node_NoAction) toolmenu = menubar.addMenu("Tools") toolmenu.addAction(toolXAction) self.editor.setContextMenuPolicy(Qt.CustomContextMenu) self.editor.customContextMenuRequested.connect(self.showMenu) #self.editor.connect(self.editor, SIGNAL( "customContextMenuRequested(QPoint)" ), self.showMenu ) def showMenu( self, pos ): """ Show a context menu for the active layer in the legend """ menu = self.editor.createStandardContextMenu() menu.addAction(self.xpathAction) menu.exec_(QtCore.QPoint( self.mapToGlobal( pos ).x() + 5, self.mapToGlobal( pos ).y() )) def fireUpdateNumbar(self): self.updateLineNumber() self.number_bar.update() def dummyFuction(self): print ("not implemented yet") def getStates(self): self.stats = { "searchbox":self.searchbox, "editor":self.editor} return self.stats ''' find previous button ''' def fire_search_backward(self): self.editor.find(self.searchbox.text(), QTextDocument.FindBackward) self.searchbox.setFocus() ''' find next button ''' def fire_search_foreward(self): #print self.tixi.getNumberOfChilds('/cpacs/vehicles/aircraft/model[@uID="Aircraft1"]/wings/wing[@uID="Aircraft1_Wing1"]/transformation[@uID="Aircraft1_Wing1_Transf"]/scaling[@uID="Aircraft1_Wing1_Transf_Sca"]/z') searchList = list(filter(lambda a : a!='', self.searchbox.text().split('/'))) if len(searchList) == 1 : if self.editor.find(searchList[0]) : pass elif not self.editor.find(searchList[0], QTextDocument.FindBackward): QMessageBox.about(self, "error", "String %s not found" % (searchList[0])) else : self.editor.moveCursor(QTextCursor.Start) self.editor.find(searchList[0]) else : self.searchXPath(self.searchbox.text(), searchList) self.searchbox.setFocus() # test # /cpacs/vehicles/aircraft/model/wings/wing/sections/section def searchXPath(self, path, searchList): try: if self.tixi.xPathEvaluateNodeNumber(path) > 1 : QMessageBox.about(self, "error", "XPath %s not unique" % path) return self.editor.moveCursor(QTextCursor.Start) found = True # search index snd loop j = 0 # search backwards for uid for i in range(len(searchList)-1, -1, -1) : if '[' in searchList[i] : # get value in brackets : [x] --> x uid = re.search(r'\[(.*)\]', searchList[i]).group(1) uid = self.__transToSearchUid(searchList[:i+1], uid) found = self.editor.find(uid) j = i+1 break # search forward for all nodes after last uid while found and j < len(searchList) : found = self.editor.find('<'+searchList[j]) j += 1 if not found : QMessageBox.about(self, "error", "XPath %s not found" % path) except TixiException : QMessageBox.about(self, "error", "XPath %s not found" % path) def __transToSearchUid(self, path_list, uid): try: int(uid) path = "" for p in path_list : path = path + '/' + p return self.tixi.getTextAttribute(path , 'uID') except ValueError: return uid.replace('@', '') def getCursorXPath(self): start_pos = self.editor.textCursor().position() tag , tag_pos , isCursorInTag = self.getTagNameAtCursor() _,xpath_idx, xpath_uid = self.__findXPath_rec('/cpacs', '/cpacs' , tag, tag_pos) if not isCursorInTag: xpath_idx = self.__strRemoveReverseToChar(xpath_idx, '/') xpath_uid = self.__strRemoveReverseToChar(xpath_uid, '/') self.__setCursorToPostion(start_pos) self.__startXPathPopUp(xpath_idx, xpath_uid) def getTagNameAtCursor(self): ''' @return: name of tag , position of tag , cursor is btw open and closing tag ''' self.editor.find('<', QTextDocument.FindBackward) isClosingTag , fst_tag = self.__getTagName() pos = self.editor.textCursor().position() if isClosingTag : # find open tag of this closing tag self.editor.find('<'+fst_tag, QTextDocument.FindBackward) pos = self.editor.textCursor().position() return fst_tag , pos , False else: return fst_tag , pos , True def __getTagName(self): tc = self.editor.textCursor() tc.select(QTextCursor.WordUnderCursor) tx = tc.selectedText() isClosingTag = False if "</" in tx : # select next word tc.select(QTextCursor.WordUnderCursor) tx = tc.selectedText() isClosingTag = True return isClosingTag , "" if "<" in tx else tx def __findXPath_rec(self, xpath_idx, xpath_uid, search, pos): nodes = self.__getChildNodesIdxTuple(xpath_idx) for (node, idx) in nodes: if node != '#text' : new_xpath_idx, new_xpath_uid = self.__createNewXPath(xpath_idx, xpath_uid, node, idx) if search == node and self.isNodeAtSearchedTagPosition(new_xpath_uid, pos) : print ("gefunden" , new_xpath_idx) return True, new_xpath_idx , new_xpath_uid else: flag , res_idx, res_uid = self.__findXPath_rec(new_xpath_idx, new_xpath_uid, search, pos) if flag : return True, res_idx, res_uid return False , xpath_idx , xpath_uid def __getChildNodesIdxTuple(self, xpath): n = self.tixi.getNumberOfChilds(xpath) + 1 node_list = list(map(lambda i : self.tixi.getChildNodeName(xpath, i), range(1,n))) res = [] for j in range(len(node_list)) : cnt = 1 for k in range(j): if node_list[k] == node_list[j] : cnt = cnt + 1 res.append((node_list[j],cnt)) return res def __createNewXPath(self, xpath_idx, xpath_uid, node, idx): path_idx = xpath_idx + '/' + node path_uid = xpath_uid + '/' + node try : uID = self.tixi.getTextAttribute(path_idx + '[' + str(idx) + ']', 'uID') path_idx = path_idx + '[' + str(idx) + ']' path_uid = path_uid+'[@uID="' + uID + '"]' except TixiException: pass # e.error == 'ATTRIBUTE_NOT_FOUND return path_idx , path_uid def isNodeAtSearchedTagPosition(self, xpath, pos): ''' @param xpath: xpath with uids (doesn't work with indices) @param param: ''' self.editor.moveCursor(QTextCursor.Start) # split string at / and remove all empty strings l = list(filter(lambda x : x != '' , xpath.split('/'))) # search index snd loop j = 0 # search backwards for uid for i in range(len(l)-1, -1, -1) : if '[' in l[i] : # get value in brackets : [x] --> x uid = re.search(r'\[@(.*)\]', l[i]).group(1) self.editor.find(uid) j = i+1 break # search forward for all nodes after last uid while j < len(l) : self.editor.find('<'+l[j]) j += 1 return pos <= self.editor.textCursor().position() def __setCursorToPostion(self, pos): tc = self.editor.textCursor() tc.setPosition(pos) self.editor.setTextCursor(tc) def __startXPathPopUp(self, xpath_idx, xpath_uid): self.popUpWidget = XPathDialog(xpath_idx, xpath_uid) self.setEnabled(False) self.popUpWidget.closeAct.triggered.connect(self.__resetPopUpWidget) self.popUpWidget.show() def updateLineNumber(self): ''' sets the line and column number ''' self.lineNumber = self.editor.textCursor().blockNumber() + 1 self.colNumber = self.editor.textCursor().columnNumber() + 1 self.m_statusRight.setText("row: " + str(self.lineNumber) + ", col:" + str(self.colNumber)) def highlightCurrentLine(self) : ''' highlight line under cursor ''' extraSelections = [] selection = QTextEdit.ExtraSelection() lineColor = QColor(255, 250, 205) selection.format.setBackground(lineColor) selection.format.setProperty(QTextFormat.FullWidthSelection, True) selection.cursor = self.editor.textCursor() selection.cursor.clearSelection() extraSelections.append(selection) self.editor.setExtraSelections(extraSelections) self.editor.setFocus() #TODO: implemnt def fireUpdate(self): print ('dummy function - update the model') text_file = open(Config.path_cpacs_tmp_file, "w") text_file.write(self.editor.toPlainText()) text_file.close() #self.tixi.saveDocument(Config.path_cpacs_tmp_file) # '../cpacs_files/temp.xml' def fireRevert(self): ''' reloads cpacs file if not updated yet ''' if(self.cur_file_path and self.cur_schema_path) : self.loadFile(self.cur_file_path, self.cur_schema_path) else : QMessageBox.about(self, "error", "CPACS-File or Validation-Schema not available") def fireSwitchLayout(self): ''' function to show or hide line numbers ''' if(self.flag_layout) : self.number_bar.flag_show_numbers = True self.update() else : self.number_bar.flag_show_numbers = False self.update() self.flag_layout = not self.flag_layout def fireNewAction(self): ''' opens new file input form ''' self.setEnabled(False) self.popUpWidget = NewFileDialog() self.popUpWidget.buttonBox.accepted.connect(self.__createNewCpacsFile) self.popUpWidget.buttonBox.rejected.connect(self.__resetPopUpWidget) self.popUpWidget.closeAct.triggered.connect(self.__resetPopUpWidget) self.popUpWidget.show() def fireToolX(self): self.popUpWidget = ToolX("X-Tool", self.tixi) self.setEnabled(False) self.popUpWidget.buttonBox.accepted.connect(self.__resetPopUpWidget) self.popUpWidget.buttonBox.rejected.connect(self.__resetPopUpWidget) # closeAct for pressing X to close window self.popUpWidget.closeAct.triggered.connect(self.__resetPopUpWidget) self.popUpWidget.show() def __createNewCpacsFile(self): ''' closes all documents and creates new empty cpacs temporary file ''' idict = self.popUpWidget.fire_submitInput() self.tixi.closeAllDocuments() self.tixi.create('cpacs') self.tixi.addCpacsHeader(idict['name'], idict['creator'], idict['version'], idict['description'], idict['cpacsVersion']) self.tixi.saveDocument(Config.path_cpacs_tmp_file) self.loadFile(Config.path_cpacs_tmp_file) self.__resetPopUpWidget() def __resetPopUpWidget(self): self.popUpWidget.close() self.popUpWidget = None self.setEnabled(True) def fireComment(self): ''' inserts open respective closing tag before and after a selected text. ''' tc = self.editor.textCursor() tc.beginEditBlock() tc.setPosition(self.editor.textCursor().selectionStart()) tc.insertText("<!--") tc.setPosition(self.editor.textCursor().selectionEnd()) tc.insertText("-->") tc.endEditBlock() def fireUnComment(self): ''' removes open respective closing tag before and after a selected text. ''' tc = self.editor.textCursor() selectTxt = tc.selectedText() if selectTxt.find('<!--') != -1 : if selectTxt.rfind('-->') != -1 : selectTxt = selectTxt.replace('<!--', '', 1) selectTxt = self.__rreplace(selectTxt, '-->' , '', 1) tc.insertText(selectTxt) else: QMessageBox.about(self, "error", "no open tag (%s) in selection" % ('-->')) else: QMessageBox.about(self, "error", "no close tag (%s) in selection" % ('<!--')) def fireSearchView(self): ''' show and hide searchbox and buttons ''' if self.searchbox.isFocused() : self.searchbox.hide() self.button1.hide() self.button2.hide() self.label1.hide() self.fontsizeSpinBox.hide() else : self.searchbox.show() self.button1.show() self.button2.show() self.label1.show() self.fontsizeSpinBox.show() self.searchbox.setFocus() def keyPressEvent(self,event): ''' handle for searching strings by pressing enter key ''' if self.searchbox.isFocused() and event.key() == Qt.Key_Return : self.fire_search_foreward() # ====================================================================================================================== # utilities # ====================================================================================================================== def __strRemoveReverseToChar(self, s, c): return self.__rm_rec(s, c) def __rm_rec(self, s, c): if s == "" : return "" elif s[-1] == c : return s[:-1] else : return self.__rm_rec(s[:-1], c) def __rreplace(self, s, old, new, occurrence): ''' reverse string replace function @param s: source string @param old: char to be replaced @param new: new char @param occurrence: only the given count occurrences are replaced. ''' li = s.rsplit(old, occurrence) return new.join(li)
class ScriptSetVal(QMainWindow): def __init__(self, tabID, subWinHandle, parent=None): super(ScriptSetVal, self).__init__(parent) self.tabID = tabID self.subWinHandle = subWinHandle self.tableHandle = subWinHandle.widget().centralWidget() self.initUI() self.initToolBar() self.initDocker() def initUI(self): self.t = QTextEdit() self.initFont() self.setCentralWidget(self.t) self.setGeometry(QRect(200, 200, 410, 610)) self.setAttribute(Qt.WA_DeleteOnClose) self.show() def initToolBar(self): self.scriptbar = QToolBar('plot options') self.addToolBar(Qt.BottomToolBarArea, self.scriptbar) scriptAction = QAction('set script', self) self.scriptbar.addAction(scriptAction) scriptAction.triggered.connect(self.RelectRng) def initFont(self): self.tabStop = 4 self.font = QFont('Courier') self.metrics = QFontMetrics(self.font) self.t.setTabStopWidth(self.tabStop * self.metrics.width(' ')) self.font.setStyleHint(QFont.Monospace) self.font.setFixedPitch(True) self.font.setPointSize(12) self.p = self.t.palette() self.p.setColor(QPalette.Base, QColor(0, 0, 0)) self.p.setColor(QPalette.Text, QColor(255, 255, 255)) self.t.setPalette(self.p) self.t.setFont(self.font) self.highlighter = Highlighter(self.t.document()) def initDocker(self): self.elog = QTextEdit() self.elogDockWidget = QDockWidget(" :: error log ::", self) self.elogDockWidget.setFeatures(QDockWidget.DockWidgetMovable) self.elogDockWidget.setAllowedAreas(Qt.TopDockWidgetArea and Qt.BottomDockWidgetArea) self.addDockWidget(Qt.BottomDockWidgetArea, self.elogDockWidget) self.elogDockWidget.setWidget(self.elog) self.p = self.elog.palette() self.p.setColor(QPalette.Base, QColor(0, 0, 0)) self.p.setColor(QPalette.Text, QColor(255, 0, 0)) self.elog.setPalette(self.p) self.elog.setReadOnly(True) def RelectRng(self): try: self.selectAry = [] if len(self.tableHandle.selectedRanges()) != 0: for i in range(len(self.tableHandle.selectedRanges())): self.leftCol = self.tableHandle.selectedRanges( )[i].leftColumn() self.colCount = self.tableHandle.selectedRanges( )[i].columnCount() for currentCol in range(self.leftCol, self.leftCol + self.colCount): self.selectAry.append(currentCol) self.leftCol = self.tableHandle.selectedRanges()[0].leftColumn( ) self.colCount = self.tableHandle.selectedRanges( )[0].columnCount() self.topRow = self.tableHandle.selectedRanges()[0].topRow() self.rowCount = self.tableHandle.selectedRanges()[0].rowCount() rows = [] cols = [] for i in range(self.topRow, self.topRow + self.rowCount, 1): rows.append(i) for i in range(self.leftCol, self.leftCol + self.colCount, 1): cols.append(i) try: exec(self.t.toPlainText()) except Exception, e: self.elog.moveCursor(QTextCursor.End) self.elog.textCursor().insertHtml( '<span style="color:#FF0000">Error: ' + str(e) + '</span><br>') print str(e) else:
class LandmarkLocationWidget(QWidget): # Signals activated = Signal(int, bool) deleted = Signal(int) def __init__(self): super(LandmarkLocationWidget, self).__init__() self._active = False self._font = QFont() self._font.setPointSize(10) self.indexLabel = QLabel() self.indexLabel.setMaximumWidth(10) self.indexLabel.setMinimumWidth(10) self.doneButton = QPushButton("Done") self.doneButton.setMaximumWidth(50) self.doneButton.setFont(self._font) self.doneButton.clicked.connect(self.doneButtonClicked) self.deleteButton = QPushButton("X") self.deleteButton.setMaximumWidth(15) self.deleteButton.setMinimumWidth(15) self.deleteButton.setMaximumHeight(15) self.deleteButton.setMinimumHeight(15) self.deleteButton.setFont(self._font) self.deleteButton.setVisible(False) self.deleteButton.clicked.connect(self.deleteButtonClicked) self.fixedButton = SpecialButton() self.fixedButton.setFont(self._font) self.movingButton = SpecialButton() self.movingButton.setFont(self._font) layout = QGridLayout() layout.setContentsMargins(0, 0, 0, 0) layout.setVerticalSpacing(0) layout.addWidget(self.deleteButton, 0, 0) layout.addWidget(self.indexLabel, 0, 1) layout.addWidget(self.fixedButton, 0, 2) layout.addWidget(self.movingButton, 0, 3) layout.addWidget(self.doneButton, 0, 4) self.setLayout(layout) self._updateState() def setIndex(self, index): self.index = index self.indexLabel.setText(str(index+1)) @property def active(self): return self._active @active.setter def active(self, value): self._active = value self._updateState() def setLandmarkSet(self, points): self.setFixedLandmark(points[0]) self.setMovingLandmark(points[1]) def setFixedLandmark(self, landmark): if not landmark: return labelX = "%2.0f" % landmark[0] labelY = "%2.0f" % landmark[1] labelZ = "%2.0f" % landmark[2] self.fixedButton.setText(labelX + ", " + labelY + ", " + labelZ) def setMovingLandmark(self, landmark): if not landmark: return labelX = "%2.0f" % landmark[0] labelY = "%2.0f" % landmark[1] labelZ = "%2.0f" % landmark[2] self.movingButton.setText(labelX + ", " + labelY + ", " + labelZ) @Slot() def doneButtonClicked(self): self._active = not self._active self.activated.emit(self.index, self._active) self._updateState() @Slot() def deleteButtonClicked(self): self.deleted.emit(self.index) def _updateState(self): text = "Done" if self._active else "Edit" self.doneButton.setText(text) self.deleteButton.setVisible(self._active) self.indexLabel.setVisible(not self._active) self.fixedButton.setEnabled(self._active) self.movingButton.setEnabled(self._active)
class Panel(QWidget): characterSelected = Signal(str) fontResized = Signal(float) def __init__(self, parent=None): super().__init__(parent) self.displayFont = QFont() self.displayFont.setStyleStrategy(QFont.PreferDefault) self.updateFont(self.displayFont.family()) self.currentChar = "" self.setMouseTracking(True) self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding) def updateFont(self, family): self.displayFont.setFamily(family) self.updateSize(self.displayFont.pointSize()) def updateSize(self, size): size = int(size) self.displayFont.setPointSize(size) self.squareSize = max(SQUARE_SIZE, QFontMetrics(self.displayFont).xHeight() * 3) self.fontResized.emit(self.squareSize) self.adjustSize() self.update() def minimumWidth(self): return COLUMNS * self.squareSize def sizeHint(self): return QSize(self.minimumWidth(), (MAX_CHAR / COLUMNS) * self.squareSize) def mousePressEvent(self, event): if event.button() == Qt.LeftButton: self.currentChar = chr((event.y() // self.squareSize) * COLUMNS + event.x() // self.squareSize) if not unicodedata.category(self.currentChar).startswith("C"): self.characterSelected.emit(self.currentChar) self.update() else: super().mousePressEvent(event) def mouseMoveEvent(self, event): pos = self.mapFromGlobal(event.globalPos()) code = ((pos.y() // self.squareSize) * COLUMNS + pos.x() // self.squareSize) name = "unnamed" try: name = unicodedata.name(chr(code)).capitalize() except ValueError: pass text = """<p><span style="font-size: 18pt;">{0:c}</span></p> <p><span style="font-size: 13pt;">U+{0:04X}<br>{1}</span></p>""".format( code, name) QToolTip.showText(event.globalPos(), text, self) def paintEvent(self, event): painter = QPainter(self) painter.fillRect(event.rect(), Qt.white) painter.setFont(self.displayFont) redrawRect = event.rect() beginRow = redrawRect.top() // self.squareSize endRow = redrawRect.bottom() // self.squareSize beginColumn = redrawRect.left() // self.squareSize endColumn = redrawRect.right() // self.squareSize painter.setPen(Qt.gray) for row in range(beginRow, endRow + 1): for column in range(beginColumn, endColumn + 1): painter.drawRect(column * self.squareSize, row * self.squareSize, self.squareSize, self.squareSize) fontMetrics = QFontMetrics(self.displayFont) painter.setPen(Qt.black) for row in range(beginRow, endRow + 1): for column in range(beginColumn, endColumn + 1): char = chr(row * COLUMNS + column) painter.setClipRect(column * self.squareSize, row * self.squareSize, self.squareSize, self.squareSize) if char == self.currentChar: painter.fillRect(column * self.squareSize + 1, row * self.squareSize + 1, self.squareSize, self.squareSize, Qt.green) painter.drawText( column * self.squareSize + (self.squareSize / 2) - fontMetrics.width(char) / 2, row * self.squareSize + 4 + fontMetrics.ascent(), char)
def __init__(self, parent=None): super(Truss, self).__init__(parent) self.resize(800, 600) self.filename = None self.filetuple = None self.dirty = False # Refers to Data Page only. centralwidget = QWidget(self) gridLayout = QGridLayout(centralwidget) self.tabWidget = QTabWidget(centralwidget) self.tab = QWidget() font = QFont() font.setFamily("Courier 10 Pitch") font.setPointSize(12) self.tab.setFont(font) gridLayout_3 = QGridLayout(self.tab) self.plainTextEdit = QPlainTextEdit(self.tab) gridLayout_3.addWidget(self.plainTextEdit, 0, 0, 1, 1) self.tabWidget.addTab(self.tab, "") self.tab_2 = QWidget() self.tab_2.setFont(font) gridLayout_2 = QGridLayout(self.tab_2) self.plainTextEdit_2 = QPlainTextEdit(self.tab_2) gridLayout_2.addWidget(self.plainTextEdit_2, 0, 0, 1, 1) self.tabWidget.addTab(self.tab_2, "") gridLayout.addWidget(self.tabWidget, 0, 0, 1, 1) self.setCentralWidget(centralwidget) menubar = QMenuBar(self) menubar.setGeometry(QRect(0, 0, 800, 29)) menu_File = QMenu(menubar) self.menu_Solve = QMenu(menubar) self.menu_Help = QMenu(menubar) self.setMenuBar(menubar) self.statusbar = QStatusBar(self) self.setStatusBar(self.statusbar) self.action_New = QAction(self) self.actionSave_As = QAction(self) self.action_Save = QAction(self) self.action_Open = QAction(self) self.action_Quit = QAction(self) self.action_About = QAction(self) self.actionShow_CCPL = QAction(self) self.action_Solve = QAction(self) self.action_CCPL = QAction(self) self.action_Help = QAction(self) menu_File.addAction(self.action_New) menu_File.addAction(self.action_Open) menu_File.addAction(self.actionSave_As) menu_File.addAction(self.action_Save) menu_File.addSeparator() menu_File.addAction(self.action_Quit) self.menu_Solve.addAction(self.action_Solve) self.menu_Help.addAction(self.action_About) self.menu_Help.addAction(self.action_CCPL) self.menu_Help.addAction(self.action_Help) menubar.addAction(menu_File.menuAction()) menubar.addAction(self.menu_Solve.menuAction()) menubar.addAction(self.menu_Help.menuAction()) self.setWindowTitle("Main Window") self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab),\ "Data Page") self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2),\ "Solution Page") menu_File.setTitle("&File") self.menu_Solve.setTitle("&Solve") self.menu_Help.setTitle("&Help") self.tabWidget.setCurrentIndex(0) self.action_New.setText("&New") self.action_Open.setText("&Open") self.actionSave_As.setText("Save &As") self.action_Save.setText("&Save") self.action_Quit.setText("&Quit") self.action_Solve.setText("&Solve") self.action_About.setText("&About") self.action_CCPL.setText("&CCPL") self.action_Help.setText("&Help") self.action_Quit.triggered.connect(self.close) allToolBar = self.addToolBar("AllToolBar") allToolBar.setObjectName("AllToolBar") self.addActions(allToolBar, (self.action_Open, self.actionSave_As,\ self.action_Save, self.action_Solve,\ self.action_Quit )) self.action_New.triggered.connect(self.fileNew) self.action_Open.triggered.connect(self.fileOpen) self.actionSave_As.triggered.connect(self.fileSaveAs) self.action_Save.triggered.connect(self.fileSave) self.action_Solve.triggered.connect(self.trussSolve) self.action_About.triggered.connect(self.aboutBox) self.action_CCPL.triggered.connect(self.displayCCPL) self.action_Help.triggered.connect(self.help) self.plainTextEdit.textChanged.connect(self.setDirty) self.action_New = self.editAction(self.action_New, None,\ 'ctrl+N', 'filenew', 'New File.') self.action_Open = self.editAction(self.action_Open, None, 'ctrl+O', 'fileopen', 'Open File.') self.actionSave_As = self.editAction(self.actionSave_As,\ None, 'ctrl+A', 'filesaveas',\ 'Save and Name File.') self.action_Save = self.editAction(self.action_Save, None, 'ctrl+S', 'filesave', 'Save File.') self.action_Solve = self.editAction(self.action_Solve, None, 'ctrl+L', 'solve', 'Solve Structure.') self.action_About = self.editAction(self.action_About, None, 'ctrl+B', 'about', 'Pop About Box.') self.action_CCPL = self.editAction(self.action_CCPL, None, 'ctrl+G', 'licence', 'Show Licence') self.action_Help = self.editAction(self.action_Help, None, 'ctrl+H', 'help', 'Show Help Page.') self.action_Quit = self.editAction(self.action_Quit, None, 'ctrl+Q', 'quit', 'Quit the program.') self.plainTextEdit_2.setReadOnly(True)
class LevelCompletionView(QFrame): """ View of the Level Completion Status """ def __init__(self, level, width, height, parent=None): """ Initialize the Level Completion View """ QFrame.__init__(self, parent) self.level = level self.setup() self.updateView() self.color = QColor(200, 200, 200) self.setStyleSheet("QFrame { background-color: %s }" % self.color.name()) self.resize(width, height) def setup(self): """ Setup the View """ self.setupFont() self.setupLevelCompletionLabel() self.setupCompletionDetailsLabel() def setupFont(self): """ Setup the Font """ self.font = QFont() self.font.setPointSize(32) def setupLevelCompletionLabel(self): """ Setup the Power Label """ self.font = QFont() self.font.setPointSize(32) self.levelCompletionLabel = QLabel("You Won!", self) self.levelCompletionLabel.move(32, 16) self.levelCompletionLabel.setFont(self.font) self.levelCompletionLabel.setVisible(False) def setupCompletionDetailsLabel(self): """ Setup the Remaining Mines Label """ self.font = QFont() self.font.setPointSize(24) self.completionDetailsLabel = QLabel("Destroyed!", self) self.completionDetailsLabel.move(32, 64) self.completionDetailsLabel.setFont(self.font) self.completionDetailsLabel.setVisible(False) def updateView(self): """ Update the View """ self.updateLevelCompletionLabel() self.updateCompletionDetailsLabel() def updateLevelCompletionLabel(self): """ Update the Power Label """ if self.level.won(): self.levelCompletionLabel.setText("You Won!") self.levelCompletionLabel.setVisible(True) elif self.level.lost(): self.levelCompletionLabel.setText("Game Over!") self.levelCompletionLabel.setVisible(True) def updateCompletionDetailsLabel(self): """ Update the Remaining Mines Label """ if self.level.destroyed(): self.completionDetailsLabel.setText("Destroyed") self.completionDetailsLabel.setVisible(True) elif self.level.noPower() and not self.level.won(): self.completionDetailsLabel.setText("Insufficient Power") self.completionDetailsLabel.setVisible(True) elif self.level.won(): text = "" if self.level.completionRating.awarded: text += "C" if self.level.moveRating.awarded: text += "M" if self.level.powerRating.awarded: text += "P" self.completionDetailsLabel.setText(text) self.completionDetailsLabel.setVisible(True)
from sys import argv, exit from PySide.QtGui import QApplication, QFont, QFontMetrics, QX11Info from mainwindow import MainWindow app = QApplication(argv) font = QFont(QApplication.font()) font.setPointSize(9) QApplication.setFont(font) w = MainWindow() metrics = QFontMetrics(font) w.resize(metrics.width('M') * 80, metrics.height() * 24) w.show() exit(app.exec_())
class GameStatusView(QFrame): """ It's the game status view """ def __init__(self, level, width, height, parent=None): """ """ QFrame.__init__(self, parent) self.level = level self.setup() self.updateView() self.color = QColor(200, 200, 200) self.setStyleSheet("QFrame { background-color: %s }" % self.color.name()) self.resize(width, height) def setup(self): """ Setup the View """ self.setupFont() self.setupPowerLabel() self.setupMovesLabel() self.setupRemainingDefensesLabels() def setupFont(self): """ Setup the Font """ self.font = QFont() self.font.setPointSize(14) def setupPowerLabel(self): """ Setup the Power Label """ self.powerLabel = QLabel("", self) self.powerLabel.move(32, 16) self.powerLabel.setFont(self.font) def setupMovesLabel(self): """ Setup the Moves Label """ self.movesLabel = QLabel("", self) self.movesLabel.move(32, 16+48) self.movesLabel.setFont(self.font) def setupRemainingDefensesLabels(self): """ Setup the Remaining Defenses Labels """ self.remainingDefensesLabels = {} labelNumber = 1 remainingDefenses = self.level.getRemainingDefenses() for defenseClass in remainingDefenses: label = QLabel("", self) label.move(32, 16+48*(labelNumber+1)) label.setFont(self.font) self.remainingDefensesLabels[defenseClass] = label labelNumber += 1 def updateView(self): """ Update the View """ self.updatePowerLabel() self.updateMovesLabel() self.updateRemainingDefensesLabels() def updatePowerLabel(self): """ Update the Power Label """ self.powerLabel.setText("Power: {0}".format(self.level.drone.powerRating.power)) def updateMovesLabel(self): """ Update the Moves Label """ self.movesLabel.setText("Moves: {0}".format(self.level.moveRating.moveCount)) self.movesLabel.resize(self.movesLabel.contentsRect().width(), self.movesLabel.contentsRect().height()) def updateRemainingDefensesLabels(self): """ Update the Remaining Mines Label """ remainingDefenses = self.level.getRemainingDefenses() for defenseClass in remainingDefenses: label = self.remainingDefensesLabels[defenseClass] label.setText("{0} Left: {1}".format(defenseClass.friendlyName, remainingDefenses[defenseClass]))