def make_source(self, name): self.compiler_view.addItem(name) self.compiler_view.setCurrentRow(0) scrollbar_width = QApplication.style().pixelMetric( QStyle.PM_ScrollBarExtent) self.compiler_view.setMaximumWidth( self.compiler_view.sizeHintForColumn(0) + scrollbar_width + 16) page = QWidget() QHBoxLayout(page) page.layout().setContentsMargins(*(0,) * 4) source = QTextEdit() source.setStyleSheet('min-width: 0; min-height: 0') source.setReadOnly(True) QVBoxLayout(source) button = QPushButton('Copy') button.clicked.connect(functools.partial(self.set_clipboard, source)) page.layout().addWidget(source) source.layout().addWidget(button, 0, Qt.AlignRight | Qt.AlignBottom) self.stacked_widget.addWidget(page) return source
class SurfaceLandmarkWidget(QWidget): def __init__(self): super(SurfaceLandmarkWidget, self).__init__() self.textFrame = QTextEdit("<p>Hold your mouse over the volume " "to move the locator. To create a landmark, press 'Space'.</p>" "<p>When you want to proceed to the following landmark, " "click the 'Done' button behind the landmark pair in the " "center of the window.</p>") self.textFrame.setReadOnly(True) self.textFrame.setFrameShape(QFrame.NoFrame) self.textFrame.setAutoFillBackground(False) self.textFrame.setAttribute(Qt.WA_TranslucentBackground) self.textFrame.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.textFrame.setStyleSheet("background: #aaa") layout = QGridLayout() layout.setAlignment(Qt.AlignTop) layout.setSpacing(0) layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(self.textFrame) self.setLayout(layout)
class SurfaceLandmarkWidget(QWidget): def __init__(self): super(SurfaceLandmarkWidget, self).__init__() self.textFrame = QTextEdit( "<p>Hold your mouse over the volume " "to move the locator. To create a landmark, press 'Space'.</p>" "<p>When you want to proceed to the following landmark, " "click the 'Done' button behind the landmark pair in the " "center of the window.</p>") self.textFrame.setReadOnly(True) self.textFrame.setFrameShape(QFrame.NoFrame) self.textFrame.setAutoFillBackground(False) self.textFrame.setAttribute(Qt.WA_TranslucentBackground) self.textFrame.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.textFrame.setStyleSheet("background: #aaa") layout = QGridLayout() layout.setAlignment(Qt.AlignTop) layout.setSpacing(0) layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(self.textFrame) self.setLayout(layout)
class TwoStepLandmarkWidget(QWidget): """ TwoStepLandmarkWidget """ pickedPosition = Signal() def __init__(self): super(TwoStepLandmarkWidget, self).__init__() self.textFrame = QTextEdit( "<p>Place your mouse over the desired " "landmark point. Press 'Space' to shoot a ray through the volume. " "Move the volume around and move the mouse to move the locator. " "Press 'Space' again to define the final place of the landmark.</p>" "<p>You can also use the ray profile to define the landmark's location.</p>" ) self.textFrame.setReadOnly(True) self.textFrame.setFrameShape(QFrame.NoFrame) self.textFrame.setAutoFillBackground(False) self.textFrame.setAttribute(Qt.WA_TranslucentBackground) self.textFrame.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.textFrame.setStyleSheet("background: #aaa") self.histogramWidget = TrackingHistogramWidget() self.histogramWidget.setMinimumHeight(100) self.histogramWidget.setVisible(False) self.button = QPushButton("Pick current landmark position") self.button.clicked.connect(self.applyButtonClicked) self.button.setVisible(False) layout = QGridLayout() layout.setAlignment(Qt.AlignTop) layout.setSpacing(0) layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(self.textFrame) layout.addWidget(self.histogramWidget) layout.addWidget(self.button) self.setLayout(layout) def setSamples(self, samples, scope=None): self.textFrame.setVisible(False) self.histogramWidget.setVisible(True) self.histogram = Histogram() self.histogram.bins = samples if scope: self.histogram.minY = scope[0] self.histogram.maxY = scope[1] self.histogram.enabled = True self.histogramWidget.setHistogram(self.histogram) self.histogramWidget.setAxeMode(left=HistogramWidget.AxeNormal) self.histogramWidget.nodeItem.tracking = True self.button.setVisible(True) @Slot() def applyButtonClicked(self): self.pickedPosition.emit() @Slot() def pickedLocation(self, location): self.histogramWidget.nodeItem.tracking = False self.button.setVisible(False)
class TwoStepLandmarkWidget(QWidget): """ TwoStepLandmarkWidget """ pickedPosition = Signal() def __init__(self): super(TwoStepLandmarkWidget, self).__init__() self.textFrame = QTextEdit("<p>Place your mouse over the desired " "landmark point. Press 'Space' to shoot a ray through the volume. " "Move the volume around and move the mouse to move the locator. " "Press 'Space' again to define the final place of the landmark.</p>" "<p>You can also use the ray profile to define the landmark's location.</p>") self.textFrame.setReadOnly(True) self.textFrame.setFrameShape(QFrame.NoFrame) self.textFrame.setAutoFillBackground(False) self.textFrame.setAttribute(Qt.WA_TranslucentBackground) self.textFrame.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.textFrame.setStyleSheet("background: #aaa") self.histogramWidget = TrackingHistogramWidget() self.histogramWidget.setMinimumHeight(100) self.histogramWidget.setVisible(False) self.button = QPushButton("Pick current landmark position") self.button.clicked.connect(self.applyButtonClicked) self.button.setVisible(False) layout = QGridLayout() layout.setAlignment(Qt.AlignTop) layout.setSpacing(0) layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(self.textFrame) layout.addWidget(self.histogramWidget) layout.addWidget(self.button) self.setLayout(layout) def setSamples(self, samples, scope=None): self.textFrame.setVisible(False) self.histogramWidget.setVisible(True) self.histogram = Histogram() self.histogram.bins = samples if scope: self.histogram.minY = scope[0] self.histogram.maxY = scope[1] self.histogram.enabled = True self.histogramWidget.setHistogram(self.histogram) self.histogramWidget.setAxeMode(left=HistogramWidget.AxeNormal) self.histogramWidget.nodeItem.tracking = True self.button.setVisible(True) @Slot() def applyButtonClicked(self): self.pickedPosition.emit() @Slot() def pickedLocation(self, location): self.histogramWidget.nodeItem.tracking = False self.button.setVisible(False)
class CCParsedTab(QWidget): def __init__(self, parser_result): QWidget.__init__(self) self._parser_result = parser_result layout = QHBoxLayout() layout.setContentsMargins(0, 0, 0, 0) layout.setSizeConstraint(QHBoxLayout.SetMinimumSize) self.table_widget = QTableWidget() self.table_widget.setSelectionMode(QAbstractItemView.NoSelection) self.table_widget.setRowCount(2) self.table_widget.setColumnCount(2) self.table_widget.horizontalHeader().setResizeMode(QHeaderView.Stretch) self.table_widget.setHorizontalHeaderLabels(["Dimension", "Choice"]) self.table_widget.verticalHeader().setVisible(False) self.table_widget.verticalHeader().setResizeMode(QHeaderView.Fixed) self.table_widget.verticalHeader().setDefaultSectionSize(20) sp_table = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) sp_table.setHorizontalStretch(1) self.table_widget.setSizePolicy(sp_table) layout.addWidget(self.table_widget) self.text_widget = QTextEdit() sp_text = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) sp_text.setHorizontalStretch(4) self.text_widget.setReadOnly(True) self.text_widget.setSizePolicy(sp_text) self.text_widget.setStyleSheet('font: 9pt "Courier";') self.text_widget.setText(self._parser_result.get_text()) layout.addWidget(self.text_widget) self.setLayout(layout) self._fill_table() def _fill_table(self): colors = ["yellow", "orange", "green", "red"] dimensions = self._parser_result.get_dimensions() row = 0 for dimension in dimensions: dimension_name = QLabel(dimension[0]) dimension_name.setStyleSheet("background: %s" % colors[row % len(colors)]) self.table_widget.setCellWidget(row, 0, dimension_name) choices_widget = QComboBox() choices = dimension[1] choices.insert(0, "No choice") choices_widget.addItems(choices) choices_widget.setStyleSheet("background: white") choices_widget.setStyleSheet("border: none") choices_widget.currentIndexChanged.connect(self.on_choice_change) self.table_widget.setCellWidget(row, 1, choices_widget) row += 1 @Slot() def on_choice_change(self): text = self._parser_result.get_text() for row in range(self.table_widget.rowCount()): label = self.table_widget.cellWidget(row, 0) choices = self.table_widget.cellWidget(row, 1) if choices.currentIndex() == 0: continue regex = self._build_regex(label.text(), choices.count() - 1) pattern = re.compile(regex) matches = pattern.search(text) for match in matches.groups(): results = re.search("<(.+)>", match) variants = [s.strip() for s in results.groups()[0].split(",")] text = text.replace(match, variants[choices.currentIndex() - 1]) self.text_widget.setText(text) @staticmethod def _build_regex(dim, count): regex = "(" + dim + "<" for i in range(count): regex += ".+,[ ]?" regex = regex[:-5] regex += ">)" return regex
class qNotebook(QVBoxLayout): def __init__(self): QVBoxLayout.__init__(self) self._teditor = QTextEdit() self._teditor.setMinimumWidth(500) self._teditor.setStyleSheet("font: 12pt \"Courier\";") button_layout = QHBoxLayout() self.addLayout(button_layout) self.clear_but = qmy_button(button_layout, self.clear_all, "clear") self.copy_but = qmy_button(button_layout, self._teditor.copy, "copy") qmy_button(button_layout, self._teditor.selectAll, "select all") qmy_button(button_layout, self._teditor.undo, "undo") qmy_button(button_layout, self._teditor.redo, "redo") search_button = qButtonWithArgumentsClass("search", self.search_for_text, {"search_text": ""}) button_layout.addWidget(search_button) qmy_button(button_layout, self.save_as_html, "save notebook") self.addWidget(self._teditor) self._teditor.document().setUndoRedoEnabled(True) self.image_counter = 0 self.image_dict = {} self.image_data_dict = {} def append_text(self, text): self._teditor.append(str(text)) def search_for_text(self, search_text = " "): self._teditor.find(search_text) def clear_all(self): self._teditor.clear() self.image_dict = {} self.image_counter = 0 # newdoc = QTextDocument() # self._teditor.setDocument(newdoc) def append_image(self, fig=None): #This assumes that an image is there waiting to be saved from matplotlib self.imgdata = StringIO.StringIO() if fig is None: pyplot.savefig(self.imgdata, transparent = False, format = img_format) else: fig.savefig(self.imgdata, transparent = False, format = img_format) self.abuffer = QBuffer() self.abuffer.open(QBuffer.ReadWrite) self.abuffer.write(self.imgdata.getvalue()) self.abuffer.close() self.abuffer.open(QBuffer.ReadOnly) iReader = QImageReader(self.abuffer, img_format ) the_image = iReader.read() # the_image = the_image0.scaledToWidth(figure_width) # save the image in a file imageFileName = "image" + str(self.image_counter) + "." + img_format self.image_data_dict[imageFileName] = self.imgdata self.image_counter +=1 imageFormat = QTextImageFormat() imageFormat.setName(imageFileName) imageFormat.setWidth(image_width) self.image_dict[imageFileName] = the_image #insert the image in the text document text_doc = self._teditor.document() text_doc.addResource(QTextDocument.ImageResource, QUrl(imageFileName), the_image) cursor = self._teditor.textCursor() cursor.movePosition(QTextCursor.End) cursor.insertImage(imageFormat) def add_image_data_resource(self, imgdata, imageFileName): self.abuffer = QBuffer() self.abuffer.open(QBuffer.ReadWrite) self.abuffer.write(imgdata.getvalue()) self.abuffer.close() self.abuffer.open(QBuffer.ReadOnly) iReader = QImageReader(self.abuffer, img_format ) the_image = iReader.read() # the_image = the_image0.scaledToWidth(figure_width) # save the image in a file # imageFileName = "image" + str(self.image_counter) + "." + img_format self.image_data_dict[imageFileName] = imgdata # self.image_counter +=1 imageFormat = QTextImageFormat() imageFormat.setName(imageFileName) imageFormat.setWidth(image_width) self.image_dict[imageFileName] = the_image #insert the image in the text document text_doc = self._teditor.document() text_doc.addResource(QTextDocument.ImageResource, QUrl(imageFileName), the_image) def append_html_table_from_array(self, a, header_rows=0, precision = 3, caption = None, cmap = None): nrows = len(a) ncols = len(a[0]) result_string = "<table border=\"1\" cellspacing=\"0\" cellpadding=\"2\">\n" if caption != None: result_string += "<caption>%s</caption>\n" % caption r = 0 while r < header_rows: result_string += "<tr>" for c in range(ncols): if a[r][c] != "": # count following blank columns count = 1 while ((c+count) < len(a[r])) and (a[r][c+count] == "") : count += 1 val = a[r][c] if (type(val) == numpy.float64) or (type(val) == float): # @UndefinedVariable if precision != 999: val = round(val, precision) if count > 1: result_string +="<th colspan=%s>%s</th>" % (count, val) else: result_string += "<th>%s</th>" % val result_string +="</tr>\n" r += 1 while r < nrows: result_string += "<tr>" for c in range(ncols): val = a[r][c] if (cmap == None): fcolor = "#ffffff" elif (type(val) == int) or (type(val) == float) or (type(val) == numpy.float64): # @UndefinedVariable fcolor = cmap.color_from_val(val) else: fcolor = "#ffffff" if (val != "") or (c == 0): if (type(val) == numpy.float64) or (type(val) == float): # @UndefinedVariable if precision != 999: val = round(val, precision) count = 1 while ((c+count) < len(a[r])) and (a[r][c+count] == "") : count += 1 if count > 1: result_string +="<td colspan=%s bgcolor=%s>%s</td>" % (count, fcolor, val) else: result_string += "<td bgcolor=%s>%s</td>" % (fcolor, val) result_string +="</tr>\n" r += 1 result_string += "</table>\n" self.append_text(result_string) def create_empty_string_array(self, rows, cols): table_array = [] for r in range(rows): #@UnusedVariable the_row = [] for c in range(cols): #@UnusedVariable the_row.append("") table_array.append(the_row) return table_array def recurse_on_dict_headers(self, sdict, r, c, sorted_headers = None): if ((type(sdict) != dict) and (type(sdict) != OrderedDict)): return c + 1 else: if sorted_headers != None: sheaders = sorted_headers else: sheaders = sorted(sdict.keys()) for k in sheaders: self.table_array[r][c] = k c = self.recurse_on_dict_headers(sdict[k], r + 1, c) return c def recurse_to_find_size(self, sdict, r, c): if ((type(sdict) != dict) and (type(sdict) != OrderedDict)): return r, c + 1 else: rbiggest = r for k in sorted(sdict.keys()): rnew, c = self.recurse_to_find_size(sdict[k], r + 1, c) if rnew > rbiggest: rbiggest = rnew return rbiggest, c def recurse_on_dict(self, sdict, r, c, sorted_headers = None): if ((type(sdict) != dict) and (type(sdict) != OrderedDict)): self.table_array[r][c] = sdict return c + 1 else: if sorted_headers != None: sheaders = sorted_headers else: sheaders = sorted(sdict.keys()) for k in sheaders: c = self.recurse_on_dict(sdict[k], r, c) return c def convert_structured_dicts_to_array(self, sdict, sorted_keys = None, sorted_headers = None): header_levels, ncols = self.recurse_to_find_size(sdict[sdict.keys()[0]], 0, 0) nrows = header_levels + len(sdict.keys()) self.table_array = self.create_empty_string_array(nrows, ncols) self.recurse_on_dict_headers(sdict[sdict.keys()[0]], 0, 0, sorted_headers) if sorted_keys != None: key_list = sorted_keys else: key_list = sdict.keys() r = header_levels for entry in key_list: c = 0 self.table_array[r][0] = entry self.recurse_on_dict(sdict[entry], r, c, sorted_headers = sorted_headers) r += 1 return self.table_array def append_html_table_from_dicts(self, sdict, header_rows = 1, title = None, sorted_keys = None, precision = 3, cmap = None, sorted_headers = None): the_array = self.convert_structured_dicts_to_array(sdict, sorted_keys, sorted_headers = sorted_headers) self.append_html_table_from_array(the_array, header_rows, caption = title, precision = precision, cmap = cmap) def append_table(self, rows, cols, border_style = QTextFrameFormat.BorderStyle_Solid): tformat = QTextTableFormat() tformat.setBorderStyle(border_style) cursor= self._teditor.textCursor() cursor.movePosition(QTextCursor.End) table = cursor.insertTable(rows, cols, tformat) return table def fill_table_cell(self, row, col, table, text): cptr = table.cellAt(row, col).firstCursorPosition() cptr.insertText(text) def save_as_html(self): fname = QFileDialog.getSaveFileName()[0] fdirectoryname = os.path.dirname(fname) # fdirectoryname = QFileDialog.getExistingDirectory() # print fdirectoryname # fname = fdirectoryname + "/report.html" text_doc = self._teditor.document() f = open(fname, 'w') f.write(text_doc.toHtml()) f.close() for imageFileName in self.image_dict.keys(): full_image_path = fdirectoryname + "/" + imageFileName iWriter = QImageWriter(full_image_path, img_format) iWriter.write(self.image_dict[imageFileName])