def __init__(self, parent=None, command="/bin/bash", font_name="Monospace", font_size=14): super(TerminalWidget, self).__init__(parent) self._columns = 80 self._rows = 24 self._char_width = [0] * (self._columns + 1) self._char_height = [0] * (self._rows + 1) # self.parent().setTabOrder(self, self) self.setFocusPolicy(Qt.StrongFocus) self.setAutoFillBackground(False) self.setAttribute(Qt.WA_OpaquePaintEvent, True) self.setCursor(Qt.IBeamCursor) font = QFont(font_name) font.setStyleHint(QFont.TypeWriter) font.setPixelSize(font_size) self.setFont(font) self._session = None self._last_update = 0 self._screen = [] self._text = [] self._cursor_rect = None self._cursor_col = 0 self._cursor_row = 0 self._dirty = False self._blink = False self._press_pos = None self._selection = None self._clipboard = QApplication.clipboard() self._pixmap = None
def font(self, text_style): device_font = text_style.fontfacename in LIBERATION_FONT_MAP try: if device_font: face = self.font_map[text_style.fontfacename] else: face = self.face_map[text_style.fontfacename] except KeyError: # Bad fontfacename field in LRF face = self.font_map['Dutch801 Rm BT Roman'] sz = text_style.fontsize wt = text_style.fontweight style = text_style.fontstyle font = ( face, wt, style, sz, ) if font in self.cache: rfont = self.cache[font] else: italic = font[2] == QFont.StyleItalic rfont = QFont(font[0], font[3], font[1], italic) rfont.setPixelSize(font[3]) rfont.setBold(wt >= 69) self.cache[font] = rfont qfont = rfont if text_style.emplinetype != 'none': qfont = QFont(rfont) qfont.setOverline(text_style.emplineposition == 'before') qfont.setUnderline(text_style.emplineposition == 'after') return qfont
def __init__(self,parent, font_name, font_size, cols, rows, colorscheme): super().__init__(parent) self.callback_scrollbar= None # # determine font metrics and terminal window size in pixel # font= QFont(font_name) font.setPixelSize(font_size) metrics= QFontMetrics(font) font_width=metrics.width("A") font_height=metrics.height() width= font_width*cols height= int(font_height* rows) # # create terminal window and scrollbar # self.hbox= QHBoxLayout() self.terminalwidget= QTerminalWidget(self,font_name,font_size,font_height, width,height, colorscheme) self.hbox.addWidget(self.terminalwidget) self.hbox.setAlignment(self.terminalwidget,Qt.AlignLeft) self.scrollbar= QScrollBar() self.hbox.addWidget(self.scrollbar) self.hbox.setAlignment(self.scrollbar,Qt.AlignLeft) self.setLayout(self.hbox) # # initialize scrollbar # self.scrollbar.valueChanged.connect(self.do_scrollbar) self.scrollbar.setEnabled(False)
def __init__(self, parent=None, command="/bin/bash", font_name="Monospace", font_size=18): super(TerminalWidget, self).__init__(parent) if self.parent() is not None: self.parent().setTabOrder(self, self) self.setFocusPolicy(Qt.WheelFocus) self.setAutoFillBackground(False) self.setAttribute(Qt.WA_OpaquePaintEvent, True) self.setCursor(Qt.IBeamCursor) font = QFont(font_name) font.setPixelSize(font_size) self.setFont(font) self._session = None self._last_update = None self._screen = [] self._text = [] self._cursor_rect = None self._cursor_col = 0 self._cursor_row = 0 self._dirty = False self._blink = False self._press_pos = None self._selection = None self._clipboard = QApplication.clipboard() QApplication.instance().lastWindowClosed.connect(Session.close_all) if command: self.execute()
def initUi(self): self.setWindowTitle('BLABLABLA') self.setMouseTracking(True) # self.setGeometry(50, 50, 1024, 768) # self.setMaximumSize(1024, 768) # self.setMinimumSize(800, 600) self.setLayout(self.hbox) self.hbox.addStretch(1) self.hbox.addLayout(self.vbox) self.hbox.addStretch(1) self.hbox.addWidget(self.grid) self.grid.show() self.vbox.addStretch(1) font = QFont() font.setBold(True) font.setPixelSize(30 * variables.SCALE) label = QLabel("PUNTAJE") label.setFont(font) label.setAlignment(Qt.AlignCenter) self.vbox.addWidget(label) font2 = QFont() font2.setPixelSize(30 * variables.SCALE) self.label_puntaje.setFont(font2) self.label_puntaje.setAlignment(Qt.AlignCenter) self.vbox.addWidget(self.label_puntaje) self.vbox.addWidget(self.button) self.vbox.addWidget(self.orientation) self.orientation.setAlignment(Qt.AlignCenter) self.orientation.setPixmap(self.__clockwise_pm) self.vbox.addStretch(1) self.button.clicked.connect(self.invertirPressed) self.grid.initUI()
def __init__(self, parent=None, command="/bin/bash", font_name="Monospace", font_size=18): super(TerminalWidget, self).__init__(parent) # self.parent().setTabOrder(self, self) self.setFocusPolicy(Qt.WheelFocus) self.setAutoFillBackground(False) self.setAttribute(Qt.WA_OpaquePaintEvent, True) self.setCursor(Qt.IBeamCursor) font = QFont(font_name) font.setPixelSize(font_size) self.setFont(font) self._session = None self._last_update = None self._screen = [] self._text = [] self._cursor_rect = None self._cursor_col = 0 self._cursor_row = 0 self._dirty = False self._blink = False self._press_pos = None self._selection = None self._clipboard = QApplication.clipboard() QApplication.instance().lastWindowClosed.connect(Session.close_all) if command: self.execute()
def drawMarkings(self, painter): painter.save() painter.translate(self.width() / 2, self.height() / 2) scale = min((self.width() - self._margins) / 120.0, (self.height() - self._margins) / 120.0) painter.scale(scale, scale) font = QFont(self.font()) font.setPixelSize(10) metrics = QFontMetricsF(font) painter.setFont(font) painter.setPen(self.palette().color(QPalette.Shadow)) i = 0 while i < 360: if i % 45 == 0: painter.drawLine(0, -40, 0, -50) painter.drawText(-metrics.width(self._pointText[i]) / 2.0, -52, self._pointText[i]) else: painter.drawLine(0, -45, 0, -50) painter.rotate(15) i += 15 painter.restore()
def __init__(self, imshape, xc, yc, width, height, threshold=1, counts=1000, ID=0, autothresh=False): super().__init__() self.x = xc self.y = yc self.w = width self.h = height self.t = threshold self.c = np.zeros(counts) self.i = 0 # number of images processed self.id = ID self.label = pg.TextItem('ROI'+str(ID), pg.intColor(ID), anchor=(0,1)) font = QFont() font.setPixelSize(16) self.label.setFont(font) self.label.setPos(xc+width//2, yc+height//2) # in bottom left corner self.roi = pg.ROI((xc-width//2, yc-height//2), (width,height), movable=True, translateSnap=True, ) self.roi.setPen(pg.intColor(ID), width=3) # box outlining the ROI self.edits = OrderedDict(zip(['x','y','w','h'], # display ROI values [QLineEdit(str(val), self) for val in [xc, yc, width, height]])) self.threshedit = QLineEdit(str(threshold), self) for i, edit in enumerate(list(self.edits.values()) + [self.threshedit]): edit.setValidator(int_validator if i < 2 else nat_validator) edit.textEdited[str].connect(self.set_vals) # only triggered by user, not setText self.autothresh = QCheckBox(self) # toggle whether to auto update threshold self.autothresh.setChecked(autothresh) self.create_rect_mask(imshape) # the values of the image included in ROI self.mask_type = 'rect' # what type of mask is being used self.ps = np.zeros(4) # parameters for gauss mask self.d = 3 # number of pixels around centre point to use for gauss mask
def paint(self, p, option, widget): x, y = 0, 0 qfont = QFont("Courier") current_pixel = 0 blackPen = QPen(QColor("black")) for letter in self.seq: if x >= current_pixel: if self.draw_text and self.poswidth >= 5: br = QBrush(QColor(self.bg.get(letter, "white"))) p.setPen(blackPen) p.fillRect(x, 0, self.poswidth, self.posheight, br) qfont.setPixelSize(min(self.posheight, self.poswidth)) p.setFont(qfont) p.setBrush(QBrush(QColor("black"))) p.drawText(x, 0, self.poswidth, self.posheight, Qt.AlignCenter | Qt.AlignVCenter, letter) elif letter == "-" or letter == ".": p.setPen(blackPen) p.drawLine(x, self.posheight / 2, x + self.poswidth, self.posheight / 2) else: br = QBrush(QColor(self.bg.get(letter, "white"))) p.fillRect(x, 0, max(1, self.poswidth), self.posheight, br) # p.setPen(QPen(QColor(self.bg.get(letter, "black")))) # p.drawLine(x, 0, x, self.posheight) current_pixel = int(x) x += self.poswidth
def __init__(self,parent, font_name, font_size, font_height, w,h, colorscheme): super().__init__(parent) self.setFocusPolicy(Qt.WheelFocus) self.setAutoFillBackground(False) self.setAttribute(Qt.WA_OpaquePaintEvent, True) self.setCursor(Qt.IBeamCursor) font = QFont(font_name) font.setPixelSize(font_size) self.setFont(font) self._screen = [] self._text = [] self._transform= QTransform() self._cursor_col = 0 self._cursor_row = 0 self._dirty = False self._kbdfunc= None self._w=w self._h=h self._alt_sequence= False self._alt_seq_length=0 self._alt_seq_value=0 self._cursortype= CURSOR_OFF self._color_scheme=self.color_schemes[self.color_scheme_names[colorscheme]] self._cursor_color=self._color_scheme[2] self._cursor_char= 0x20 self._cursor_attr=-1 self._cursor_update=True self._blink= True self._blink_counter=0 self._cursor_rect = QRect(0, 0, self._char_width, self._char_height) self._cursor_polygon=QPolygon([QPoint(0,0+(self._char_height/2)), QPoint(0+(self._char_width*0.8),0+self._char_height), QPoint(0+(self._char_width*0.8),0+(self._char_height*0.67)), QPoint(0+self._char_width,0+(self._char_height*0.67)), QPoint(0+self._char_width,0+(self._char_height*0.33)), QPoint(0+(self._char_width*0.8),0+(self._char_height*0.33)), QPoint(0+(self._char_width*0.8),0), QPoint(0,0+(self._char_height/2))])
def __init__(self, pixmap): super(SplashScreen, self).__init__(pixmap) self._title = QLabel(self) self._title.setGeometry(50 * self.width() / 100, 20 * self.height() / 100, 50 * self.width() / 100, 11 * self.height() / 100) self._title.setStyleSheet('QLabel { color : rgb(191,180,110); }') font = QFont('Exo 2') font.setPixelSize(36) font.setBold(True) font.setItalic(True) self._title.setFont(font) font = QFont('Exo 2') font.setPixelSize(16) font.setBold(False) font.setItalic(True) self.setFont(font) self.progressBar = QProgressBar(self) self.progressBar.setGeometry(self.width() / 10, 8 * self.height() / 10, 8 * self.width() / 10, self.height() / 30)
def splash_screen(): """ """ pm = QPixmap( pkg_resources.resource_filename( __name__, "icons/orange-splash-screen.png") ) version = QCoreApplication.applicationVersion() size = 21 if len(version) < 5 else 16 font = QFont("Helvetica") font.setPixelSize(size) font.setBold(True) font.setItalic(True) font.setLetterSpacing(QFont.AbsoluteSpacing, 2) metrics = QFontMetrics(font) br = metrics.boundingRect(version).adjusted(-5, 0, 5, 0) br.moveCenter(QPoint(436, 224)) p = QPainter(pm) p.setRenderHint(QPainter.Antialiasing) p.setRenderHint(QPainter.TextAntialiasing) p.setFont(font) p.setPen(QColor("#231F20")) p.drawText(br, Qt.AlignCenter, version) p.end() return pm, QRect(88, 193, 200, 20)
def font(self, text_style): device_font = text_style.fontfacename in LIBERATION_FONT_MAP try: if device_font: face = self.font_map[text_style.fontfacename] else: face = self.face_map[text_style.fontfacename] except KeyError: # Bad fontfacename field in LRF face = self.font_map['Dutch801 Rm BT Roman'] sz = text_style.fontsize wt = text_style.fontweight style = text_style.fontstyle font = (face, wt, style, sz,) if font in self.cache: rfont = self.cache[font] else: italic = font[2] == QFont.StyleItalic rfont = QFont(font[0], font[3], font[1], italic) rfont.setPixelSize(font[3]) rfont.setBold(wt>=69) self.cache[font] = rfont qfont = rfont if text_style.emplinetype != 'none': qfont = QFont(rfont) qfont.setOverline(text_style.emplineposition == 'before') qfont.setUnderline(text_style.emplineposition == 'after') return qfont
def update_font(basefont, weight=None, italic=None, underline=None, pixelSize=None, pointSize=None): """ Return a copy of `basefont` :class:`QFont` with updated properties. """ font = QFont(basefont) if weight is not None: font.setWeight(weight) if italic is not None: font.setItalic(italic) if underline is not None: font.setUnderline(underline) if pixelSize is not None: font.setPixelSize(pixelSize) if pointSize is not None: font.setPointSize(pointSize) return font
def initUi(self): self.setWindowTitle('BLABLABLA') self.setMouseTracking(True) # self.setGeometry(50, 50, 1024, 768) # self.setMaximumSize(1024, 768) # self.setMinimumSize(800, 600) self.setLayout(self.hbox) self.hbox.addStretch(1) self.hbox.addLayout(self.vbox) self.hbox.addStretch(1) self.hbox.addWidget(self.grid) self.grid.show() self.vbox.addStretch(1) font = QFont() font.setBold(True) font.setPixelSize(30*variables.SCALE) label = QLabel("PUNTAJE") label.setFont(font) label.setAlignment(Qt.AlignCenter) self.vbox.addWidget(label) font2 = QFont() font2.setPixelSize(30*variables.SCALE) self.label_puntaje.setFont(font2) self.label_puntaje.setAlignment(Qt.AlignCenter) self.vbox.addWidget(self.label_puntaje) self.vbox.addWidget(self.button) self.vbox.addWidget(self.orientation) self.orientation.setAlignment(Qt.AlignCenter) self.orientation.setPixmap(self.__clockwise_pm) self.vbox.addStretch(1) self.button.clicked.connect(self.invertirPressed) self.grid.initUI()
def __init__(self, parent=None, command="/bin/bash", font_name="Monospace", font_size=14): super(TerminalWidget, self).__init__(parent) self._columns = 80 self._rows = 24 self._char_width = [0]*(self._columns+1) self._char_height = [0]*(self._rows+1) # self.parent().setTabOrder(self, self) self.setFocusPolicy(Qt.StrongFocus) self.setAutoFillBackground(False) self.setAttribute(Qt.WA_OpaquePaintEvent, True) self.setCursor(Qt.IBeamCursor) font = QFont(font_name) font.setStyleHint(QFont.TypeWriter) font.setPixelSize(font_size) self.setFont(font) self._session = None self._last_update = 0 self._screen = [] self._text = [] self._cursor_rect = None self._cursor_col = 0 self._cursor_row = 0 self._dirty = False self._blink = False self._press_pos = None self._selection = None self._clipboard = QApplication.clipboard() self._pixmap = None
def drawAxisLegend(self, x_label, y_label): """ Draw Axis Legend """ font =QFont("Typewriter") #RT axis legend font.setPixelSize(12) self.renderText(self.corner_, -self.corner_-20.0, 0., x_label)# font self.renderText(-self.corner_-20.0, self.corner_, 0., y_label, font)
def add_main_layout(self): self.scatterplot_item = None self.plot_item = None self.x_label = 'x' self.y_label = 'y' box = gui.vBox(self.controlArea, "Variables") self.x_var_model = itemmodels.VariableListModel() self.comboBoxAttributesX = gui.comboBox( box, self, value='x_var_index', label="Input ", orientation=Qt.Horizontal, callback=self.apply, contentsLength=12) self.comboBoxAttributesX.setSizePolicy( QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) self.comboBoxAttributesX.setModel(self.x_var_model) gui.doubleSpin( gui.indentedBox(box), self, "polynomialexpansion", 0, 10, label="Polynomial expansion:", callback=self.apply) gui.separator(box, height=8) self.y_var_model = itemmodels.VariableListModel() self.comboBoxAttributesY = gui.comboBox( box, self, value='y_var_index', label='Target', orientation=Qt.Horizontal, callback=self.apply, contentsLength=12) self.comboBoxAttributesY.setSizePolicy( QSizePolicy.MinimumExpanding, QSizePolicy.Fixed) self.comboBoxAttributesY.setModel(self.y_var_model) gui.rubber(self.controlArea) # main area GUI self.plotview = pg.PlotWidget(background="w") self.plot = self.plotview.getPlotItem() axis_color = self.palette().color(QPalette.Text) axis_pen = QPen(axis_color) tickfont = QFont(self.font()) tickfont.setPixelSize(max(int(tickfont.pixelSize() * 2 // 3), 11)) axis = self.plot.getAxis("bottom") axis.setLabel(self.x_label) axis.setPen(axis_pen) axis.setTickFont(tickfont) axis = self.plot.getAxis("left") axis.setLabel(self.y_label) axis.setPen(axis_pen) axis.setTickFont(tickfont) self.plot.setRange(xRange=(0.0, 1.0), yRange=(0.0, 1.0), disableAutoRange=True) self.mainArea.layout().addWidget(self.plotview)
def drawAxisLegend(self, x_label, y_label): """ Draw Axis Legend """ font = QFont("Typewriter") #RT axis legend font.setPixelSize(12) self.renderText(self.corner_, -self.corner_ - 20.0, 0., x_label) # font self.renderText(-self.corner_ - 20.0, self.corner_, 0., y_label, font)
def __init__(self, piece_type, number=5, parent=None): super().__init__(piece_type, parent) self._number = number self._number_label = QLabel(self) self._number_label.setText(str(self._number)) self._number_label.move(40, 38) font = QFont() font.setBold(True) font.setPixelSize(30) self._number_label.setFont(font) self._number_label.setStyleSheet("color: white;") self._number_label.show()
def __init__(self): QPushButton.__init__(self) self.setText('R') font = QFont() font.setPixelSize(8) self.setFont(font) self.setFixedSize(18, 18) self.range_from = None self.range_to = None self.range_step = None self.values = [] self._active = False
class offsetItem(QGraphicsTextItem): def __init__(self, whex): QGraphicsTextItem.__init__(self) self.initValues(whex) # self.initShape() self.initPosition() self.initFont() def initPosition(self): self.setPos(0, 25) def initValues(self, whex): self.whex = whex self.bdiff = self.whex.bdiff #Buffer self.buffer = [] self.bufferLines = 0 #Line self.currentLine = 0 #Offset self.startOffset = 0 self.fontPixel = 14 def initFont(self): self.setDefaultTextColor(QColor(Qt.red)) self.font = QFont("Gothic") self.font.setFixedPitch(1) self.font.setBold(False) self.font.setPixelSize(self.fontPixel) self.setFont(self.font) #Print Operations def printFullOffset(self, start, len): count = 0 fullBuff = QString() while count <= len: if self.bdiff.opt_offsetBase == 1: fullBuff.append("%.10d" % start) elif self.bdiff.opt_offsetBase == 0: fullBuff.append("%.10X" % start) fullBuff.append("\n") start += 16 count += 1 #Clear and set cursor = self.textCursor() cursor.movePosition(QTextCursor.Start) cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor) self.setPlainText(fullBuff) cursor.movePosition(QTextCursor.Start)
class offsetItem(QGraphicsTextItem): def __init__(self, whex): QGraphicsTextItem.__init__(self) self.initValues(whex) # self.initShape() self.initPosition() self.initFont() def initPosition(self): self.setPos(0, 25) def initValues(self, whex): self.whex = whex self.heditor = self.whex.heditor #Buffer self.buffer = [] self.bufferLines = 0 #Line self.currentLine = 0 #Offset self.startOffset = 0 self.fontPixel = 14 def initFont(self): self.setDefaultTextColor(QColor(Qt.red)) self.font = QFont("Gothic") self.font.setFixedPitch(1) self.font.setBold(False) self.font.setPixelSize(self.fontPixel) self.setFont(self.font) #Print Operations def printFullOffset(self, start, len): count = 0 fullBuff = QString() while count <= len: if self.heditor.decimalview: fullBuff.append("%.10d" % start) else: fullBuff.append("%.10X" % start) fullBuff.append("\n") start += 16 count += 1 #Clear and set cursor = self.textCursor() cursor.movePosition(QTextCursor.Start) cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor) self.setPlainText(fullBuff) cursor.movePosition(QTextCursor.Start)
def __init__(self): QPushButton.__init__(self) self.setText('R') font = QFont() font.setPixelSize(8) self.setFont(font) self.setFixedSize(18, 18) self.range_type = None self.range_from = None self.range_to = None self.range_step = None self.values = [] self._active = False
def setup_ui(self): self.resize(500, 500) self.out = QLabel(self) self.out.setMinimumHeight(100) font = QFont() font.setPixelSize(80) self.out.setFont(font) self.grid = QGridLayout(self) self.display = StrokeWidget() self.letter_selector = QComboBox() self.grid.addWidget(self.display, 0, 0, 1, 1) self.grid.addWidget(self.letter_selector, 1, 0, 1, 1) self.grid.addWidget(self.out, 2, 0, 1, 1)
def font_from_dict(font_dict, font=None): if font is None: font = QFont() else: font = QFont(font) if "family" in font_dict: font.setFamily(font_dict["family"]) if "size" in font_dict: font.setPixelSize(font_dict["size"]) return font
def __init__(self, parent=None, command="/bin/bash", font_name="Monospace", font_size=18): super(TerminalWidget, self).__init__(parent) self.setFocusPolicy(Qt.WheelFocus) self.setAutoFillBackground(False) self.setAttribute(Qt.WA_OpaquePaintEvent, True) self.setCursor(Qt.IBeamCursor) font = QFont(font_name) font.setPixelSize(font_size) self.setFont(font) self._session = None self._draw_screen = self.Screen(self) self.setupPainters() self.execute()
def drawText(self, p, innerRect, innerRadius, value): if not self.m_format: return f = QFont(self.font()) f.setPixelSize(10) fm = QFontMetricsF(f) maxWidth = fm.width(self.valueToText(self.m_max)) delta = innerRadius / maxWidth fontSize = f.pixelSize() * delta * 0.75 f.setPixelSize(int(fontSize)) p.setFont(f) textRect = QRectF(innerRect) p.setPen(self.palette().text().color()) p.drawText(textRect, Qt.AlignCenter, self.valueToText(value))
def getFont(self, font_family, font_size=10, bold=False, italic=False, Underline=False): font = QFont() font.setFamily(_fromUtf8(font_family)) font.setPixelSize(font_size) font.setFixedPitch(True) font.setBold(bold) font.setItalic(italic) font.setUnderline(Underline) return font
class DiceWidget(QPushButton): def __init__(self, dice, parent=None): super(DiceWidget, self).__init__(parent) self.dice = dice # dimensions policy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) policy.setHeightForWidth(True) self.setSizePolicy(policy) self.resize(70, 70) # text and font self.font = QFont() self.font.setBold(True) self.font.setPixelSize(self.height() * 0.4) # set behavior self.setToolTip("Game Dice") QObject.connect(self, SIGNAL("clicked()"), self.dice_click) # default color/text self.setText("{0}\nAll".format(self.dice.num())) self.setStyleSheet("background-color: rgb(135, 5, 45);") self.show() def resize_font(self): """Resize font with button size""" self.font.setPixelSize(self.height() * 0.4) self.setFont(self.font) def sizeHint(self): return QSize(75, 75) def resizeEvent(self, event): """resize event for font... might need to account for other factors on resize""" self.resize_font() def dice_click(self): self.resize_font() self.dice.roll() if self.dice.is_all(): self.setStyleSheet("background-color: rgb(135, 5, 45);") self.setText("{0}\nAll".format(self.dice.num())) else: self.setStyleSheet("background-color: rgb(5, 135, 10);") self.setText("{0}".format(self.dice.num()))
def initLogo(self, layout): font_label = QFont() font_label.setBold(True) font_info = QFont() font_info.setItalic(True) font_info.setPixelSize(12) lisa_logo = QLabel() logopath = find_logo() logo = QPixmap(logopath) logo = logo.scaled(130, 130) lisa_logo.setPixmap(logo) # scaledToWidth(128)) lisa_logo.mousePressEvent = lambda event: self.changeWidget('Main') layout.addWidget(lisa_logo) return layout
def populate(self, phrase, ts, process_space=True): phrase_pos = 0 processed = False matches = self.__class__.whitespace.finditer(phrase) font = QFont(ts.font) if self.valign is not None: font.setPixelSize(font.pixelSize() / 1.5) fm = QFontMetrics(font) single_space_width = fm.width(' ') height, descent = fm.height(), fm.descent() for match in matches: processed = True left, right = match.span() if not process_space: right = left space_width = single_space_width * (right - left) word = phrase[phrase_pos:left] width = fm.width(word) if self.current_width + width < self.line_length: self.commit(word, width, height, descent, ts, font) if space_width > 0 and self.current_width + space_width < self.line_length: self.add_space(space_width) phrase_pos = right continue # Word doesn't fit on line if self.hyphenate and len(word) > 3: tokens = hyphenate_word(word) for i in range(len(tokens) - 2, -1, -1): word = ''.join(tokens[0:i + 1]) + '-' width = fm.width(word) if self.current_width + width < self.line_length: self.commit(word, width, height, descent, ts, font) return phrase_pos + len(word) - 1, True if self.current_width < 5: # Force hyphenation as word is longer than line for i in range(len(word) - 5, 0, -5): part = word[:i] + '-' width = fm.width(part) if self.current_width + width < self.line_length: self.commit(part, width, height, descent, ts, font) return phrase_pos + len(part) - 1, True # Failed to add word. return phrase_pos, True if not processed: return self.populate(phrase + ' ', ts, False) return phrase_pos, False
def populate(self, phrase, ts, process_space=True): phrase_pos = 0 processed = False matches = self.__class__.whitespace.finditer(phrase) font = QFont(ts.font) if self.valign is not None: font.setPixelSize(font.pixelSize()/1.5) fm = QFontMetrics(font) single_space_width = fm.width(' ') height, descent = fm.height(), fm.descent() for match in matches: processed = True left, right = match.span() if not process_space: right = left space_width = single_space_width * (right-left) word = phrase[phrase_pos:left] width = fm.width(word) if self.current_width + width < self.line_length: self.commit(word, width, height, descent, ts, font) if space_width > 0 and self.current_width + space_width < self.line_length: self.add_space(space_width) phrase_pos = right continue # Word doesn't fit on line if self.hyphenate and len(word) > 3: tokens = hyphenate_word(word) for i in range(len(tokens)-2, -1, -1): word = ''.join(tokens[0:i+1])+'-' width = fm.width(word) if self.current_width + width < self.line_length: self.commit(word, width, height, descent, ts, font) return phrase_pos + len(word)-1, True if self.current_width < 5: # Force hyphenation as word is longer than line for i in range(len(word)-5, 0, -5): part = word[:i] + '-' width = fm.width(part) if self.current_width + width < self.line_length: self.commit(part, width, height, descent, ts, font) return phrase_pos + len(part)-1, True # Failed to add word. return phrase_pos, True if not processed: return self.populate(phrase+' ', ts, False) return phrase_pos, False
def __init__(self, parent): super(QLabel, self).__init__(parent) font = QFont("monospace") font.setPixelSize(27) self.setFont(font) self.qtcb_set_char.connect(self.set_char_slot) self.setText(" ") self.setFixedSize(23, 45) self.setAutoFillBackground(True) palette = self.palette() palette.setColor(self.backgroundRole(), Qt.blue) palette.setColor(self.foregroundRole(), Qt.white) self.setPalette(palette)
def createAxisLabelPixmap(self): pixmap = QPixmap(250, 250) pixmap.fill(self.backgroundColor) painter = QPainter() painter.begin(pixmap) font = QFont() font.setBold(True) font.setPixelSize(250 - 30) path = QPainterPath() path.addText(QPointF(50, 250 - 50), font, self.axis) brush = QBrush(self.foregroundColor) painter.setBrush(brush) painter.drawPath(path) painter.setFont(font) painter.end() pixmap = pixmap.scaled(QSize(self.labelsWidth, self.labelsheight), Qt.KeepAspectRatio, Qt.SmoothTransformation) return pixmap
def adjust_UI(self): """Edit the widgets created by main_window""" # self.hist_canvas.setTitle("Histogram of CCD counts") self.setWindowTitle(self.name + ' - Re-Image Analyser - ') # change font size font = QFont() font.setPixelSize(14) #### edit histogram tab: display all image handlers #### hist_grid = self.tabs.widget(1).layout() hist_grid.removeWidget(self.hist_canvas) self.hist_canvas.setTitle("Recapture") self.hist1 = pg.PlotWidget() self.hist1.setTitle("Before") self.hist2 = pg.PlotWidget() self.hist2.setTitle("After") for hist in [self.hist1, self.hist2]: hist.getAxis('bottom').tickFont = font hist.getAxis('left').tickFont = font hist_grid.addWidget(self.hist1, 1, 0, 3, 8) hist_grid.addWidget(self.hist2, 4, 0, 3, 8) hist_grid.addWidget(self.hist_canvas, 7, 0, 3, 8) #### edit stats tab: display all histogram statistics #### stat_grid = self.tabs.widget(2).layout() for i, text in enumerate( ['Histogram: ', 'Recapture', 'Before', 'After']): label = QLabel(text, self) stat_grid.addWidget(label, 1 + len(self.histo_handler.stats.keys()), i, 1, 1) self.hist1_stats = {} # dictionary of stat labels for hist1 self.hist2_stats = {} # dictionary of stat labels for hist2 # get the statistics from the histogram handler for i, labels in enumerate([self.hist1_stats, self.hist2_stats]): for j, label_text in enumerate(self.histo_handler.stats.keys()): labels[label_text] = QLabel('', self) # value stat_grid.addWidget(labels[label_text], 1 + j, 2 + i, 1, 1) # take the threshold from the second image handler self.thresh_toggle.setChecked(True)
def create_font_array(self, char_height=62, pixel_margin=1, font_family='Courier', font_weight=50): # Load font and get the dimensions of one character (assuming monospaced font) f = QFont(font_family) f.setPixelSize(char_height) f.setWeight(font_weight) fm = QFontMetrics(f, QImage()) char_width = char_height = 0 char_y = 999 for i in range(32, 127): bb = fm.boundingRect(chr(i)) char_width = max(char_width, bb.width()) char_height = max(char_height, bb.height()) char_y = min(char_y, bb.y()) imgsize = (char_width + 2 * pixel_margin, char_height + 2 * pixel_margin) self.char_ar = float(imgsize[1]) / imgsize[0] # init the image and the painter that will draw the characters to each image img = QImage(imgsize[0], imgsize[1], QImage.Format_ARGB32) ptr = c_void_p(int(img.constBits())) painter = QPainter(img) painter.setFont(f) painter.setPen(QColor(255, 255, 255, 255)) # Set-up the texture array self.tex_id = gl.glGenTextures(1) gl.glBindTexture(gl.GL_TEXTURE_2D_ARRAY, self.tex_id) gl.glTexImage3D(gl.GL_TEXTURE_2D_ARRAY, 0, gl.GL_RGBA8, imgsize[0], imgsize[1], 127 - 32, 0, gl.GL_BGRA, gl.GL_UNSIGNED_BYTE, None) gl.glTexParameteri(gl.GL_TEXTURE_2D_ARRAY, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR) gl.glTexParameteri(gl.GL_TEXTURE_2D_ARRAY, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR) gl.glTexParameterf(gl.GL_TEXTURE_2D_ARRAY, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_BORDER) gl.glTexParameterf(gl.GL_TEXTURE_2D_ARRAY, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_BORDER) # We're using the ASCII range 32-126; space, uppercase, lower case, numbers, brackets, punctuation marks for i in range(32, 127): img.fill(0) painter.drawText(pixel_margin, pixel_margin - char_y, chr(i)) gl.glTexSubImage3D(gl.GL_TEXTURE_2D_ARRAY, 0, 0, 0, i - 32, imgsize[0], imgsize[1], 1, gl.GL_BGRA, gl.GL_UNSIGNED_BYTE, ptr) # We're done, close the painter, and return the texture ID, char width and char height painter.end()
def _get_pos_widget(name, backgroundColor, foregroundColor): label = QLabel() label.setAttribute(Qt.WA_TransparentForMouseEvents, True) pixmap = QPixmap(25*10, 25*10) pixmap.fill(backgroundColor) painter = QPainter() painter.begin(pixmap) pen = QPen(foregroundColor) painter.setPen(pen) painter.setRenderHint(QPainter.Antialiasing) font = QFont() font.setBold(True) font.setPixelSize(25*10-30) path = QPainterPath() path.addText(QPointF(50, 25*10-50), font, name) brush = QBrush(foregroundColor) painter.setBrush(brush) painter.drawPath(path) painter.setFont(font) painter.end() pixmap = pixmap.scaled(QSize(20,20), Qt.KeepAspectRatio, Qt.SmoothTransformation) label.setPixmap(pixmap) spinbox = QSpinBox() spinbox.setAttribute(Qt.WA_TransparentForMouseEvents, True) spinbox.setEnabled(False) spinbox.setAlignment(Qt.AlignCenter) spinbox.setToolTip("{0} Spin Box".format(name)) spinbox.setButtonSymbols(QAbstractSpinBox.NoButtons) spinbox.setMaximumHeight(20) spinbox.setMaximum(9999) font = spinbox.font() font.setPixelSize(14) spinbox.setFont(font) sheet = TEMPLATE.format(foregroundColor.name(), backgroundColor.name()) spinbox.setStyleSheet(sheet) return label, spinbox
def __init__(self): buxpaper.Window.__init__(self) start_time = QDateTime.currentDateTime().time() self.displayTime = (start_time.hour(), start_time.minute()) self.timer = QTimer(self) self.timer.timeout.connect(self.updateTime) self.timer.setInterval(5000) self.timer.start() self.foreground = QPen(self.palette().foreground().color()) self.background = self.palette().background() font = QFont(QApplication.font()) desktop = QApplication.desktop() geometry = desktop.screenGeometry() font.setPixelSize(min(geometry.width() / 8, geometry.height() / 4)) self.setFont(font) self.maxHeight = QFontMetrics(font).height()
def __init__(self, parent=None): """Constructor.""" super(JRodosGraphWidget, self).__init__(parent) # Set up the user interface from Designer. # After setupUI you can access any designer object by doing # self.<objectname>, and you can use autoconnect slots - see # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html # #widgets-and-dialogs-with-auto-connect self.setupUi(self) # RD: hopefully fix exit errors from pyqtgraph pg.setConfigOptions(exitCleanup=False) x_axis = DateAxis(orientation='bottom', pen='333333') y_axis = pg.AxisItem(orientation='left', pen='333333') font = QFont() font.setPixelSize(10) x_axis.tickFont = font y_axis.tickFont = font # Switch to using white background and black foreground pg.setConfigOption('background', 'ffffff') pg.setConfigOption('foreground', '000000') pw = pg.PlotWidget(axisItems={'bottom': x_axis, 'left': y_axis}, enableMenu=False, title=unicode("y: "+u"\u03BC"+"Sv/h - x: time")) pw.show() self.graph = pw # ROI = Region Of Interest r = pg.PolyLineROI([(0, 0), (10, 10)]) pw.addItem(r) self.setWidget(pw)
def drawAxisLegend(self): """Draw Axis Legend""" font = QFont("Typewriter") font.setPixelSize(10) #RT axis legend font.setPixelSize(12) self.qglColor(Qt.blue) mz_label = "retention time [s]";rt_label = "m/z" self.renderText(0.0, -self.corner-20.0, -self.near-2*self.corner+20.0, rt_label, font) self.renderText(-self.corner-20.0, -self.corner-20.0, -self.near-3*self.corner, mz_label, font) self.renderText(-self.corner-20.0, self.corner+10.0, -self.near-2*self.corner+20.0, "intensity %", font) font.setPixelSize(10)
def drawAxisLegend(self): """Draw Axis Legend""" font = QFont("Typewriter") font.setPixelSize(10) #RT axis legend font.setPixelSize(12) self.qglColor(Qt.blue) mz_label = "retention time [s]" rt_label = "m/z" self.renderText(0.0, -self.corner - 20.0, -self.near - 2 * self.corner + 20.0, rt_label, font) self.renderText(-self.corner - 20.0, -self.corner - 20.0, -self.near - 3 * self.corner, mz_label, font) self.renderText(-self.corner - 20.0, self.corner + 10.0, -self.near - 2 * self.corner + 20.0, "intensity %", font) font.setPixelSize(10)
def drawContents(self, painter): """ @type painter: QPainter """ w = self.width() h = self.height() margin = 10 background = QColor(210, 211, 215) text_color = QColor(0, 0, 0) foreground = QColor(255, 255, 255) painter.setBrush(background) painter.fillRect(0, 0, w, h, background) pen = QPen() pen.setWidth(2) pen.setColor(foreground) painter.setPen(pen) painter.drawRect(0, 0, w - 1, h - 1) image_width = self.splash_image.width() image_height = self.splash_image.height() aspect = float(image_width) / float(image_height) scaled_height = h - 2 * margin scaled_width = scaled_height * aspect painter.drawRect(margin, margin, scaled_width, scaled_height) painter.drawPixmap(margin, margin, scaled_width, scaled_height, self.splash_image) text_x = scaled_width + 2 * margin top_offset = margin text_area_width = w - scaled_width - 2 * margin painter.setPen(text_color) text_size = 150 font = QFont("Serif") font.setStyleHint(QFont.Serif) font.setPixelSize(text_size) painter.setFont(font) painter.drawText(text_x, margin + top_offset, text_area_width, text_size, Qt.AlignHCenter | Qt.AlignCenter, self.ert) top_offset += text_size + 2 * margin text_size = 25 font.setPixelSize(text_size) painter.setFont(font) painter.drawText(text_x, top_offset, text_area_width, text_size, Qt.AlignHCenter | Qt.AlignCenter, self.ert_title) top_offset += text_size + 4 * margin text_size = 20 font.setPixelSize(text_size) painter.setFont(font) painter.drawText(text_x, top_offset, text_area_width, text_size, Qt.AlignHCenter | Qt.AlignCenter, self.version) top_offset += text_size + margin text_size = 15 font.setPixelSize(text_size) painter.setFont(font) painter.drawText(text_x, top_offset, text_area_width, text_size, Qt.AlignHCenter | Qt.AlignCenter, self.timestamp) text_size = 12 font.setPixelSize(text_size) painter.setFont(font) painter.drawText(text_x, h - text_size - margin - 5, text_area_width, text_size + 5, Qt.AlignHCenter | Qt.AlignCenter, self.copyright)
def _initUI(self): window = QtGui.QWidget() self.window = window self.setCentralWidget(window) self.resize(800, 600) self.setWindowTitle('LISA') self.statusBar().showMessage('Ready') self.mainLayout = QHBoxLayout(window) window.setLayout(self.mainLayout) self.ui_widgets = {} self.ui_buttons = {} #### MENU #### self.initUIMenu() line = QFrame() line.setFrameShape(QFrame.VLine) self.mainLayout.addWidget(line) ##### BODY ##### bodyLayout = QVBoxLayout() self.bodyLayout = bodyLayout self.mainLayout.addLayout(bodyLayout) #--- title --- self.infoBody = QtGui.QWidget() infoBodyLayout = QVBoxLayout() bodyLayout.addWidget(self.infoBody) self.infoBody.setLayout(infoBodyLayout) self.ui_widgets["Main"] = self.infoBody font_label = QFont() font_label.setBold(True) font_info = QFont() font_info.setItalic(True) font_info.setPixelSize(12) lisa_title = QLabel('Liver Surgery Analyser') info = QLabel('Developed by:\n' + 'University of West Bohemia\n' + 'Faculty of Applied Sciences\n' + QString.fromUtf8('M. Jiřík, V. Lukeš - 2013') + '\n\nVersion: ' + self.oseg.version ) info.setFont(font_info) lisa_title.setFont(font_label) infoBodyLayout.addWidget(lisa_title) infoBodyLayout.addWidget(info) #--- segmentation option --- self.segBody = segmentationQt.SegmentationWidget(oseg=self.oseg) # self.segBody.oseg = self.oseg bodyLayout.addWidget(self.segBody) self.ui_widgets["Segmentation"] = self.segBody # self.segBody.lblSegData.setText(self.text_seg_data) self.segBody.btnVirtualResectionPV.clicked.connect(self.btnVirtualResectionPV) self.segBody.btnVirtualResectionPlanar.clicked.connect(self.btnVirtualResectionPlanar) self.segBody.btnVirtualResectionPV_testing.clicked.connect(self.btnVirtualResectionPV_new) ### self.segBody.btnSegManual.clicked.connect(self.btnManualSeg) self.segBody.btnSegSemiAuto.clicked.connect(self.btnSemiautoSeg) self.segBody.btnSegMask.clicked.connect(self.maskRegion) self.segBody.btnSegPV.clicked.connect(self.btnPortalVeinSegmentation) self.segBody.btnSegHV.clicked.connect(self.btnHepaticVeinsSegmentation) #--- edit slab --- self.slabBody = dictEditQt.DictEdit(dictionary=self.oseg) bodyLayout.addWidget(self.slabBody) self.ui_widgets["EditSlab"] = self.slabBody self.slabBody.btnSaveSlab.clicked.connect(self.segBody.reinitLabels) # -- load widget import io3d.datareaderqt self.read_widget = io3d.datareaderqt.DataReaderWidget( before_function=self._before_read_callback, after_function=self._after_read_callback ) self.read_widget.cache = self.oseg.cache bodyLayout.addWidget(self.read_widget) self.ui_widgets["Load"] = self.read_widget #--- file info (footer) --- bodyLayout.addStretch() self.oseg.gui_update = self.gui_update ##### OTHERS ##### self.mainLayout.addStretch() self.btnSave.setDisabled(True) self.btnSegmentation.setDisabled(True) self.btnCompare.setDisabled(True) self.changeWidget('Main') self.show()
class asciiItem(QGraphicsTextItem): def __init__(self, whex): QGraphicsTextItem.__init__(self) self.initValues(whex) self.initPosition() self.initFont() self.initMetricsValues() # self.initCursor() def initPosition(self): self.setPos(485, 25) # self.setTextInteractionFlags(Qt.TextSelectableByMouse) def initValues(self, whex): self.whex = whex self.bdiff = self.whex.bdiff #Buffer self.buffer = [] self.bufferLines = 0 #Line self.currentLine = 0 #Offset self.startOffset = 0 self.fontPixel = 14 #Current Positions self.currentPos = 0 # def initCursor(self): # self.cursor = asciiCursor(self) # self.bdiff.scene.addItem(self.cursor) def initFont(self): self.setDefaultTextColor(QColor(Qt.darkCyan)) self.font = QFont("Gothic") self.font.setFixedPitch(1) self.font.setBold(False) self.font.setPixelSize(self.fontPixel) self.setFont(self.font) self.sfont = QFont("Gothic") self.sfont.setFixedPitch(1) self.sfont.setBold(False) self.sfont.setPixelSize(self.fontPixel) self.metric = QFontMetrics(self.font) self.metric = QFontMetrics(self.font) def initMetricsValues(self): #Calibrate calibrate = QString("A") self.charsByByte = 1 self.charW = self.metric.width(calibrate) self.charH = self.metric.height() self.byteW = self.charW * self.charsByByte self.byteH = self.charH def initStartBlank(self): self.lineW = self.boundingRect().width() self.startBlank = self.lineW - (self.byteW * 16) # print "start ASCII blank" # print self.startBlank #Print Operations def printBuffer(self, buff): del self.buffer self.buffer = buff count = 0 printer = QString() for char in buff: if char > "\x20" and char < "\x7e": printer.append(char) else: printer.append(".") if count < 15: count += 1 else: printer.append("\n") count = 0 #Clear and set cursor = self.textCursor() cursor.movePosition(QTextCursor.Start) cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor) self.setPlainText(printer) cursor.movePosition(QTextCursor.Start) def colorizeDiff(self, diffinfos): cursor = self.textCursor() cursor.setPosition(QTextCursor.Start) text = self.toPlainText() keys = diffinfos.keys() keys.sort() for offset in keys: difflen = diffinfos[offset] pos = offset + (offset / 16) # count = offset / 16 # print "offset ", offset, " count ", count count = difflen + (((offset + difflen) / 16) - (offset / 16)) # count = difflen cursor.setPosition(pos, QTextCursor.MoveAnchor) # print "L", l, " len ", pos + difflen cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor, count) format = QTextCharFormat() format.setFont(self.sfont) format.setForeground(QBrush(QColor(Qt.red))) cursor.setCharFormat(format) cursor.setPosition(QTextCursor.Start, QTextCursor.MoveAnchor)
class hexItem(QGraphicsTextItem): def __init__(self, whex): QGraphicsTextItem.__init__(self) self.initValues(whex) self.initPosition() # self.initDocument() self.initFont() self.initMetricsValues() # self.initCursor() def initPosition(self): self.setPos(95, 25) def initValues(self, whex): self.whex = whex self.heditor = self.whex.heditor self.hexview = self.whex.view #Buffer self.buffer = [] self.fontPixel = 14 #Current Position self.bytesPerLine = self.heditor.bytesPerLine self.groupBytes = self.heditor.groupBytes #Selection self.select = False self.xsel = 0 self.ysel = 0 def initDocument(self): self.document = QTextDocument() self.setDocument(self.document) # def initSyntaxHighlighter(self): # self.search = self.heditor.right.search # self.highlighter = highlighter(self) # def initCursor(self): # self.cursor = hexCursor(self) # self.heditor.whex.view.scene.addItem(self.cursor) def initFont(self): self.setDefaultTextColor(QColor(Qt.black)) self.font = QFont("Gothic") self.font.setFixedPitch(1) self.font.setBold(False) self.font.setPixelSize(self.fontPixel) # self.setFont(self.font) self.setFont(self.font) #Search Highlight font self.sfont = QFont("Gothic") self.sfont.setFixedPitch(1) self.sfont.setBold(False) self.sfont.setPixelSize(self.fontPixel) self.metric = QFontMetrics(self.font) def initMetricsValues(self): #Calibrate calibrate = QString("A") self.charsByByte = 2 * self.groupBytes self.charW = self.metric.width(calibrate) self.charH = self.metric.height() self.byteW = self.charW * self.charsByByte self.byteH = self.charH def initStartBlank(self): self.lineW = self.boundingRect().width() self.startBlank = self.lineW - (self.byteW * self.bytesPerLine) - (self.charW * (self.bytesPerLine - 1)) # print "start blank" # print self.startBlank # def getPatternOffsets(self, buff): # plist = self.search.searchedPatterns # startoffset = self.heditor.currentOffset # offlist = {} # for pattern, offsetlist in plist.iteritems(): # for offset in offsetlist: # if offset >= startoffset and offset <= startoffset + self.heditor.readSize: # offlist[offset - self.heditor.currentOffset] = len(pattern) / 2 # return offlist #Print Operations def dumpHexBuffer(self, buff): self.printFullBuffer(buff) # searchofflist = self.getPatternOffsets(buff) # if len(searchofflist) > 0: # highoffsets = searchofflist.keys() # highoffsets.sort() # self.highlighter(searchofflist) def printFullBuffer(self, buff): del self.buffer pos = str(len(buff)) + 'B' self.buffer = struct.unpack(pos, buff) count = 0 fullBuff = QString() for byte in self.buffer: fullBuff.append("%.2x" % byte) if count < 15: fullBuff.append(" ") count += 1 else: fullBuff.append("\n") count = 0 cursor = self.textCursor() cursor.movePosition(QTextCursor.Start) cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor) self.setPlainText(fullBuff) cursor.movePosition(QTextCursor.Start) # if len(self.search.searchedPatterns) > 0: # self.highlighter.highlightBlock(self.document.toPlainText()) def getXPos(self, x): count = 0 current = self.byteW + (self.charW / 2) + (self.startBlank / 2) while current < x: count += 1 current = current + self.byteW + self.charW return count def getYPos(self, y): count = 0 current = self.byteH while current < y: count += 1 current = current + self.byteH return count def highlighter(self, searchofflist): offsets = searchofflist.keys() cursor = self.textCursor() cursor.setPosition(QTextCursor.Start) for offset in offsets: len = searchofflist[offset] pos = (offset * 2) + offset cursor.setPosition(pos, QTextCursor.MoveAnchor) l = 0 while l < len: cursor.movePosition(QTextCursor.NextWord, QTextCursor.KeepAnchor) l += 1 format = QTextCharFormat() format.setFont(self.sfont) format.setForeground(QBrush(QColor(Qt.red))) cursor.setCharFormat(format) cursor.setPosition(QTextCursor.Start, QTextCursor.MoveAnchor) ############## # # MOUSE EVENTS # ########################### ############## # def mouseMoveEvent(self, event): pos = event.pos() x = pos.x() y = pos.y() xpos = self.getXPos(x) ypos = self.getYPos(y) self.heditor.selection.select(self.heditor.selection.xstart, self.heditor.selection.ystart, xpos, ypos) self.heditor.infos.update() self.heditor.right.decode.update() def mousePressEvent(self, event): button = event.button() pos = event.pos() if event.button() == 1: #Get CLicked coordonates x = pos.x() y = pos.y() xpos = self.getXPos(x) ypos = self.getYPos(y) #refresh cursors self.whex.hexcursor.draw(xpos, ypos) self.whex.asciicursor.draw(xpos, ypos) self.heditor.selection.select(xpos, ypos, xpos, ypos, True) self.heditor.right.decode.update() self.heditor.infos.update() def mouseReleaseEvent(self, event): pass
def _initUI(self): cw = QWidget() self.setCentralWidget(cw) grid = QGridLayout() grid.setSpacing(10) self.uiw = {} # status bar self.statusBar().showMessage('Ready') # menubar self._initMenu() font_label = QFont() font_label.setBold(True) font_info = QFont() font_info.setItalic(True) font_info.setPixelSize(10) # # # # # # # # # LISA logo # font_title = QFont() # font_title.setBold(True) # font_title.setSize(24) lisa_title = QLabel('LIver Surgery Analyser') info = QLabel('Developed by:\n' + 'University of West Bohemia\n' + 'Faculty of Applied Sciences\n' + QString.fromUtf8('M. Jiřík, V. Lukeš - 2013') + '\n\nVersion: ' + self.oseg.version ) info.setFont(font_info) lisa_title.setFont(font_label) lisa_logo = QLabel() logopath = find_logo() logo = QPixmap(logopath) lisa_logo.setPixmap(logo) # scaledToWidth(128)) grid.addWidget(lisa_title, 0, 1) grid.addWidget(info, 1, 1) btn_config = QPushButton("Configuration", self) btn_config.clicked.connect(self.btnConfig) self.uiw['config'] = btn_config grid.addWidget(btn_config, 2, 1) btn_update = QPushButton("Update", self) btn_update.clicked.connect(self.btnUpdate) self.uiw['btn_update'] = btn_update grid.addWidget(btn_update, 3, 1) grid.addWidget(lisa_logo, 0, 2, 5, 2) # combo = QtGui.QComboBox(self) # for text in self.oseg.segmentation_alternative_params.keys(): # combo.addItem(text) # combo.activated[str].connect(self.onAlternativeSegmentationParams) # grid.addWidget(combo, 4, 1) # right from logo rstart = 0 btn_sync = QPushButton("Sync", self) btn_sync.clicked.connect(self.sync_lisa_data) self.uiw['sync'] = btn_sync grid.addWidget(btn_sync, rstart + 2, 4) grid.addWidget( self._add_button("Log", self.btnLog, 'Log', "See log file", QStyle.SP_FileDialogContentsView), rstart + 3, 4) # # dicom reader rstart = 5 hr = QFrame() hr.setFrameShape(QFrame.HLine) text_dcm = QLabel('DICOM reader') text_dcm.setFont(font_label) # btn_dcmdir = QPushButton("Load DICOM", self) # btn_dcmdir.clicked.connect(self.loadDataDir) # btn_dcmdir.setIcon(btn_dcmdir.style().standardIcon(QStyle.SP_DirOpenIcon)) # self.uiw['dcmdir'] = btn_dcmdir # btn_datafile = QPushButton("Load file", self) # btn_datafile.clicked.connect(self.loadDataFile) # btn_datafile.setToolTip("Load data from pkl file, 3D Dicom, tiff, ...") btn_dcmcrop = QPushButton("Crop", self) btn_dcmcrop.clicked.connect(self.cropDcm) # voxelsize gui comment # elf.scaling_mode = 'original' # ombo_vs = QComboBox(self) # ombo_vs.activated[str].connect(self.changeVoxelSize) # eys = scaling_modes.keys() # eys.sort() # ombo_vs.addItems(keys) # ombo_vs.setCurrentIndex(keys.index(self.scaling_mode)) # elf.text_vs = QLabel('Voxel size:') # end-- voxelsize gui self.text_dcm_dir = QLabel('DICOM dir:') self.text_dcm_data = QLabel('DICOM data:') grid.addWidget(hr, rstart + 0, 2, 1, 4) grid.addWidget(text_dcm, rstart + 0, 1, 1, 3) grid.addWidget( self._add_button("Load dir", self.loadDataDir, 'dcmdir', "Load data from directory (DICOM, png, jpg...)", QStyle.SP_DirOpenIcon), rstart + 1, 1) grid.addWidget( self._add_button("Load file", self.loadDataFile, 'load_file', "Load data from pkl file, 3D Dicom, tiff, ...", QStyle.SP_FileIcon), rstart + 1, 2) # grid.addWidget(btn_datafile, rstart + 1, 2) grid.addWidget(btn_dcmcrop, rstart + 1, 3) # voxelsize gui comment # grid.addWidget(self.text_vs, rstart + 3, 1) # grid.addWidget(combo_vs, rstart + 4, 1) grid.addWidget(self.text_dcm_dir, rstart + 6, 1, 1, 4) grid.addWidget(self.text_dcm_data, rstart + 7, 1, 1, 4) rstart += 9 # # # # # # # # # segmentation hr = QFrame() hr.setFrameShape(QFrame.HLine) text_seg = QLabel('Segmentation') text_seg.setFont(font_label) btn_segfile = QPushButton("Seg. from file", self) btn_segfile.clicked.connect(self.loadSegmentationFromFile) btn_segfile.setToolTip("Load segmentation from pkl file, raw, ...") btn_segcompare = QPushButton("Compare", self) btn_segcompare.clicked.connect(self.compareSegmentationWithFile) btn_segcompare.setToolTip( "Compare data with segmentation from pkl file, raw, ...") btn_mask = QPushButton("Mask region", self) btn_mask.clicked.connect(self.maskRegion) btn_segliver = QPushButton("Liver seg.", self) btn_segliver.clicked.connect(self.liverSeg) self.btn_segauto = QPushButton("Auto seg.", self) self.btn_segauto.clicked.connect(self.autoSeg) btn_segman = QPushButton("Viewer", self) btn_segman.clicked.connect(self.manualSeg) self.text_seg_data = QLabel('segmented data:') grid.addWidget(hr, rstart + 0, 2, 1, 4) grid.addWidget(text_seg, rstart + 0, 1) grid.addWidget(btn_segfile, rstart + 1, 1) grid.addWidget(btn_segcompare, rstart + 1, 3) grid.addWidget(btn_mask, rstart + 2, 1) grid.addWidget(btn_segliver, rstart + 2, 2) grid.addWidget(self.btn_segauto, rstart + 1, 2) grid.addWidget(btn_segman, rstart + 2, 3) grid.addWidget(self.text_seg_data, rstart + 3, 1, 1, 3) rstart += 4 # # # # # # # # # save/view # hr = QFrame() # hr.setFrameShape(QFrame.HLine) grid.addWidget( self._add_button( "Save", self.saveOut, 'save', "Save data with segmentation. Use filename 'slice{:04d}.tiff' to store slices", QStyle.SP_DialogSaveButton), rstart + 0, 1) # btn_segsave = QPushButton("Save", self) # btn_segsave.clicked.connect(self.saveOut) btn_segsavedcmoverlay = QPushButton("Save Dicom Overlay", self) btn_segsavedcmoverlay.clicked.connect(self.btnSaveOutDcmOverlay) btn_segsavedcm = QPushButton("Save Dicom", self) btn_segsavedcm.clicked.connect(self.btnSaveOutDcm) btn_segview = QPushButton("View3D", self) if viewer3D_available: btn_segview.clicked.connect(self.view3D) else: btn_segview.setEnabled(False) grid.addWidget(btn_segsavedcm, rstart + 0, 2) grid.addWidget(btn_segsavedcmoverlay, rstart + 0, 3) grid.addWidget(btn_segview, rstart + 0, 4) rstart += 1 # # # # Virtual resection hr = QFrame() hr.setFrameShape(QFrame.HLine) rstart += 1 hr = QFrame() hr.setFrameShape(QFrame.HLine) text_resection = QLabel('Virtual resection') text_resection.setFont(font_label) btn_pvseg = QPushButton("Portal vein seg.", self) btn_pvseg.clicked.connect(self.btnPortalVeinSegmentation) btn_svpv = QPushButton("Save PV tree", self) btn_svpv.clicked.connect(self.btnSavePortalVeinTree) btn_svpv.setToolTip("Save Portal Vein 1D model into vessel_tree.yaml") # btn_svpv.setEnabled(False) btn_svpv.setEnabled(True) btn_hvseg = QPushButton("Hepatic veins seg.", self) btn_hvseg.clicked.connect(self.btnHepaticVeinsSegmentation) btn_svhv = QPushButton("Save HV tree", self) btn_svhv.clicked.connect(self.btnSaveHepaticVeinsTree) btn_svhv.setToolTip( "Save Hepatic Veins 1D model into vessel_tree.yaml") btn_svhv.setEnabled(True) # btn_svhv.setEnabled(False) btn_lesions = QPushButton("Lesions localization", self) btn_lesions.clicked.connect(self.btnLesionLocalization) # btn_lesions.setEnabled(False) grid.addWidget( self._add_button("Resection (PV)", self.btnVirtualResectionPV, 'btn_resection_pv', "Portal Vein based virtual resection"), rstart + 2, 3) grid.addWidget( self._add_button("Resection (planar)", self.btnVirtualResectionPlanar, 'btn_resection_planar', "Plane based virtual resection"), rstart + 1, 3) # btn_resection_pv = QPushButton("Resection (PV)", self) # btn_resection_pv.clicked.connect(self.btnVirtualResectionPV) # btn_resection_planar = QPushButton("Resection (planar)", self) # btn_resection_planar.clicked.connect(self.btnVirtualResectionPV) grid.addWidget(hr, rstart + 0, 2, 1, 4) grid.addWidget(text_resection, rstart + 0, 1) grid.addWidget(btn_pvseg, rstart + 1, 1) grid.addWidget(btn_hvseg, rstart + 1, 2) # grid.addWidget(btn_resection_planar, rstart + 1, 3) # grid.addWidget(btn_resection_pv, rstart + 2, 3) grid.addWidget(btn_lesions, rstart + 1, 4) grid.addWidget(btn_svpv, rstart + 2, 1) grid.addWidget(btn_svhv, rstart + 2, 2) # # # # # # # hr = QFrame() hr.setFrameShape(QFrame.HLine) # rid.addWidget(hr, rstart + 0, 0, 1, 4) rstart += 3 # quit btn_quit = QPushButton("Quit", self) btn_quit.clicked.connect(self.quit) grid.addWidget(btn_quit, rstart + -1, 4, 1, 1) self.uiw['quit'] = btn_quit if self.oseg.debug_mode: btn_debug = QPushButton("Debug", self) btn_debug.clicked.connect(self.run_debug) grid.addWidget(btn_debug, rstart - 2, 4) cw.setLayout(grid) self.cw = cw self.grid = grid self.setWindowTitle('LISA') self.show()
class textItem(QTextEdit): def __init__(self, parent): QTextEdit.__init__(self) self.initValues(parent) self.initFont() # self.initColors() # self.initTab() def initTab(self): cursor = self.textCursor() # self.tableformat = QTextTableFormat() self.table = cursor.insertTable(1, 3) self.printOffset(0) # print self.table.rows() def initValues(self, parent): self.heditor = parent # Buffer self.buffer = [] self.bufferLines = 0 # Line self.currentLine = 0 # Offset self.startOffset = 0 self.row = {} self.line = [] # self.setAcceptsHoverEvents(True) self.document = QTextDocument() self.setDocument(self.document) self.cursor = self.textCursor() # self.setTextCursor(self.cursor) def initFont(self): # Font self.font = QFont("Courier") self.font.setFixedPitch(1) self.font.setBold(False) self.font.setPixelSize(14) self.setCurrentFont(self.font) # Cursor # Just after new read def formatBuffer(self, buff, offset): t = time.time() self.startOffset = offset del self.buffer pos = str(len(buff)) + "B" self.buffer = struct.unpack(pos, buff) self.bufferLines = len(self.buffer) / 16 # for index in block: # byte = "%.2x" % index # if count < 15: # byte += " " # count += 1 # else: # byte += "\n" # count = 0 # self.buffer.append(byte) print time.time() - t def printLine(self, line, offset): count = 0 start = line * 16 dline = self.buffer[start : start + 16] # Print Offset self.setTextColor(Qt.black) cell = self.table.cellAt(0, 1) cellCursor = cell.firstCursorPosition() cellCursor.insertText(" | ") for byte in dline: if count % 2 == 0: self.setTextColor(Qt.black) cellCursor.insertText("%.2x" % byte) else: self.setTextColor(Qt.blue) cellCursor.insertText("%.2x" % byte) cellCursor.insertText(" ") count += 1 # print count self.setTextColor(Qt.black) cellCursor.insertText("| ") # self.printAscii(dline) cellCursor.insertText("\n") # print self.buffer # self.setPlainText(self.buffer) # self.colorizeText() def printOffset(self, offset): self.setCurrentFont(self.font) self.setTextColor(Qt.red) cell = self.table.cellAt(0, 0) cellCursor = cell.firstCursorPosition() # cursor = self.table.cellAt(0, 0).firstCursorPosition() cellCursor.insertText("%.10d" % offset) def printAscii(self, line): for char in line: if str(char) in string.printable: self.insertPlainText(str(char)) else: self.insertPlainText(".") def printBuffer(self): t = time.time() # Clean text self.moveCursor(QTextCursor.Start) self.moveCursor(QTextCursor.End, QTextCursor.KeepAnchor) self.setCurrentFont(self.font) offset = self.startOffset # self.printOffset(offset) l = self.currentLine while l < self.bufferLines: self.printLine(l, offset) l += 1 offset += 16 print "E" self.moveCursor(QTextCursor.Start) print time.time() - t def initColors(self): # Blue Color self.blue = QBrush(QColor(Qt.blue)) self.blueFormat = QTextCharFormat() self.blueFormat.setFont(self.font) self.blueFormat.setForeground(self.blue) def colorizeText(self): self.size = self.buffer.size() cur = self.textCursor() pos = cur.position() # self.moveCursor(QTextCursor.Start) while pos < self.size: self.moveCursor(QTextCursor.NextWord) self.moveCursor(QTextCursor.EndOfWord, QTextCursor.KeepAnchor) cur = self.textCursor() # self.setTextColor(QColor(Qt.blue)) cur.setCharFormat(self.blueFormat) self.moveCursor(QTextCursor.NextWord) cur = self.textCursor() pos = cur.position() # print pos self.moveCursor(QTextCursor.Start)
def initUI(self): cw = QWidget() self.setCentralWidget(cw) grid = QGridLayout() grid.setSpacing(15) # status bar self.statusBar().showMessage('Ready') font_label = QFont() font_label.setBold(True) font_info = QFont() font_info.setItalic(True) font_info.setPixelSize(10) ############# lisa_title = QLabel('Organ Segmentation with Random Walker') info = QLabel('Developed by:\n' + 'University of West Bohemia\n' + 'Faculty of Applied Sciences\n' + QString.fromUtf8('M. Jirik, V. Lukes, T. Ryba - 2013') ) info.setFont(font_info) lisa_title.setFont(font_label) lisa_logo = QLabel() logopath = os.path.join(path_to_script, 'kky_small.png') logo = QPixmap(logopath) lisa_logo.setPixmap(logo) grid.addWidget(lisa_title, 0, 1) grid.addWidget(info, 1, 1) grid.addWidget(lisa_logo, 0, 2, 2, 1) grid.setColumnMinimumWidth(1, logo.width()) ### dicom reader rstart = 2 hr = QFrame() hr.setFrameShape(QFrame.HLine) text_dcm = QLabel('DICOM reader') text_dcm.setFont(font_label) btn_dcmdir = QPushButton("Load DICOM", self) btn_dcmdir.clicked.connect(self.loadDcmDir) btn_dcmcrop = QPushButton("Crop", self) btn_dcmcrop.clicked.connect(self.cropDcm) self.text_dcm_dir = QLabel('DICOM dir:') self.text_dcm_data = QLabel('DICOM data:') grid.addWidget(hr, rstart + 0, 0, 1, 4) grid.addWidget(text_dcm, rstart + 1, 1, 1, 2) grid.addWidget(btn_dcmdir, rstart + 2, 1) grid.addWidget(btn_dcmcrop, rstart + 2, 2) grid.addWidget(self.text_dcm_dir, rstart + 5, 1, 1, 2) grid.addWidget(self.text_dcm_data, rstart + 6, 1, 1, 2) rstart += 8 # ################ segmentation hr = QFrame() hr.setFrameShape(QFrame.HLine) text_seg = QLabel('Segmentation') text_seg.setFont(font_label) btn_segauto = QPushButton("Automatic seg.", self) btn_segauto.clicked.connect(self.autoSeg) btn_segman = QPushButton("Manual seg.", self) btn_segman.clicked.connect(self.manualSeg) self.text_seg_data = QLabel('segmented data:') grid.addWidget(hr, rstart + 0, 0, 1, 4) grid.addWidget(text_seg, rstart + 1, 1) grid.addWidget(btn_segauto, rstart + 2, 1) grid.addWidget(btn_segman, rstart + 2, 2) grid.addWidget(self.text_seg_data, rstart + 3, 1, 1, 2) rstart += 4 # ################ save/view btn_segsave = QPushButton("Save", self) btn_segsave.clicked.connect(self.saveOut) btn_segsavedcm = QPushButton("Save Dicom", self) btn_segsavedcm.clicked.connect(self.saveOutDcm) btn_segview = QPushButton("View3D", self) if viewer3D_available: btn_segview.clicked.connect(self.view3D) else: btn_segview.setEnabled(False) grid.addWidget(btn_segsave, rstart + 0, 1) grid.addWidget(btn_segview, rstart + 0, 2) grid.addWidget(btn_segsavedcm, rstart + 1, 1) rstart += 2 hr = QFrame() hr.setFrameShape(QFrame.HLine) grid.addWidget(hr, rstart + 0, 0, 1, 4) # quit btn_quit = QPushButton("Quit", self) btn_quit.clicked.connect(self.quit) grid.addWidget(btn_quit, rstart + 1, 1, 1, 2) cw.setLayout(grid) self.setWindowTitle('Organ Segmentation with Random Walker') self.show()
def initUI(self): cw = QWidget() self.setCentralWidget(cw) grid = QGridLayout() grid.setSpacing(10) # status bar self.statusBar().showMessage('Ready') font_label = QFont() font_label.setBold(True) font_info = QFont() font_info.setItalic(True) font_info.setPixelSize(10) # # # # # # # # # LISA logo # font_title = QFont() # font_title.setBold(True) # font_title.setSize(24) lisa_title = QLabel('LIver Surgery Analyser') info = QLabel('Developed by:\n' + 'University of West Bohemia\n' + 'Faculty of Applied Sciences\n' + QString.fromUtf8('M. Jiřík, V. Lukeš - 2013') + '\n\nVersion: ' + self.oseg.version ) info.setFont(font_info) lisa_title.setFont(font_label) lisa_logo = QLabel() logopath = os.path.join(path_to_script, "../applications/LISA256.png") logo = QPixmap(logopath) lisa_logo.setPixmap(logo) # scaledToWidth(128)) grid.addWidget(lisa_title, 0, 1) grid.addWidget(info, 1, 1) grid.addWidget(lisa_logo, 0, 2, 2, 2) # rid.setColumnMinimumWidth(1, logo.width()/2) # rid.setColumnMinimumWidth(2, logo.width()/2) # rid.setColumnMinimumWidth(3, logo.width()/2) # # dicom reader rstart = 2 hr = QFrame() hr.setFrameShape(QFrame.HLine) text_dcm = QLabel('DICOM reader') text_dcm.setFont(font_label) btn_dcmdir = QPushButton("Load DICOM", self) btn_dcmdir.clicked.connect(self.loadDataDir) btn_datafile = QPushButton("Load file", self) btn_datafile.clicked.connect(self.loadDataFile) btn_dcmcrop = QPushButton("Crop", self) btn_dcmcrop.clicked.connect(self.cropDcm) # voxelsize gui comment # elf.scaling_mode = 'original' # ombo_vs = QComboBox(self) # ombo_vs.activated[str].connect(self.changeVoxelSize) # eys = scaling_modes.keys() # eys.sort() # ombo_vs.addItems(keys) # ombo_vs.setCurrentIndex(keys.index(self.scaling_mode)) # elf.text_vs = QLabel('Voxel size:') # end-- voxelsize gui self.text_dcm_dir = QLabel('DICOM dir:') self.text_dcm_data = QLabel('DICOM data:') grid.addWidget(hr, rstart + 0, 2, 1, 4) grid.addWidget(text_dcm, rstart + 0, 1, 1, 3) grid.addWidget(btn_dcmdir, rstart + 1, 1) grid.addWidget(btn_datafile, rstart + 1, 2) grid.addWidget(btn_dcmcrop, rstart + 1, 3) # voxelsize gui comment # grid.addWidget(self.text_vs, rstart + 3, 1) # grid.addWidget(combo_vs, rstart + 4, 1) grid.addWidget(self.text_dcm_dir, rstart + 6, 1, 1, 3) grid.addWidget(self.text_dcm_data, rstart + 7, 1, 1, 3) rstart += 9 # # # # # # # # # segmentation hr = QFrame() hr.setFrameShape(QFrame.HLine) text_seg = QLabel('Segmentation') text_seg.setFont(font_label) btn_mask = QPushButton("Mask region", self) btn_mask.clicked.connect(self.maskRegion) btn_segauto = QPushButton("Automatic seg.", self) btn_segauto.clicked.connect(self.autoSeg) btn_segman = QPushButton("Manual seg.", self) btn_segman.clicked.connect(self.manualSeg) self.text_seg_data = QLabel('segmented data:') grid.addWidget(hr, rstart + 0, 2, 1, 4) grid.addWidget(text_seg, rstart + 0, 1) grid.addWidget(btn_mask, rstart + 1, 1) grid.addWidget(btn_segauto, rstart + 1, 2) grid.addWidget(btn_segman, rstart + 1, 3) grid.addWidget(self.text_seg_data, rstart + 2, 1, 1, 3) rstart += 3 # # # # # # # # # save/view # hr = QFrame() # hr.setFrameShape(QFrame.HLine) btn_segsave = QPushButton("Save", self) btn_segsave.clicked.connect(self.saveOut) btn_segsavedcm = QPushButton("Save Dicom", self) btn_segsavedcm.clicked.connect(self.saveOutDcm) btn_segview = QPushButton("View3D", self) if viewer3D_available: btn_segview.clicked.connect(self.view3D) else: btn_segview.setEnabled(False) grid.addWidget(btn_segsave, rstart + 0, 1) grid.addWidget(btn_segview, rstart + 0, 3) grid.addWidget(btn_segsavedcm, rstart + 0, 2) rstart += 2 # # # # Virtual resection hr = QFrame() hr.setFrameShape(QFrame.HLine) rstart += 1 hr = QFrame() hr.setFrameShape(QFrame.HLine) text_resection = QLabel('Virtual resection') text_resection.setFont(font_label) btn_vesselseg = QPushButton("Vessel segmentation", self) btn_vesselseg.clicked.connect(self.btnVesselSegmentation) btn_lesions = QPushButton("Lesions localization", self) btn_lesions.clicked.connect(self.btnLesionLocalization) btn_resection = QPushButton("Virtual resection", self) btn_resection.clicked.connect(self.btnVirtualResection) grid.addWidget(hr, rstart + 0, 2, 1, 4) grid.addWidget(text_resection, rstart + 0, 1) grid.addWidget(btn_vesselseg, rstart + 1, 1) grid.addWidget(btn_lesions, rstart + 1, 2) grid.addWidget(btn_resection, rstart + 1, 3) # # # # # # # hr = QFrame() hr.setFrameShape(QFrame.HLine) # rid.addWidget(hr, rstart + 0, 0, 1, 4) rstart += 3 # quit btn_quit = QPushButton("Quit", self) btn_quit.clicked.connect(self.quit) grid.addWidget(btn_quit, rstart + 1, 1, 1, 2) cw.setLayout(grid) self.setWindowTitle('LISA') self.show()