def decoration(self, index): """Defines the decoration of the node. Tries to load a banner from the URL, defined by :py:meth:`banner_url`, sets a default image while loading and in case the attempt to obtain a banner was unsuccesful. If a banner has been cached for the given URL, the cached image will be used instead. :param index: The index referring to the node to get decoration for. :type index: :class:`~.PySide.QtCore.QModelIndex` :returns: The :class:`PySide.QtGui.Pixmap` to use as the node's decoration. """ pixmap = QPixmap() banner_url = self.banner_url() if banner_url: placeholder = ":/icons/image-loading.png" fetch = True else: banner_url = placeholder = ":/icons/image-missing.png" fetch = False if not pixmap_cache.find(banner_url, pixmap): if fetch: banner_loader.fetch_banner(banner_url, index, self._cache) pixmap.load(placeholder) if self._scale: pixmap = pixmap.scaled(self._scale, Qt.AspectRatioMode.KeepAspectRatio) pixmap_cache.insert(banner_url, pixmap) return pixmap
def convert_bitmap(image, width=None, height=None): pix = None if isinstance(image, ImageResource): pix = traitsui_convert_bitmap(image) elif isinstance(image, Image): # image = image.convert('RGBA') data = image.tostring('raw', 'RGBA') im = QImage(data, image.size[0], image.size[1], QImage.Format_ARGB32) pix = QPixmap.fromImage(QImage.rgbSwapped(im)) else: s = image.shape if len(s) >= 2: # im = QImage(image.tostring(),s[1], s[0], QImage.Format_RGB888) im = QImage(image, s[1], s[0], QImage.Format_RGB888) pix = QPixmap.fromImage(QImage.rgbSwapped(im)) else: pix = QPixmap() if pix: if width > 0 and height > 0: pix = pix.scaled(width, height) elif width > 0: pix = pix.scaledToWidth(width) if height > 0: pix = pix.scaledToHeight(height) return pix
def apply(self, value): if isinstance(value, basestring): value = QPixmap(value) assert isinstance(value, QPixmap), "Image bridge must be assigned a pixmap" if self.width and self.height: value = value.scaled(self.width, self.height) self.widget.setPixmap(value)
def paintEvent(self, pe): painter = QPainter(self) icon = QPixmap(self._icon) icon = icon.scaled(self.size(), Qt.IgnoreAspectRatio) if not self._mouse_over or not self._enabled: painter.setOpacity(self._normal_opacity) else: painter.setOpacity(self._hover_opacity) painter.drawPixmap(0, 0, icon)
def paintEvent(self, pe): if self._mouse_over: icon = self._hover_icon else: icon = self._normal_icon painter = QPainter(self) pixmap = QPixmap(icon) pixmap = pixmap.scaled(self.size(), Qt.IgnoreAspectRatio) painter.drawPixmap(0, 0, pixmap)
def paint(self, painter, option, index): if index.column() != 0: # not the image column super(ScrapeItemDelegate, self).paint(painter, option, index) else: images = index.data(role=Qt.DisplayRole) if images: # yep. Make an image appear here image_data = images[0] # assuming a single image for now pixmap = QPixmap(image_data.get("path")) pixmap = pixmap.scaled(self.max_cell_res[0], self.max_cell_res[1], Qt.IgnoreAspectRatio) cell_rect = option.rect painter.drawPixmap(cell_rect.x(), cell_rect.y(), pixmap) else: super(ScrapeItemDelegate, self).paint(painter, option, index)
def fill_ranking(self): rank = self.generation.ranking best = rank.ranking[0] rest = rank.ranking[1:] rx = QRegExp("pok\d+") best_pokelabels = self.ranking.findChildren(QtGui.QLabel, rx) for idx, pokename in enumerate(best.team_names): pixmap = QPixmap("./sprites/" + pokename + ".png") pixmap = pixmap.scaled(60, 40, QtCore.Qt.KeepAspectRatio) best_pokelabels[idx].setPixmap(pixmap) rx = QRegExp("poketeam_\d+") pop_teams = self.ranking.findChildren(QtGui.QWidget, rx) for g in range(len(rest)): plabel = pop_teams[g].findChildren(QtGui.QLabel) for idx, pokename in enumerate(rest[g].team_names): pixmap = QPixmap("./sprites/" + pokename + ".png") plabel[idx].setPixmap(pixmap)
def fill_ranking(self): rank = self.generation.ranking best = rank.ranking[0] rest = rank.ranking[1:] rx = QRegExp("pok\d+") best_pokelabels = self.ranking.findChildren(QtGui.QLabel, rx) for idx, pokename in enumerate(best.team_names): pixmap = QPixmap("./sprites/" + pokename + ".png") pixmap = pixmap.scaled(60, 40, QtCore.Qt.KeepAspectRatio) best_pokelabels[idx].setPixmap(pixmap) rx = QRegExp("poketeam_\d+") pop_teams = self.ranking.findChildren(QtGui.QWidget, rx) for g in range(len(rest)): plabel = pop_teams[g].findChildren(QtGui.QLabel) for idx, pokename in enumerate(rest[g].team_names): pixmap = QPixmap("./sprites/" + pokename + ".png") plabel[idx].setPixmap(pixmap)
def convert_bitmap(image, width=None, height=None): if isinstance(image, ImageResource): pix = traitsui_convert_bitmap(image) elif isinstance(image, Image): data = image.tostring('raw', 'RGBA') im = QImage(data, image.size[0], image.size[1], QImage.Format_ARGB32) pix = QPixmap.fromImage(QImage.rgbSwapped(im)) else: s = image.shape if len(s) >= 2: pix = QPixmap.fromImage(array2qimage(image)) else: pix = QPixmap() if pix: if width > 0 and height > 0: pix = pix.scaled(width, height) elif width > 0: pix = pix.scaledToWidth(width) if height > 0: pix = pix.scaledToHeight(height) return pix
def requestPixmap(self, name, rsize, size): """@reimp @public @param[in] providerId unicode unused @param[out] rsize QSize @param[in] size QSize @return QPixmap not None virtual QPixmap requestPixmap(const QString &id, QSize *size, const QSize &requestedSize) """ ret = QPixmap(rc.image_path(name)) if ret.isNull(): derror("failed to load image: '%s'" % name) elif ret.size() != size: ret = ( ret.scaled(size, Qt.KeepAspectRatio, Qt.SmoothTransformation) if not size.isEmpty() else ret.scaledToWidth( size.width(), Qt.SmoothTransformation) if size.width() > 0 else ret.scaledToHeight(size.height(), Qt.SmoothTransformation) if size.height() > 0 else ret) rsize.setWidth(ret.width()) rsize.setHeight(ret.height()) return ret
class ImageWidget(QWidget): """ A widget that displays an image. """ def __init__(self, imagePath, fill=True, parent=None): """ Args: imagePath : a system path that points to an image fles fill : boolean that when True, makes the image fill the widget, whatever the current widget size. When False, just draws the image at it's original size. """ super(ImageWidget, self).__init__(parent) assert imagePath != None, self.tr("Invalid image path") self._image_pixmap = QPixmap(path.normpath(imagePath)) self._fill = fill def paintEvent(self, pe): painter = QPainter(self) if self._fill: scaled_pixmap = self._image_pixmap.scaled(self.size(), Qt.IgnoreAspectRatio) painter.drawPixmap(0, 0, scaled_pixmap) else: painter.drawPixmap(0, 0, self._image_pixmap)
class MdiArea(QMdiArea): # MdiArea::MdiArea(MainWindow* mw, QWidget *parent) : QMdiArea(parent), mainWin(mw) """ Subclass of `QMdiArea`_ TOWRITE """ def __init__(self, mw, parent=None): """ Default class constructor. :param `mw`: Pointer to a application main window instance. :type `mw`: `MainWindow`_ :param `parent`: Pointer to a parent widget instance. :type `parent`: `QWidget`_ """ super(MdiArea, self).__init__(parent) self.mainWin = mw self.gSpiralsImgPath = mw.gImgDir + os.sep + 'texture-spirals.png' self.gLogoSpiralsImgPath = mw.gImgDir + os.sep + 'logo-spirals.png' try: #if QT_VERSION >= 0x040800 self.setTabsClosable(True) except AttributeError: pass self.useLogo = False self.useTexture = False self.useColor = False self.bgLogo = QPixmap() self.bgTexture = QPixmap(self.gSpiralsImgPath) self.bgColor = QColor() self.bgLogo = QPixmap(self.gLogoSpiralsImgPath) # Brushes self.colorBrush = QBrush(QColor(EMBROIDERBLUE1)) self.backgroundBrush = QBrush(QPixmap(self.gSpiralsImgPath)) linearGrad = QLinearGradient(QPointF(0, 0), QPointF(400, 400)) linearGrad.setColorAt(0, QColor(EMBROIDERBLUE1)) linearGrad.setColorAt(1, QColor(EMBROIDERBLUE2)) self.gradientBrush = QBrush(linearGrad) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.setActivationOrder(QMdiArea.ActivationHistoryOrder) self.setFocusPolicy(Qt.WheelFocus) self.setFocus() self.setAcceptDrops(True) self.doSetDocumentMode(True) def __del__(self): """Class destructor.""" qDebug("MdiArea Destructor") def useBackgroundLogo(self, use): """ TOWRITE :param `use`: TOWRITE :type `use`: bool """ self.useLogo = use self.forceRepaint() def useBackgroundTexture(self, use): """ TOWRITE :param `use`: TOWRITE :type `use`: bool """ self.useTexture = use self.forceRepaint() def useBackgroundColor(self, use): """ TOWRITE :param `use`: TOWRITE :type `use`: bool """ self.useColor = use self.forceRepaint() def setBackgroundLogo(self, fileName): """ TOWRITE :param `fileName`: TOWRITE :type `fileName`: QString """ self.bgLogo.load(fileName) self.forceRepaint() def setBackgroundTexture(self, fileName): """ TOWRITE :param `fileName`: TOWRITE :type `fileName`: QString """ self.bgTexture.load(fileName) self.forceRepaint() def setBackgroundColor(self, color): """ TOWRITE :param `color`: TOWRITE :type `color`: `QColor`_ """ if not color: # .isValid() self.bgColor = self.background().color() else: self.bgColor = color self.forceRepaint() def mouseDoubleClickEvent(self, event): """ Handles the ``mouseDoubleClickEvent`` event for :class:`MdiArea`. :param `event`: A `QMouseEvent`_ to be processed. """ qDebug('%s' % event.button()) evtBtn = event.button() if evtBtn == Qt.LeftButton: # return 1 self.mainWin.openFile() elif evtBtn == Qt.RightButton: # return 2 qDebug('DoubleRightClick') elif evtBtn == Qt.MiddleButton: # return 4 qDebug('DoubleMiddleClick') elif evtBtn == Qt.XButton1: # Aux1 return 8 qDebug('DoubleAux1Click') elif evtBtn == Qt.XButton2: # Aux2 return 16 qDebug('DoubleAux2Click') ## def paintEvent(self, event): ## """ ## Handles the ``paintEvent`` event for :class:`MdiArea`. ## ## :param `event`: A `QPaintEvent`_ to be processed. ## """ ## vport = self.viewport() # QWidget* ## rect = vport.rect() # QRect ## ## painter = QPainter(vport) ## painter.setRenderHint(QPainter.SmoothPixmapTransform) ## ## # Always fill with a solid color first. ## if self.useColor: ## painter.fillRect(rect, self.bgColor) ## else: ## painter.fillRect(rect, self.background()) ## ## # Then overlay the texture. ## if self.useTexture: ## bgBrush = QBrush(self.bgTexture) ## painter.fillRect(rect, bgBrush) ## ## # Overlay the logo last. ## if self.useLogo: ## bgLogo = self.bgLogo ## # Center the pixmap. ## dx = (rect.width() - bgLogo.width()) / 2 # int ## dy = (rect.height() - bgLogo.height()) / 2 # int ## painter.drawPixmap(dx, dy, bgLogo.width(), bgLogo.height(), bgLogo) def paintEvent(self, event): """ Handles the ``paintEvent`` event for :class:`MdiArea`. :param `event`: A `QPaintEvent`_ to be processed. """ vport = self.viewport() rect = vport.rect() painter = QPainter(vport) painter.setRenderHint(painter.SmoothPixmapTransform) # Always fill with a solid color first if self.useColor: # painter.fillRect(rect, self.colorBrush) painter.fillRect(rect, self.bgColor) else: painter.fillRect(rect, self.background()) # Then overlay the texture if self.useTexture: # painter.fillRect(rect, self.backgroundBrush) bgBrush = QBrush(self.bgTexture) painter.fillRect(rect, bgBrush) # Overlay the logo last if self.useLogo: if not len(self.subWindowList()): # Nothing is open. cSizeW, cSizeH = rect.width(), rect.height() bgLogoW, bgLogoH = self.bgLogo.width(), self.bgLogo.height() if bgLogoW > cSizeW: # Proportional Scaling an Image. newHeight = bgLogoH * cSizeW // bgLogoW scaledLogo = self.bgLogo.scaled(cSizeW, newHeight) painter.drawPixmap(0, cSizeH // 2 - scaledLogo.height() // 2, scaledLogo) else: painter.drawPixmap((cSizeW - bgLogoW) // 2, (cSizeH - bgLogoH) // 2, self.bgLogo) else: # Center the pixmap dx = (rect.width() - self.bgLogo.width()) / 2 dy = (rect.height() - self.bgLogo.height()) / 2 painter.drawPixmap(dx, dy, self.bgLogo.width(), self.bgLogo.height(), self.bgLogo) def zoomExtentsAllSubWindows(self): """ TOWRITE """ for window in self.subWindowList(): # foreach(QMdiSubWindow* window, subWindowList()) mdiWin = window # MdiWindow* mdiWin = qobject_cast<MdiWindow*>(window); if mdiWin: v = mdiWin.getView() # View* if v: v.recalculateLimits() v.zoomExtents() def forceRepaint(self): """ TOWRITE """ # HACK: Take that QMdiArea! hack = self.size() # QSize self.resize(hack + QSize(1, 1)) self.resize(hack) def moveEvent(self, event): """ Handles the ``moveEvent`` event for :class:`MDIArea`. :param `event`: A `QMoveEvent`_ to be processed. """ # Dragging while MouseButton is down. qDebug("QMdiArea moveEvent") def contextMenuEvent(self, event): """ Handles the ``contextMenuEvent`` event for :class:`MDIArea`. :param `event`: A `QContextMenuEvent`_ to be processed. """ mainWin = self.mainWin if not len(self.subWindowList()): # Nothing is open. # Build a menu suitable for the startup screen. menu = QMenu(self) menu.addAction(mainWin.actionHash["ACTION_new"]) menu.addAction(mainWin.actionHash["ACTION_open"]) menu.addAction(mainWin.actionHash["ACTION_settingsdialog"]) menu.addAction(mainWin.actionHash["ACTION_help"]) menu.addAction(mainWin.actionHash["ACTION_about"]) menu.addAction(mainWin.actionHash["ACTION_exit"]) menu.popup(self.mapToGlobal(event.pos())) # menu.exec_(self.mapToGlobal(event.pos())) else: # Build a menu suitable for when the mdi workspace is open. mainWin.fileMenu.popup(self.mapToGlobal(event.pos())) event.accept() qDebug("QMdiArea contextMenuEvent") def doSetDocumentMode(self, enabled=False): """ Set the document mode for :class:`MDIArea`. :param `enabled`: Whether the tab bar is set to document mode in tabbed view mode. Document mode is disabled by default. :type `enabled`: bool """ self.setDocumentMode(enabled) # Slots ------------------------------------------------------------------ @Slot() def cascade(self): """ TOWRITE """ self.cascadeSubWindows() self.zoomExtentsAllSubWindows() @Slot() def tile(self): """ TOWRITE """ self.tileSubWindows() self.zoomExtentsAllSubWindows()
if 'coords' in self.flags: print('x: {:.2f} {}'.format(x * scale, units)) print('y: {:.2f} {}'.format(y * scale, units)) print('angle: {:.2f} degrees'.format(angle)) def draw_line(self, linef): line = QGraphicsLineItem(linef) line.setPen(QPen(QBrush(QColor(0, 0, 0)), 1)) self.addItem(line) if __name__ == '__main__': app = QApplication(sys.argv) loader = QUiLoader() ui = loader.load('line_gui.ui') ui.show() pixmap = QPixmap(u'Top.jpg') pixmap = pixmap.scaled(2 * pixmap.size()) scene = GraphicsScene('tricavity', ['axis', 'coords'], scale_triplet=(.55, 3.04, 3.08)) pix_item = scene.addPixmap(pixmap) pix_item.setCursor(Qt.CrossCursor) layout = ui.findChild(QGridLayout, 'gridLayout') view = QGraphicsView(scene) layout.addWidget(view) app.exec_()
if 'coords' in self.flags: print('x: {:.2f} {}'.format(x*scale, units)) print('y: {:.2f} {}'.format(y*scale, units)) print('angle: {:.2f} degrees'.format(angle)) def draw_line(self, linef): line = QGraphicsLineItem(linef) line.setPen(QPen(QBrush(QColor(0, 0, 0)), 1)) self.addItem(line) if __name__ == '__main__': app = QApplication(sys.argv) loader = QUiLoader() ui = loader.load('line_gui.ui') ui.show() pixmap = QPixmap(u'Top.jpg') pixmap = pixmap.scaled(2*pixmap.size()) scene = GraphicsScene('tricavity', ['axis', 'coords'], scale_triplet=(.55,3.04,3.08)) pix_item = scene.addPixmap(pixmap) pix_item.setCursor(Qt.CrossCursor) layout = ui.findChild(QGridLayout, 'gridLayout') view = QGraphicsView(scene) layout.addWidget(view) app.exec_()
class MdiArea( QMdiArea ): # MdiArea::MdiArea(MainWindow* mw, QWidget *parent) : QMdiArea(parent), mainWin(mw) """ Subclass of `QMdiArea`_ TOWRITE """ def __init__(self, mw, parent=None): """ Default class constructor. :param `mw`: Pointer to a application main window instance. :type `mw`: `MainWindow`_ :param `parent`: Pointer to a parent widget instance. :type `parent`: `QWidget`_ """ super(MdiArea, self).__init__(parent) self.mainWin = mw self.gSpiralsImgPath = mw.gImgDir + os.sep + 'texture-spirals.png' self.gLogoSpiralsImgPath = mw.gImgDir + os.sep + 'logo-spirals.png' try: #if QT_VERSION >= 0x040800 self.setTabsClosable(True) except AttributeError: pass self.useLogo = False self.useTexture = False self.useColor = False self.bgLogo = QPixmap() self.bgTexture = QPixmap(self.gSpiralsImgPath) self.bgColor = QColor() self.bgLogo = QPixmap(self.gLogoSpiralsImgPath) # Brushes self.colorBrush = QBrush(QColor(EMBROIDERBLUE1)) self.backgroundBrush = QBrush(QPixmap(self.gSpiralsImgPath)) linearGrad = QLinearGradient(QPointF(0, 0), QPointF(400, 400)) linearGrad.setColorAt(0, QColor(EMBROIDERBLUE1)) linearGrad.setColorAt(1, QColor(EMBROIDERBLUE2)) self.gradientBrush = QBrush(linearGrad) self.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.setActivationOrder(QMdiArea.ActivationHistoryOrder) self.setFocusPolicy(Qt.WheelFocus) self.setFocus() self.setAcceptDrops(True) self.doSetDocumentMode(True) def __del__(self): """Class destructor.""" qDebug("MdiArea Destructor") def useBackgroundLogo(self, use): """ TOWRITE :param `use`: TOWRITE :type `use`: bool """ self.useLogo = use self.forceRepaint() def useBackgroundTexture(self, use): """ TOWRITE :param `use`: TOWRITE :type `use`: bool """ self.useTexture = use self.forceRepaint() def useBackgroundColor(self, use): """ TOWRITE :param `use`: TOWRITE :type `use`: bool """ self.useColor = use self.forceRepaint() def setBackgroundLogo(self, fileName): """ TOWRITE :param `fileName`: TOWRITE :type `fileName`: QString """ self.bgLogo.load(fileName) self.forceRepaint() def setBackgroundTexture(self, fileName): """ TOWRITE :param `fileName`: TOWRITE :type `fileName`: QString """ self.bgTexture.load(fileName) self.forceRepaint() def setBackgroundColor(self, color): """ TOWRITE :param `color`: TOWRITE :type `color`: `QColor`_ """ if not color: # .isValid() self.bgColor = self.background().color() else: self.bgColor = color self.forceRepaint() def mouseDoubleClickEvent(self, event): """ Handles the ``mouseDoubleClickEvent`` event for :class:`MdiArea`. :param `event`: A `QMouseEvent`_ to be processed. """ qDebug('%s' % event.button()) evtBtn = event.button() if evtBtn == Qt.LeftButton: # return 1 self.mainWin.openFile() elif evtBtn == Qt.RightButton: # return 2 qDebug('DoubleRightClick') elif evtBtn == Qt.MiddleButton: # return 4 qDebug('DoubleMiddleClick') elif evtBtn == Qt.XButton1: # Aux1 return 8 qDebug('DoubleAux1Click') elif evtBtn == Qt.XButton2: # Aux2 return 16 qDebug('DoubleAux2Click') ## def paintEvent(self, event): ## """ ## Handles the ``paintEvent`` event for :class:`MdiArea`. ## ## :param `event`: A `QPaintEvent`_ to be processed. ## """ ## vport = self.viewport() # QWidget* ## rect = vport.rect() # QRect ## ## painter = QPainter(vport) ## painter.setRenderHint(QPainter.SmoothPixmapTransform) ## ## # Always fill with a solid color first. ## if self.useColor: ## painter.fillRect(rect, self.bgColor) ## else: ## painter.fillRect(rect, self.background()) ## ## # Then overlay the texture. ## if self.useTexture: ## bgBrush = QBrush(self.bgTexture) ## painter.fillRect(rect, bgBrush) ## ## # Overlay the logo last. ## if self.useLogo: ## bgLogo = self.bgLogo ## # Center the pixmap. ## dx = (rect.width() - bgLogo.width()) / 2 # int ## dy = (rect.height() - bgLogo.height()) / 2 # int ## painter.drawPixmap(dx, dy, bgLogo.width(), bgLogo.height(), bgLogo) def paintEvent(self, event): """ Handles the ``paintEvent`` event for :class:`MdiArea`. :param `event`: A `QPaintEvent`_ to be processed. """ vport = self.viewport() rect = vport.rect() painter = QPainter(vport) painter.setRenderHint(painter.SmoothPixmapTransform) # Always fill with a solid color first if self.useColor: # painter.fillRect(rect, self.colorBrush) painter.fillRect(rect, self.bgColor) else: painter.fillRect(rect, self.background()) # Then overlay the texture if self.useTexture: # painter.fillRect(rect, self.backgroundBrush) bgBrush = QBrush(self.bgTexture) painter.fillRect(rect, bgBrush) # Overlay the logo last if self.useLogo: if not len(self.subWindowList()): # Nothing is open. cSizeW, cSizeH = rect.width(), rect.height() bgLogoW, bgLogoH = self.bgLogo.width(), self.bgLogo.height() if bgLogoW > cSizeW: # Proportional Scaling an Image. newHeight = bgLogoH * cSizeW // bgLogoW scaledLogo = self.bgLogo.scaled(cSizeW, newHeight) painter.drawPixmap(0, cSizeH // 2 - scaledLogo.height() // 2, scaledLogo) else: painter.drawPixmap((cSizeW - bgLogoW) // 2, (cSizeH - bgLogoH) // 2, self.bgLogo) else: # Center the pixmap dx = (rect.width() - self.bgLogo.width()) / 2 dy = (rect.height() - self.bgLogo.height()) / 2 painter.drawPixmap(dx, dy, self.bgLogo.width(), self.bgLogo.height(), self.bgLogo) def zoomExtentsAllSubWindows(self): """ TOWRITE """ for window in self.subWindowList( ): # foreach(QMdiSubWindow* window, subWindowList()) mdiWin = window # MdiWindow* mdiWin = qobject_cast<MdiWindow*>(window); if mdiWin: v = mdiWin.getView() # View* if v: v.recalculateLimits() v.zoomExtents() def forceRepaint(self): """ TOWRITE """ # HACK: Take that QMdiArea! hack = self.size() # QSize self.resize(hack + QSize(1, 1)) self.resize(hack) def moveEvent(self, event): """ Handles the ``moveEvent`` event for :class:`MDIArea`. :param `event`: A `QMoveEvent`_ to be processed. """ # Dragging while MouseButton is down. qDebug("QMdiArea moveEvent") def contextMenuEvent(self, event): """ Handles the ``contextMenuEvent`` event for :class:`MDIArea`. :param `event`: A `QContextMenuEvent`_ to be processed. """ mainWin = self.mainWin if not len(self.subWindowList()): # Nothing is open. # Build a menu suitable for the startup screen. menu = QMenu(self) menu.addAction(mainWin.actionHash["ACTION_new"]) menu.addAction(mainWin.actionHash["ACTION_open"]) menu.addAction(mainWin.actionHash["ACTION_settingsdialog"]) menu.addAction(mainWin.actionHash["ACTION_help"]) menu.addAction(mainWin.actionHash["ACTION_about"]) menu.addAction(mainWin.actionHash["ACTION_exit"]) menu.popup(self.mapToGlobal(event.pos())) # menu.exec_(self.mapToGlobal(event.pos())) else: # Build a menu suitable for when the mdi workspace is open. mainWin.fileMenu.popup(self.mapToGlobal(event.pos())) event.accept() qDebug("QMdiArea contextMenuEvent") def doSetDocumentMode(self, enabled=False): """ Set the document mode for :class:`MDIArea`. :param `enabled`: Whether the tab bar is set to document mode in tabbed view mode. Document mode is disabled by default. :type `enabled`: bool """ self.setDocumentMode(enabled) # Slots ------------------------------------------------------------------ @Slot() def cascade(self): """ TOWRITE """ self.cascadeSubWindows() self.zoomExtentsAllSubWindows() @Slot() def tile(self): """ TOWRITE """ self.tileSubWindows() self.zoomExtentsAllSubWindows()
class HygieneReportPop(QDialog): """ The Report Form Handler """ def __init__(self, parent=None, code=None, table=None): super(HygieneReportPop, self).__init__() self.setup_pop() # do not change the order of these two function self.code = code self.parent_object = parent self.image_data = None self.process_override( table=table) # do not change the order of these two function if not code: self.update_button.setHidden(True) self.delete_button.setHidden(True) self.calculate_code() else: self.create_button.setHidden(True) self.update_data() def process_override(self, table): """ Function that assigns the table and tryton backend handler objects based on the tables :param table: the table name """ try: if table == 'pest_table': self.backend_handle = self.parent_object.pest self.table = self.parent_object.report_hyginepest_table elif table == 'water_table': self.backend_handle = self.parent_object.water self.table = self.parent_object.report_hyginewater_table elif table == 'health_table': self.backend_handle = self.parent_object.health self.table = self.parent_object.report_health_table except Exception: if settings.level == 10: logger.exception('raised exception') return False, 'Some Internal Error' def setup_pop(self): """ sets up the form. """ self.grid_layout = QGridLayout(self) self.label_1 = QLabel(self) self.grid_layout.addWidget(self.label_1, 0, 0, 1, 1) self.code_line = QLineEdit(self) self.code_line.setValidator(QIntValidator(0, 99999)) self.grid_layout.addWidget(self.code_line, 0, 1, 1, 1) self.label_2 = QLabel(self) self.grid_layout.addWidget(self.label_2, 1, 0, 1, 1) self.date_line = QDateEdit(self) self.date_line.setCalendarPopup(True) self.grid_layout.addWidget(self.date_line, 1, 1, 1, 1) self.label_3 = QLabel(self) self.grid_layout.addWidget(self.label_3, 2, 0, 1, 1) self.organization_line = QLineEdit(self) self.grid_layout.addWidget(self.organization_line, 2, 1, 1, 1) self.label_4 = QLabel(self) self.grid_layout.addWidget(self.label_4, 3, 0, 1, 1) self.test_line = QLineEdit(self) self.grid_layout.addWidget(self.test_line, 3, 1, 1, 1) self.label_5 = QLabel(self) self.grid_layout.addWidget(self.label_5, 4, 0, 1, 1) self.description_line = QLineEdit(self) self.grid_layout.addWidget(self.description_line, 4, 1, 1, 1) self.image_label = QLabel(self) self.pixmap = QPixmap(':/images/upload.png') # self.pixmap.scaled(self.image_label.size(), Qt.KeepAspectRatio, Qt.FastTransformation) #not used self.image_label.setPixmap(self.pixmap) self.image_label.setScaledContents(True) self.grid_layout.addWidget(self.image_label, 0, 2, 5, 2) self.horizontal = QHBoxLayout() self.delete_button = QPushButton(self) self.horizontal.addWidget(self.delete_button) self.create_button = QPushButton(self) self.horizontal.addWidget(self.create_button) self.update_button = QPushButton(self) self.horizontal.addWidget(self.update_button) self.upload_button = QPushButton(self) self.horizontal.addWidget(self.upload_button) self.grid_layout.addLayout(self.horizontal, 5, 0, 1, 4) ### retanslate self.label_1.setText( QApplication.translate("MainWindow", "Code", None, QApplication.UnicodeUTF8)) self.label_2.setText( QApplication.translate("MainWindow", "Date", None, QApplication.UnicodeUTF8)) self.date_line.setDisplayFormat( QApplication.translate("MainWindow", "dd/MM/yyyy", None, QApplication.UnicodeUTF8)) self.label_3.setText( QApplication.translate("MainWindow", "Organization Name", None, QApplication.UnicodeUTF8)) self.label_4.setText( QApplication.translate("MainWindow", "Test", None, QApplication.UnicodeUTF8)) self.label_5.setText( QApplication.translate("MainWindow", "Description", None, QApplication.UnicodeUTF8)) self.delete_button.setText( QApplication.translate("MainWindow", "Delete", None, QApplication.UnicodeUTF8)) self.create_button.setText( QApplication.translate("MainWindow", "Create", None, QApplication.UnicodeUTF8)) self.update_button.setText( QApplication.translate("MainWindow", "Update", None, QApplication.UnicodeUTF8)) self.upload_button.setText( QApplication.translate("MainWindow", "Upload", None, QApplication.UnicodeUTF8)) self.create_button.clicked.connect(self.create_report) self.upload_button.clicked.connect(self.open_file) self.update_button.clicked.connect(self.update_report) self.delete_button.clicked.connect(self.delete_report) self.image_label.mouseReleaseEvent = self.image_viewer def update_data(self): """ Updates the data in the form """ try: data = self.backend_handle.read_report(code=int(self.code)) if data: if data[0]: data = data[1] self.code_line.setText(data['code']) self.code_line.setDisabled(True) self.date_line.setDate(data['date']) self.organization_line.setText(data['organization']) self.test_line.setText(data['test']) self.description_line.setText(data['description']) self.image_data = str(data['report']) self.pixmap = QPixmap() self.pixmap.loadFromData(self.image_data) self.image_label.setPixmap( self.pixmap.scaled(self.image_label.size(), Qt.KeepAspectRatio, Qt.FastTransformation)) except Exception: if settings.level == 10: logger.exception('raised exception') return False, 'Some Internal Error' def image_viewer(self, event=None): """pops up a image viewer to check the details""" dialog = QDialog() dialog.setWindowFlags(Qt.WindowTitleHint | Qt.WindowStaysOnTopHint) layout = QHBoxLayout(dialog) label = QLabel(dialog) # self.pixmap.scaled(self.image_label.size(), Qt.KeepAspectRatio, Qt.FastTransformation) label.setPixmap(self.pixmap) label.setScaledContents(True) layout.addWidget(label) dialog.exec_() def open_file(self): """ saves the file """ dialog = QFileDialog(self) dialog.setNameFilter("Image Files (*.png *.jpg *.bmp)") dialog.setStyleSheet('color:black;') name = '' if dialog.exec_(): name = dialog.selectedFiles() if name: self.image_data = open(name[0], 'rb').read() self.pixmap = QPixmap(name[0]) self.image_label.setPixmap( self.pixmap.scaled(self.image_label.size(), Qt.KeepAspectRatio, Qt.FastTransformation)) def create_report(self): """ Creates a new Report """ try: data = self.get_data() if data: status = self.backend_handle.create_report(data=data) if status: if status[0]: QMessageBox.information(self, 'Success', status[1], QMessageBox.Ok) self.create_button.setHidden(True) self.delete_button.setVisible(True) self.update_button.setVisible(True) self.code = data['code'] self.update_data() else: QMessageBox.critical(self, 'Error', status[1], QMessageBox.Ok) except Exception: if settings.level == 10: logger.exception('raised exception') return False, 'Some Internal Error' def update_report(self): """ Updates an existing Report """ try: data = self.get_data() if data: status = self.backend_handle.update_report(data=data) if status: if status[0]: QMessageBox.information(self, 'Success', status[1], QMessageBox.Ok) else: QMessageBox.critical(self, 'Error', status[1], QMessageBox.Ok) except Exception: if settings.level == 10: logger.exception('raised exception') return False, 'Some Internal Error' def get_data(self): """ Gets the data from the form as a dictionary :return:dictionary """ try: data = {} data['code'] = self.code_line.text() data['date'] = self.date_line.text() data['organization'] = self.organization_line.text() data['test'] = self.test_line.text() data['description'] = self.description_line.text() data['report'] = self.image_data for key, value in data.iteritems(): if not value: QMessageBox.critical( self, 'Error', 'Insert Proper value for %s' % key.title(), QMessageBox.Ok) return False return data except Exception: if settings.level == 10: logger.exception('raised exception') return False def delete_report(self): """ Deletes the existing report :return: """ try: code = self.code_line.text() status = self.backend_handle.delete_report(code=code) if status: if status[0]: QMessageBox.information(self, 'Success', status[1], QMessageBox.Ok) self.close() else: QMessageBox.critical(self, 'Error', status[1], QMessageBox.Ok) except Exception: if settings.level == 10: logger.exception('raised exception') return False, 'Some Internal Error' def calculate_code(self): """ Calculates the entry number, Eases the user for entering the code """ try: table = self.table if table: code = [] rows = table.rowCount() for row in range(rows): code.append(table.item(row, 0).text()) if code: new_code = str(int(max(code)) + 1) self.code_line.setText(new_code) except Exception: if settings.level == 10: logger.exception('raised exception') return False, 'Some Internal Error'