def init_kernel_menu(self): self.kernel_menu = self.menuBar().addMenu("&Kernel") # Qt on OSX maps Ctrl to Cmd, and Meta to Ctrl # keep the signal shortcuts to ctrl, rather than # platform-default like we do elsewhere. ctrl = "Meta" if sys.platform == 'darwin' else "Ctrl" self.interrupt_kernel_action = QtGui.QAction("&Interrupt current Kernel", self, triggered=self.interrupt_kernel_active_frontend, shortcut=ctrl+"+C", ) self.add_menu_action(self.kernel_menu, self.interrupt_kernel_action) self.restart_kernel_action = QtGui.QAction("&Restart current Kernel", self, triggered=self.restart_kernel_active_frontend, shortcut=ctrl+"+.", ) self.add_menu_action(self.kernel_menu, self.restart_kernel_action) self.kernel_menu.addSeparator() self.confirm_restart_kernel_action = QtGui.QAction("&Confirm kernel restart", self, checkable=True, checked=self.active_frontend.confirm_restart, triggered=self.toggle_confirm_restart_active_frontend ) self.add_menu_action(self.kernel_menu, self.confirm_restart_kernel_action) self.tab_widget.currentChanged.connect(self.update_restart_checkbox)
def get_color(self, color, intensity=0): """ Returns a QColor for a given color code or rgb list, or None if one cannot be constructed. """ if isinstance(color, int): # Adjust for intensity, if possible. if color < 8 and intensity > 0: color += 8 constructor = self.color_map.get(color, None) elif isinstance(color, (tuple, list)): constructor = color else: return None if isinstance(constructor, string_types): # If this is an X11 color name, we just hope there is a close SVG # color name. We could use QColor's static method # 'setAllowX11ColorNames()', but this is global and only available # on X11. It seems cleaner to aim for uniformity of behavior. return QtGui.QColor(constructor) elif isinstance(constructor, (tuple, list)): return QtGui.QColor(*constructor) return None
def svg_to_image(string, size=None): """ Convert a SVG document to a QImage. Parameters ---------- string : basestring A Python string containing a SVG document. size : QSize, optional The size of the image that is produced. If not specified, the SVG document's default size is used. Raises ------ ValueError If an invalid SVG string is provided. Returns ------- A QImage of format QImage.Format_ARGB32. """ if isinstance(string, unicode_type): string = string.encode('utf-8') renderer = QtSvg.QSvgRenderer(QtCore.QByteArray(string)) if not renderer.isValid(): raise ValueError('Invalid SVG data.') if size is None: size = renderer.defaultSize() image = QtGui.QImage(size, QtGui.QImage.Format_ARGB32) painter = QtGui.QPainter(image) renderer.render(painter) return image
def init_help_menu(self): # please keep the Help menu in Mac Os even if empty. It will # automatically contain a search field to search inside menus and # please keep it spelled in English, as long as Qt Doesn't support # a QAction.MenuRole like HelpMenuRole otherwise it will lose # this search field functionality self.help_menu = self.menuBar().addMenu("&Help") # Help Menu self.intro_active_frontend_action = QtGui.QAction( "&Intro to IPython", self, triggered=self.intro_active_frontend) self.add_menu_action(self.help_menu, self.intro_active_frontend_action) self.quickref_active_frontend_action = QtGui.QAction( "IPython &Cheat Sheet", self, triggered=self.quickref_active_frontend) self.add_menu_action(self.help_menu, self.quickref_active_frontend_action) self.guiref_active_frontend_action = QtGui.QAction( "&Qt Console", self, triggered=self.guiref_active_frontend) self.add_menu_action(self.help_menu, self.guiref_active_frontend_action) self.onlineHelpAct = QtGui.QAction("Open Online &Help", self, triggered=self._open_online_help) self.add_menu_action(self.help_menu, self.onlineHelpAct)
def addFitCheckBoxes(self, setpars, fitpars, nofitbox): """ Add the fitting checkboxes at the top of the plk Window @param setpars: The parameters that are 'set' (in the model) @param fitpars: The parameters that are currently being fitted for @param nofitbox: The parameters we should skip """ # Delete the fitboxes if there were still some left if not len(self.vboxes) == 0: self.deleteFitCheckBoxes() # First add all the vbox layouts for ii in range(min(self.fitboxPerLine, len(setpars))): self.vboxes.append(QtGui.QVBoxLayout()) self.hbox.addLayout(self.vboxes[-1]) # Then add the checkbox widgets to the vboxes index = 0 for pp, par in enumerate(setpars): if not par in nofitbox: vboxind = index % self.fitboxPerLine cb = QtGui.QCheckBox(par, self) cb.stateChanged.connect(self.changedFitCheckBox) # Set checked/unchecked cb.setChecked(par in fitpars) self.vboxes[vboxind].addWidget(cb) index += 1 for vv, vbox in enumerate(self.vboxes): vbox.addStretch(1)
def get_font(family, fallback=None): """Return a font of the requested family, using fallback as alternative. If a fallback is provided, it is used in case the requested family isn't found. If no fallback is given, no alternative is chosen and Qt's internal algorithms may automatically choose a fallback font. Parameters ---------- family : str A font name. fallback : str A font name. Returns ------- font : QFont object """ font = QtGui.QFont(family) # Check whether we got what we wanted using QFontInfo, since exactMatch() # is overly strict and returns false in too many cases. font_info = QtGui.QFontInfo(font) if fallback is not None and font_info.family() != family: font = QtGui.QFont(fallback) return font
def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.history_s = 20.0 self.next_color = 0 self.paused = False self.last_draw_time = 0.0 self.figure = matplotlib.figure.Figure() self.canvas = FigureCanvas(self.figure) self.canvas.mpl_connect('key_press_event', self.handle_key_press) self.canvas.mpl_connect('key_release_event', self.handle_key_release) self.left_axis = self.figure.add_subplot(111) self.left_axis.grid() self.left_axis.fmt_xdata = lambda x: '%.3f' % x self.left_axis.legend_loc = LEFT_LEGEND_LOC self.right_axis = None self.toolbar = qt_backend.NavigationToolbar2QT(self.canvas, self) self.pause_action = QtGui.QAction(u'Pause', self) self.pause_action.setCheckable(True) self.pause_action.toggled.connect(self._handle_pause) self.toolbar.addAction(self.pause_action) layout = QtGui.QVBoxLayout(self) layout.addWidget(self.toolbar, 0) layout.addWidget(self.canvas, 1) self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus)
def __init__(self, parent=None, **kwargs): super(PlkXYPlotWidget, self).__init__(parent, **kwargs) self.parent = parent # We are going to use a grid layout: self.grid = QtGui.QGridLayout() self.grid.setSpacing(10) self.xButtonGroup = QtGui.QButtonGroup(self) self.xButtonGroup.buttonClicked[int].connect(self.updateXPlot) self.yButtonGroup = QtGui.QButtonGroup(self) self.yButtonGroup.buttonClicked[int].connect(self.updateYPlot) self.xSelected = 0 self.ySelected = 0 # TODO: implement this: # Connect the 'buttonClicked' signal 'self.setLabel' # There are two overloads for 'buttonClicked' signal: QAbstractButton (button itself) or int (id) # Specific overload for the signal is selected via [QtGui.QAbstractButton] # Clicking any button in the QButtonGroup will send this signal with the button # self.buttonGroup.buttonClicked[QtGui.QAbstractButton].connect(self.setLabel) # def setLabel(self, button): # Use an empty base pulsar to obtain the labels self.xychoices = pu.plot_labels self.setPlkXYPlotLayout()
def __init__(self, parent=None, **kwargs): super(ParEditWidget, self).__init__(parent, **kwargs) self.parent = parent self.layout = QtGui.QVBoxLayout() self.table = QtGui.QTableWidget() self.initLayout()
def insertRow(self, row): self.table.insertRow(row) self.table.setItem(row, 0, QtGui.QTableWidgetItem('')) self.table.setItem(row, 1, QtGui.QTableWidgetItem('')) cbox = QtGui.QTableWidgetItem() cbox.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled) cbox.setCheckState(QtCore.Qt.Unchecked) self.table.setItem(row, 2, cbox) self.table.setItem(row, 3, QtGui.QTableWidgetItem(''))
def paintEvent(self, event): """ Reimplemented to paint the background panel. """ painter = QtGui.QStylePainter(self) option = QtGui.QStyleOptionFrame() option.initFrom(self) painter.drawPrimitive(QtGui.QStyle.PE_PanelTipLabel, option) painter.end() super(CallTipWidget, self).paintEvent(event)
def initOSWidget(self): """ Initialise the widget with a button and a label """ self.vbox = QtGui.QVBoxLayout() button = QtGui.QPushButton("Open a file...") button.clicked.connect(self.openFile) self.vbox.addWidget(button) self.setLayout(self.vbox)
def drawLabelAtMouse(self, qp): # Nothing to do without a highlighted object if not self.highlightObj: return # Nothing to without a mouse position if not self.mousePosOrig: return # Save QPainter settings to stack qp.save() # That is the mouse positiong mouse = self.mousePosOrig # Will show zoom showZoom = self.zoom and not self.image.isNull() and self.w and self.h # The text that is written next to the mouse mouseText = self.highlightObj.label # Where to write the text # Depends on the zoom (additional offset to mouse to make space for zoom?) # The location in the image (if we are at the top we want to write below of the mouse) off = 36 if showZoom: off += self.zoomSize / 2 if mouse.y() - off > self.toolbar.height(): top = mouse.y() - off btm = mouse.y() vAlign = QtCore.Qt.AlignTop else: # The height of the cursor if not showZoom: off += 20 top = mouse.y() btm = mouse.y() + off vAlign = QtCore.Qt.AlignBottom # Here we can draw rect = QtCore.QRect() rect.setTopLeft(QtCore.QPoint(mouse.x() - 200, top)) rect.setBottomRight(QtCore.QPoint(mouse.x() + 200, btm)) # The color qp.setPen(QtGui.QColor('white')) # The font to use font = QtGui.QFont("Helvetica", 20, QtGui.QFont.Bold) qp.setFont(font) # Non-transparent qp.setOpacity(1) # Draw the text, horizontally centered qp.drawText(rect, QtCore.Qt.AlignHCenter | vAlign, mouseText) # Restore settings qp.restore()
def __init__(self, *args, **kw): super(FrontendWidget, self).__init__(*args, **kw) # FIXME: remove this when PySide min version is updated past 1.0.7 # forcefully disable calltips if PySide is < 1.0.7, because they crash if qt.QT_API == qt.QT_API_PYSIDE: import PySide if PySide.__version_info__ < (1, 0, 7): self.log.warn( "PySide %s < 1.0.7 detected, disabling calltips" % PySide.__version__) self.enable_calltips = False # FrontendWidget protected variables. self._bracket_matcher = BracketMatcher(self._control) self._call_tip_widget = CallTipWidget(self._control) self._copy_raw_action = QtGui.QAction('Copy (Raw Text)', None) self._hidden = False self._highlighter = FrontendHighlighter(self, lexer=self.lexer) self._input_splitter = self._input_splitter_class() self._kernel_manager = None self._kernel_client = None self._request_info = {} self._request_info['execute'] = {} self._callback_dict = {} self._display_banner = True # Configure the ConsoleWidget. self.tab_width = 4 self._set_continuation_prompt('... ') # Configure the CallTipWidget. self._call_tip_widget.setFont(self.font) self.font_changed.connect(self._call_tip_widget.setFont) # Configure actions. action = self._copy_raw_action key = QtCore.Qt.CTRL | QtCore.Qt.SHIFT | QtCore.Qt.Key_C action.setEnabled(False) action.setShortcut(QtGui.QKeySequence(key)) action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut) action.triggered.connect(self.copy_raw) self.copy_available.connect(action.setEnabled) self.addAction(action) # Connect signal handlers. document = self._control.document() document.contentsChange.connect(self._document_contents_change) # Set flag for whether we are connected via localhost. self._local_kernel = kw.get('local_kernel', FrontendWidget._local_kernel) # Whether or not a clear_output call is pending new output. self._pending_clearoutput = False
def initLayout(self): self.prefit = QtGui.QRadioButton('Pre-Fit') self.prefit.toggled.connect(lambda: self.choose(self.prefit)) self.prefit.setChecked(True) self.hbox.addWidget(self.prefit) self.postfit = QtGui.QRadioButton('Post-Fit') self.postfit.toggled.connect(lambda: self.choose(self.postfit)) self.hbox.addWidget(self.postfit) self.hbox.addStretch(1) self.setLayout(self.hbox)
def addFitCheckBoxes(self, comps, fitpars, nofitbox): """ Add the fitting checkboxes at the top of the plk Window @param comps: A dict of model components and their 'set' parameters @param fitpars: The parameters that are currently being fitted for @param nofitbox: The parameters we should skip """ self.deleteFitCheckBoxes() self.compGrids = [] ii = 0 for comp in comps: showpars = [p for p in comps[comp] if not p in nofitbox] #Don't put anything if there are no parameters to show if len(showpars) == 0: continue #Add component label font = QtGui.QFont() font.setBold(True) ccb = QtGui.QCheckBox(comp, self) ccb.stateChanged.connect(self.changedGroupCheckBox) ccb.setFont(font) ccb.setChecked(False) self.grid.addWidget(ccb, ii, 0, 1, 1) noneChecked = True self.compGrids.append(QtGui.QGridLayout()) for pp, par in enumerate(showpars): cb = QtGui.QCheckBox(par, self) cb.stateChanged.connect(self.changedFitCheckBox) #Set checked/unchecked cb.setChecked(par in fitpars) if par in fitpars: noneChecked = False self.compGrids[ii].addWidget(cb, int(pp / self.maxcols), pp % self.maxcols, 1, 1) #Now pad the last row lastcol = len(showpars) % self.maxcols lastrow = int(len(showpars) / self.maxcols) if lastcol < self.maxcols: label = QtGui.QLabel(self) label.setText('') self.compGrids[ii].addWidget(label, lastrow, lastcol, 1, self.maxcols - lastcol) self.grid.addItem(self.compGrids[ii], ii, 1, 1, self.maxcols) if noneChecked: self.changeGroupVisibility(False, ii) ii += 1
def loadDisparities(self): if not self.enableDisparity: return if not self.showDisparity: return filename = self.getDisparityFilename() if not filename: self.dispImg = None return # If we have everything and the filename did not change, then we are good if self.dispImg and filename == self.currentDispFile: return # Clear the current labels first self.dispImg = None try: self.dispImg = Image.open(filename) except IOError as e: # This is the error if the file does not exist message = "Error parsing disparities in {0}. Message: {1}".format(filename, e.strerror) self.statusBar().showMessage(message) self.dispImg = None if self.dispImg: dispNp = np.array(self.dispImg) dispNp /= 128 dispNp.round() dispNp = np.array(dispNp, dtype=np.uint8) dispQt = QtGui.QImage(dispNp.data, dispNp.shape[1], dispNp.shape[0], QtGui.QImage.Format_Indexed8) colortable = [] for i in range(256): color = self.colormap.to_rgba(i) colorRgb = (int(color[0] * 255), int(color[1] * 255), int(color[2] * 255)) colortable.append(QtGui.qRgb(*colorRgb)) dispQt.setColorTable(colortable) dispQt = dispQt.convertToFormat(QtGui.QImage.Format_ARGB32_Premultiplied) self.dispOverlay = dispQt # Remember the filename loaded self.currentDispFile = filename # Remember the status bar message to restore it later restoreMessage = self.statusBar().currentMessage() # Restore the message self.statusBar().showMessage(restoreMessage)
def initPlk(self): self.setMinimumSize(650, 550) self.plkbox = QtGui.QVBoxLayout( ) # plkbox contains the whole plk widget self.xyplotbox = QtGui.QHBoxLayout( ) # plkbox contains the whole plk widget self.fitboxesWidget = PlkFitboxesWidget( parent=self) # Contains all the checkboxes self.actionsWidget = PlkActionsWidget(parent=self) # We are creating the Figure here, so set the color scheme appropriately self.setColorScheme(True) # Create the mpl Figure and FigCanvas objects. # 5x4 inches, 100 dots-per-inch # self.plkDpi = 100 self.plkFig = Figure((5.0, 4.0), dpi=self.plkDpi) self.plkCanvas = FigureCanvas(self.plkFig) self.plkCanvas.setParent(self) # Since we have only one plot, we can use add_axes # instead of add_subplot, but then the subplot # configuration tool in the navigation toolbar wouldn't # work. # self.plkAxes = self.plkFig.add_subplot(111) # Done creating the Figure. Restore color scheme to defaults self.setColorScheme(False) # Call-back functions for clicking and key-press. self.plkCanvas.mpl_connect('button_press_event', self.canvasClickEvent) self.plkCanvas.mpl_connect('key_press_event', self.canvasKeyEvent) # Create the navigation toolbar, tied to the canvas # #self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame) # Draw an empty graph self.drawSomething() # Create the XY choice widget self.xyChoiceWidget = PlkXYPlotWidget(parent=self) # At startup, all the widgets are visible self.xyChoiceVisible = True self.fitboxVisible = True self.actionsVisible = False #self.layoutMode = 1 # (0 = none, 1 = all, 2 = only fitboxes, 3 = fit & action) self.layoutMode = 4 # (0 = none, 1 = all, 2 = only xy select, 3 = only fit, 4 = xy select & fit)
def __init__(self, text_edit): """ Create a call tip manager that is attached to the specified Qt text edit widget. """ assert isinstance(text_edit, (QtGui.QTextEdit, QtGui.QPlainTextEdit)) super(BracketMatcher, self).__init__() # The format to apply to matching brackets. self.format = QtGui.QTextCharFormat() self.format.setBackground(QtGui.QColor('silver')) self._text_edit = text_edit text_edit.cursorPositionChanged.connect(self._cursor_position_changed)
def init_edit_menu(self): self.edit_menu = self.menuBar().addMenu("&Edit") self.undo_action = QtGui.QAction( "&Undo", self, shortcut=QtGui.QKeySequence.Undo, statusTip="Undo last action if possible", triggered=self.undo_active_frontend) self.add_menu_action(self.edit_menu, self.undo_action) self.redo_action = QtGui.QAction( "&Redo", self, shortcut=QtGui.QKeySequence.Redo, statusTip="Redo last action if possible", triggered=self.redo_active_frontend) self.add_menu_action(self.edit_menu, self.redo_action) self.edit_menu.addSeparator() self.cut_action = QtGui.QAction("&Cut", self, shortcut=QtGui.QKeySequence.Cut, triggered=self.cut_active_frontend) self.add_menu_action(self.edit_menu, self.cut_action, True) self.copy_action = QtGui.QAction("&Copy", self, shortcut=QtGui.QKeySequence.Copy, triggered=self.copy_active_frontend) self.add_menu_action(self.edit_menu, self.copy_action, True) self.copy_raw_action = QtGui.QAction( "Copy (&Raw Text)", self, shortcut="Ctrl+Shift+C", triggered=self.copy_raw_active_frontend) self.add_menu_action(self.edit_menu, self.copy_raw_action, True) self.paste_action = QtGui.QAction("&Paste", self, shortcut=QtGui.QKeySequence.Paste, triggered=self.paste_active_frontend) self.add_menu_action(self.edit_menu, self.paste_action, True) self.edit_menu.addSeparator() selectall = QtGui.QKeySequence(QtGui.QKeySequence.SelectAll) if selectall.matches("Ctrl+A") and sys.platform != 'darwin': # Only override the default if there is a collision. # Qt ctrl = cmd on OSX, so the match gets a false positive on OSX. selectall = "Ctrl+Shift+A" self.select_all_action = QtGui.QAction( "Select Cell/&All", self, shortcut=selectall, triggered=self.select_all_active_frontend) self.add_menu_action(self.edit_menu, self.select_all_action, True)
def initLayout(self): button = QtGui.QPushButton('Reset Changes') button.clicked.connect(self.resetChanges) self.hbox.addWidget(button) button = QtGui.QPushButton('Apply Changes') button.clicked.connect(self.applyChanges) self.hbox.addWidget(button) button = QtGui.QPushButton('Write Par') button.clicked.connect(self.writePar) self.hbox.addWidget(button) self.hbox.addStretch(1) self.setLayout(self.hbox)
def init_help_menu(self): # please keep the Help menu in Mac Os even if empty. It will # automatically contain a search field to search inside menus and # please keep it spelled in English, as long as Qt Doesn't support # a QAction.MenuRole like HelpMenuRole otherwise it will lose # this search field functionality self.help_menu = self.menuBar().addMenu("&Help") # Help Menu self.help_action = QtGui.QAction("Show &QtConsole help", self, triggered=self._show_help) self.online_help_action = QtGui.QAction("Open online &help", self, triggered=self._open_online_help) self.add_menu_action(self.help_menu, self.help_action) self.add_menu_action(self.help_menu, self.online_help_action)
def save_svg(string, parent=None): """ Prompts the user to save an SVG document to disk. Parameters ---------- string : basestring A Python string containing a SVG document. parent : QWidget, optional The parent to use for the file dialog. Returns ------- The name of the file to which the document was saved, or None if the save was cancelled. """ if isinstance(string, unicode_type): string = string.encode('utf-8') dialog = QtGui.QFileDialog(parent, 'Save SVG Document') dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave) dialog.setDefaultSuffix('svg') dialog.setNameFilter('SVG document (*.svg)') if dialog.exec_(): filename = dialog.selectedFiles()[0] f = open(filename, 'wb') try: f.write(string) finally: f.close() return filename return None
def __init__(self, parent=None): super().__init__(parent) self.setWindowTitle("Fail!") #setWindowTitle('')=>윈도우의 타이틀 지정한다 self.setGeometry(300, 300, 400, 300) #setGeometry(시작 위치, 윈도우 크기)=>윈도우 크기와 위치 지정한다 self.mouseIs = None #버튼이 눌렸는지 확인하는 변수 생성한다 failImg = QLabel(self) #문자열, 이미지 나타내는 데에 편리한 라벨 객체를 생성한다 failImg.setPixmap(QPixmap("typing_img/fail.png")) # .setPixmap()=>QLabel에 이미지를 지정한다 failImg.move(self.width()-330, self.height()-300) # .move()=>QLabel 위치를 지정한다 failImg.resize(250, 250) # .resize()=>QLabel 크기를 지정한다 fail = QLabel("Fail! Try again?", self) #문자열을 담은 라벨 객체를 생성한다 fail.setFont(QtGui.QFont('맑은 고딕', 15)) # .setFont()=>글씨체와 크기 지정한다 fail.move(130, 200) fail.resize(400,50) yesButton = QPushButton("Yes", self) #문자열을 담은 버튼 객체를 생성한다=>QLabel과 다르게 버튼을 누르는 이벤트 발생 가능하다 yesButton.move(80, 250) yesButton.clicked.connect(self.yesbutton_clicked) #yesButton이 눌렸을 때 yesbutton_clicked 함수를 실행한다 noButton = QPushButton("No", self) noButton.move(220, 250) noButton.clicked.connect(self.noButton_clicked) #noButton이 눌렸을 때 nobutton_clicked 함수를 실행한다
def show_items(self, cursor, items): """ Shows the completion widget with 'items' at the position specified by 'cursor'. """ if not items: return self._start_position = cursor.position() self._consecutive_tab = 1 # Calculate the number of characters available. width = self._text_edit.document().textWidth() char_width = QtGui.QFontMetrics(self._console_widget.font).width(' ') displaywidth = int(max(10, (width / char_width) - 1)) items_m, ci = text.compute_item_matrix(items, empty=' ', displaywidth=displaywidth) self._sliding_interval = SlidingInterval(len(items_m) - 1) self._items = items_m self._size = (ci['rows_numbers'], ci['columns_numbers']) self._old_cursor = cursor self._index = (0, 0) sjoin = lambda x: [ y.ljust(w, ' ') for y, w in zip(x, ci['columns_width']) ] self._justified_items = list(map(sjoin, items_m)) self._update_list(hilight=False)
def setUpClass(cls): """ Create the application for the test case. """ cls._app = QtGui.QApplication.instance() if cls._app is None: cls._app = QtGui.QApplication([]) cls._app.setQuitOnLastWindowClosed(False)
def __init__(self, parent=None): super().__init__(parent) self.setWindowTitle("Success!") self.setGeometry(300, 300, 400, 300) self.mouseIs = None successImg = QLabel(self) successImg.setPixmap(QPixmap("typing_img/success.png")) successImg.move(self.width()-330, self.height()-300) successImg.resize(250, 250) success = QLabel("Success! One more time?", self) success.setFont(QtGui.QFont('맑은 고딕', 15)) success.move(80, 200) success.resize(400,50) yesButton = QPushButton("Yes", self) yesButton.move(80, 250) yesButton.clicked.connect(self.yesbutton_clicked) noButton = QPushButton("No", self) noButton.move(220, 250) noButton.clicked.connect(self.noButton_clicked)
def init_qt_elements(self): # Create the widget. base_path = os.path.abspath(os.path.dirname(__file__)) icon_path = os.path.join(base_path, 'resources', 'icon', 'JupyterConsole.svg') self.app.icon = QtGui.QIcon(icon_path) QtGui.QApplication.setWindowIcon(self.app.icon) ip = self.ip local_kernel = (not self.existing) or is_local_ip(ip) self.widget = self.widget_factory(config=self.config, local_kernel=local_kernel) self.init_colors(self.widget) self.widget._existing = self.existing self.widget._may_close = not self.existing self.widget._confirm_exit = self.confirm_exit self.widget._display_banner = self.display_banner self.widget.kernel_manager = self.kernel_manager self.widget.kernel_client = self.kernel_client self.window = MainWindow(self.app, confirm_exit=self.confirm_exit, new_frontend_factory=self.new_frontend_master, slave_frontend_factory=self.new_frontend_slave, connection_frontend_factory=self.new_frontend_connection, ) self.window.log = self.log self.window.add_tab_with_frontend(self.widget) self.window.init_menu_bar() # Ignore on OSX, where there is always a menu bar if sys.platform != 'darwin' and self.hide_menubar: self.window.menuBar().setVisible(False) self.window.setWindowTitle('Jupyter QtConsole')
def show_items(self, cursor, items, prefix_length=0): """ Shows the completion widget with 'items' at the position specified by 'cursor'. """ text_edit = self._text_edit point = self._get_top_left_position(cursor) self.clear() for item in items: list_item = QtGui.QListWidgetItem() list_item.setData(QtCore.Qt.UserRole, item) list_item.setText(item.split('.')[-1]) self.addItem(list_item) height = self.sizeHint().height() screen_rect = QtGui.QApplication.desktop().availableGeometry(self) if (screen_rect.size().height() + screen_rect.y() - point.y() - height < 0): point = text_edit.mapToGlobal(text_edit.cursorRect().topRight()) point.setY(point.y() - height) w = (self.sizeHintForColumn(0) + self.verticalScrollBar().sizeHint().width()) self.setGeometry(point.x(), point.y(), w, height) # Move cursor to start of the prefix to replace it # when a item is selected cursor.movePosition(QtGui.QTextCursor.Left, n=prefix_length) self._start_position = cursor.position() self.setCurrentRow(0) self.raise_() self.show()
def _insert_img(self, cursor, img, fmt, metadata=None): """ insert a raw image, jpg or png """ if metadata: width = metadata.get('width', None) height = metadata.get('height', None) else: width = height = None try: image = QtGui.QImage() image.loadFromData(img, fmt.upper()) if width and height: image = image.scaled(width, height, QtCore.Qt.IgnoreAspectRatio, QtCore.Qt.SmoothTransformation) elif width and not height: image = image.scaledToWidth(width, QtCore.Qt.SmoothTransformation) elif height and not width: image = image.scaledToHeight(height, QtCore.Qt.SmoothTransformation) except ValueError: self._insert_plain_text(cursor, 'Received invalid %s data.' % fmt) else: format = self._add_image(image) cursor.insertBlock() cursor.insertImage(format) cursor.insertBlock()
def initUI(self): """ Initialise the user-interface elements """ # Create the main-frame widget, and the layout self.mainFrame = QtGui.QWidget() self.setCentralWidget(self.mainFrame) self.hbox = QtGui.QHBoxLayout() # HBox contains all widgets # Create the menu action items self.openParTimAction = QtGui.QAction('&Open par/tim', self) self.openParTimAction.setShortcut('Ctrl+O') self.openParTimAction.setStatusTip('Open par/tim') self.openParTimAction.triggered.connect(self.openParTim) self.openParPerAction = QtGui.QAction('Open &par/bestprof', self) self.openParPerAction.setShortcut('Ctrl+G') self.openParPerAction.setStatusTip('Open par/bestprof files') self.openParPerAction.triggered.connect(self.openParPer) self.openPerAction = QtGui.QAction('Open &bestprof', self) self.openPerAction.setShortcut('Ctrl+H') self.openPerAction.setStatusTip('Open bestprof files') self.openPerAction.triggered.connect(self.openPer) self.exitAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&Exit', self) self.exitAction.setShortcut('Ctrl+Q') self.exitAction.setStatusTip('Exit application') self.exitAction.triggered.connect(self.close) self.toggleBinaryAction = QtGui.QAction('&Binary', self) self.toggleBinaryAction.setShortcut('Ctrl+B') self.toggleBinaryAction.setStatusTip('Toggle binary widget') self.toggleBinaryAction.triggered.connect(self.toggleBinary) self.togglePlkAction = QtGui.QAction('&Plk', self) self.togglePlkAction.setShortcut('Ctrl+P') self.togglePlkAction.setStatusTip('Toggle plk widget') self.togglePlkAction.triggered.connect(self.togglePlk) self.toggleIPythonAction = QtGui.QAction('&IPython', self) self.toggleIPythonAction.setShortcut('Ctrl+I') self.toggleIPythonAction.setStatusTip('Toggle IPython') self.toggleIPythonAction.triggered.connect(self.toggleIPython) self.aboutAction = QtGui.QAction('&About', self) self.aboutAction.setShortcut('Ctrl+A') self.aboutAction.setStatusTip('About Qtip') self.aboutAction.triggered.connect(self.onAbout) self.theStatusBar = QtGui.QStatusBar() #self.statusBar() self.setStatusBar(self.theStatusBar) self.engine_label = QtGui.QLabel("Tempo2") self.engine_label.setFrameStyle( QtGui.QFrame.Sunken|QtGui.QFrame.Panel) self.engine_label.setLineWidth(4) self.engine_label.setMidLineWidth(4) self.engine_label.setStyleSheet("QLabel{color:black;background-color:red}") self.theStatusBar.addPermanentWidget(self.engine_label) # On OSX, make sure the menu can be displayed (in the window itself) if sys.platform == 'darwin': # On OSX, the menubar is usually on the top of the screen, not in # the window. To make it in the window: QtGui.qt_mac_set_native_menubar(False) # Otherwise, if we'd like to get the system menubar at the top, then # we need another menubar object, not self.menuBar as below. In that # case, use: # self.menubar = QtGui.QMenuBar() # TODO: Somehow this does not work. Per-window one does though # Create the menu self.menubar = self.menuBar() self.fileMenu = self.menubar.addMenu('&File') self.fileMenu.addAction(self.openParTimAction) self.fileMenu.addAction(self.openParPerAction) self.fileMenu.addAction(self.openPerAction) self.fileMenu.addAction(self.exitAction) self.viewMenu = self.menubar.addMenu('&View') self.viewMenu.addAction(self.toggleBinaryAction) self.viewMenu.addAction(self.togglePlkAction) self.viewMenu.addAction(self.toggleIPythonAction) self.helpMenu = self.menubar.addMenu('&Help') self.helpMenu.addAction(self.aboutAction) # What is the status quo of the user interface? self.showIPython = False self.whichWidget = 'None' self.prevShowIPython = None self.prevWhichWidget = 'None'
def initUI(self): """Initialise the user-interface elements""" # Create the main-frame widget, and the layout self.mainFrame = QtGui.QWidget() self.setCentralWidget(self.mainFrame) self.hbox = QtGui.QHBoxLayout() # HBox contains all widgets # Menu item: open par/tim files self.openParTimAction = QtGui.QAction('&Open par/tim', self) self.openParTimAction.setShortcut('Ctrl+O') self.openParTimAction.setStatusTip('Open par/tim') self.openParTimAction.triggered.connect(self.openParTim) # Menu item: exit Qtip self.exitAction = QtGui.QAction(QtGui.QIcon('exit.png'), '&Exit', self) self.exitAction.setShortcut('Ctrl+Q') self.exitAction.setStatusTip('Exit application') self.exitAction.triggered.connect(self.close) # Previously, it was possible to switch out the 'plk' widget for another # main widget (the binary pulsar one). That one has been stripped out # now, so for now it makes no sense to 'toggle' on or off the plk # widget. However, the option is still there for now... self.togglePlkAction = QtGui.QAction('&Plk', self) self.togglePlkAction.setShortcut('Ctrl+P') self.togglePlkAction.setStatusTip('Toggle plk widget') self.togglePlkAction.triggered.connect(self.togglePlk) # Menu item: toggle the Jupyter window self.toggleJupyterAction = QtGui.QAction('&Jupyter', self) self.toggleJupyterAction.setShortcut('Ctrl+J') self.toggleJupyterAction.setStatusTip('Toggle Jupyter') self.toggleJupyterAction.triggered.connect(self.toggleJupyter) # Menu item: about Qtip self.aboutAction = QtGui.QAction('&About', self) self.aboutAction.setShortcut('Ctrl+A') self.aboutAction.setStatusTip('About Qtip') self.aboutAction.triggered.connect(self.onAbout) # The status bar self.theStatusBar = QtGui.QStatusBar() #self.statusBar() self.setStatusBar(self.theStatusBar) # A label that shows what engine is being used (hardcoded: PINT) self.engine_label = QtGui.QLabel("PINT") self.engine_label.setFrameStyle( QtGui.QFrame.Sunken|QtGui.QFrame.Panel) self.engine_label.setLineWidth(4) self.engine_label.setMidLineWidth(4) self.engine_label.setStyleSheet("QLabel{color:black;background-color:red}") self.theStatusBar.addPermanentWidget(self.engine_label) # On OSX, make sure the menu can be displayed (in the window itself) if sys.platform == 'darwin': # On OSX, the menubar is usually on the top of the screen, not in # the window. To make it in the window: QtGui.qt_mac_set_native_menubar(False) # Otherwise, if we'd like to get the system menubar at the top, then # we need another menubar object, not self.menuBar as below. In that # case, use: # self.menubar = QtGui.QMenuBar() # TODO: Somehow this does not work. Per-window one does though # Create the menu bar, and link the action items self.menubar = self.menuBar() self.fileMenu = self.menubar.addMenu('&File') self.fileMenu.addAction(self.openParTimAction) self.fileMenu.addAction(self.exitAction) self.viewMenu = self.menubar.addMenu('&View') self.viewMenu.addAction(self.togglePlkAction) self.viewMenu.addAction(self.toggleJupyterAction) self.helpMenu = self.menubar.addMenu('&Help') self.helpMenu.addAction(self.aboutAction) # What is the status quo of the user interface? self.showJupyter = False self.whichWidget = 'None' self.prevShowJupyter = None self.prevWhichWidget = 'None'