def addWidgets(self): opener = QLabel(self) self.pixmap_open = QPixmap(asset('png', 'triangle-open.png')) self.pixmap_closed = QPixmap(asset('png', 'triangle-closed.png')) opener.setPixmap(self.pixmap_open) opener.resize(opener.pixmap().size()) self.opener = opener self.setIndent(opener.width() + 12) self.setMargin(2)
class StatusBar: def __init__(self, parent): self._parent = parent self._statusTimer = QTimer(self._parent) self._parent.connect(self._statusTimer, SIGNAL("timeout()"), self._resetMessage) self._replaceStatusMessage = False self._lastStatusMessage = '' self._lastStatusPixmap = QPixmap() self._statusBar = parent.statusBar() self._statusLabel = QLabel(self._statusBar) self._pixmapLabel = QLabel(self._statusBar) self._pixmapLabel.setPixmap(self._lastStatusPixmap) self._statusBar.addWidget(self._pixmapLabel, 0) self._statusBar.addWidget(self._statusLabel, 1) def setMessage(self, message='', duration=0, pixmap=''): """Sets the status bar message label to message. if duration is > 0 than the message is displayed for duration seconds. if duration is > 0 then after duration seconds have elapsed, the previous message is displayed. """ replace = (duration > 0) self._statusTimer.stop() self._replaceStatusMessage = replace self._lastStatusMessage = self._statusLabel.text() self._lastStatusPixmap = self._pixmapLabel.pixmap().copy() self._statusLabel.setText(message) if duration > 0: self._statusTimer.start(1000 * duration) if pixmap: self._pixmapLabel.setPixmap(pixmap) def _resetMessage(self): self._statusTimer.stop() if self._replaceStatusMessage: self._statusLabel.setText(self._lastStatusMessage) self._pixmapLabel.setPixmap(self._lastStatusPixmap) else: self._statusLabel.setText('') self._pixmapLabel.setPixmap(QPixmap())
class EnhancedLineEdit(object): """Represents and enhanced lineedit. This class works on an already added lineedit to the widget so that we are just adding extra items to it. """ def __init__(self, line_edit, valid_cb=lambda x: False, warning_sign=False): """Create an instance.""" super(EnhancedLineEdit, self).__init__() self._line_edit = line_edit layout = QHBoxLayout(self._line_edit) layout.setMargin(0) self._line_edit.setLayout(layout) self.valid_cb = valid_cb layout.addStretch() self.clear_label = QLabel(self._line_edit) self.clear_label.setMargin(2) self.clear_label.setProperty("lineEditWarning", True) layout.addWidget(self.clear_label) self.clear_label.setMinimumSize(16, 16) self.clear_label.setVisible(False) self.clear_label.setCursor(QCursor(Qt.ArrowCursor)) if warning_sign: icon = QApplication.style().standardIcon( QStyle.SP_MessageBoxWarning) self.clear_label.setPixmap(icon.pixmap(16, 16)) # connect the change of text to the cation that will check if the # text is valid and if the icon should be shown. self._line_edit.textChanged.connect(self.show_button) def show_button(self, string): """Decide if we show the button or not.""" if not self.valid_cb(string) and self.clear_label.pixmap() is not None: self.clear_label.setVisible(True) else: self.clear_label.setVisible(False)
class NonstopViewer(QtGui.QDialog): def __init__(self, parent=None): super(NonstopViewer, self).__init__(parent) self.ui = Ui_Nonstop() self.ui.setupUi(self) self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.lines = [] self.ui.actionSaveImg = QtGui.QAction("Save image...", None, triggered=self.saveImage) self.ui.actionSaveImg.setShortcut("Ctrl+S") self.addAction(self.ui.actionSaveImg) def load(self, filename): self.nonstop = NonstopParser() self.nonstop.load(filename) if len(self.nonstop.script_pack) == 0: return self.bg = get_trial(self.nonstop.script_pack[0].scene_info, show_box=False, show_sprite=False) qt_pixmap = QtGui.QPixmap.fromImage(self.bg) self.ui.lblPreview.setPixmap(qt_pixmap) self.lines = [] for i in range(len(self.nonstop.lines)): if self.nonstop.script_pack[i].translated != "": text = self.nonstop.script_pack[i].original else: text = self.nonstop.script_pack[i].original text_img = get_text(text, common.SCENE_MODES.debate) self.lines.append(text_img) def play(self): line = 0 scene_info = self.nonstop.script_pack[line].scene_info sprite_id = scene_info.sprite sprite_id.sprite_type = SPRITE_TYPE.stand sprite = get_sprite(sprite_id) self.lblSprite = QLabel(self.ui.lblPreview) self.lblSprite.setGeometry(0, 0, 480, 272) qt_pixmap = QtGui.QPixmap.fromImage(sprite) self.lblSprite.setPixmap(qt_pixmap) line = 18 text_img = self.lines[line] line_info = self.nonstop.lines[line] matrix = QMatrix() matrix.rotate(line_info.rot_angle) matrix.scale(line_info.zoom_start / 100.0, line_info.zoom_start / 100.0) text_img = text_img.transformed(matrix, Qt.Qt.SmoothTransformation) x_start = line_info.x_start - (text_img.width() / 2.0) y_start = line_info.y_start - (text_img.height() / 2.0) x_vel = line_info.velocity * math.cos( math.radians(90 - line_info.angle)) y_vel = -line_info.velocity * math.sin( math.radians(90 - line_info.angle)) time_visible = line_info.time_visible / 60.0 width_start = text_img.width() height_start = text_img.height() width_end = width_start * ( (line_info.zoom_change / 100.0)**time_visible) height_end = height_start * ( (line_info.zoom_change / 100.0)**time_visible) x_end = x_start + (x_vel * time_visible) y_end = y_start + (y_vel * time_visible) #x_end = line_info.x_start + (x_vel * time_visible) - (width_end / 2.0) #y_end = line_info.y_start + (y_vel * time_visible) - (height_end / 2.0) print x_start, y_start, width_start, height_start, line_info.zoom_start print x_end, y_end, width_end, height_end self.lblText = QLabel(self.ui.lblPreview) self.lblText.setGeometry(x_start, y_start, text_img.width(), text_img.height()) #self.lblText2 = QLabel(self.ui.lblPreview) #self.lblText2.setGeometry(x_end, y_end, text_img.width(), text_img.height()) qt_pixmap = QtGui.QPixmap.fromImage(text_img) self.lblText.setPixmap(qt_pixmap) #self.lblText2.setPixmap(qt_pixmap) self.anim = QtCore.QPropertyAnimation(self.lblText, "geometry") self.anim.setDuration(time_visible * 1000) self.anim.setStartValue( QRectF(x_start, y_start, width_start, height_start)) self.anim.setEndValue(QRectF(x_end, y_end, width_start, height_start)) self.anim.start() ############################################################################## ### @fn saveImage() ### @desc Saves a preview image. :D ############################################################################## def saveImage(self): dir = "ss" index = 0 if not os.path.isdir(dir): if os.path.isfile(dir): return else: os.mkdir(dir) while True: if index >= 9999: return filename = os.path.join(dir, ("shot%04d.png" % index)) if not os.path.isfile(filename): break index = index + 1 if not os.path.isdir(dir): os.mkdir(dir) self.lblText.pixmap().save(filename)
class ScreenShot(QWidget): def __init__(self): super(ScreenShot, self).__init__() self.initUI() def initUI(self): self.originalPixmap = QPixmap() self.screenshotLabel = QLabel("screenshotlabel", self) self.screenshotLabel.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.screenshotLabel.setAlignment(Qt.AlignCenter) self.screenGeometry = QApplication.desktop().screenGeometry( ) # Qrect() print self.screenGeometry, self.screenGeometry.width() self.screenshotLabel.setMinimumSize(self.screenGeometry.width() / 8, self.screenGeometry.height() / 8) mainlayout = QVBoxLayout(self) mainlayout.addWidget(self.screenshotLabel) self.optionsGroupBox = QGroupBox(u"选项", self) self.hideThisWindowCheckBox = QCheckBox(u"隐藏这个窗口", self.optionsGroupBox) self.optionsGroupBoxLayout = QGridLayout(self.optionsGroupBox) mainlayout.addWidget(self.optionsGroupBox) self.delaySpinBox = QSpinBox(self.optionsGroupBox) self.delaySpinBox.setSuffix(u"s") self.delaySpinBox.setMaximum(60) self.optionsGroupBoxLayout.addWidget(QLabel(u"截屏延时:", self), 0, 0) self.optionsGroupBoxLayout.addWidget(self.delaySpinBox, 0, 1) self.optionsGroupBoxLayout.addWidget(self.hideThisWindowCheckBox, 1, 0) buttonLayout = QHBoxLayout() self.newScreenshotButton = QPushButton(u"新截图", self) self.newScreenshotButton.clicked.connect(self.__newScreenshot) buttonLayout.addWidget(self.newScreenshotButton) saveScreenshotButton = QPushButton(u"保存截图", self) buttonLayout.addWidget(saveScreenshotButton) quitScreenshotButton = QPushButton(u"退出截图", self) quitScreenshotButton.setShortcut("Ctrl+Q") buttonLayout.addWidget(saveScreenshotButton) buttonLayout.addStretch() mainlayout.addLayout(buttonLayout) quitScreenshotButton.clicked.connect(self.close) saveScreenshotButton.clicked.connect(self.__saveScreenshot) self.delaySpinBox.valueChanged.connect(self.__updateCheckBox) self.delaySpinBox.setValue(5) self.setWindowTitle(u"截图") self.resize(300, 200) def resizeEvent(self, QResizeEvent): scaledSize = self.originalPixmap.size() scaledSize.scale(self.screenshotLabel.size(), Qt.KeepAspectRatio) if (not self.screenshotLabel.pixmap()) or ( scaledSize != self.screenshotLabel.pixmap().size()): self.__updateScreenshotLabel() def __newScreenshot(self): if self.hideThisWindowCheckBox.isChecked(): self.hide() self.newScreenshotButton.setDisabled(True) QTimer.singleShot(self.delaySpinBox.value() * 1000, self.__shootScreen) def __saveScreenshot(self): format = "png" initialPath = QDesktopServices.storageLocation( QDesktopServices.PicturesLocation) # initialPath = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation); if initialPath.isEmpty(): initialPath = QDir.currentPath() initialPath += "/untitled." + format fileDialog = QtGui.QFileDialog(self, u"存储为", initialPath) fileDialog.setAcceptMode(QtGui.QFileDialog.AcceptSave) fileDialog.setFileMode(QtGui.QFileDialog.AnyFile) fileDialog.setDirectory(initialPath) mimeTypes = QStringList() for bf in QImageWriter.supportedImageFormats(): mimeTypes.append(QLatin1String(bf)) # fileDialog.setMin setMimeTypeFilters(mimeTypes) # fileDialog.selectMimeTypeFilter("image/" + format); fileDialog.setDefaultSuffix(format) if fileDialog.accept(): return fileName = fileDialog.selectedFiles().first() if not self.originalPixmap.save(fileName): QtGui.QMessageBox.Warning( self, u"保存错误", u"图像无法存储到 \"%s\"." % str(QDir.toNativeSeparators(fileName))) def __shootScreen(self): if self.delaySpinBox.value() != 0: QApplication.beep() self.originalPixmap = QPixmap.grabWindow( QApplication.desktop().winId()) self.__updateScreenshotLabel() self.newScreenshotButton.setDisabled(False) if self.hideThisWindowCheckBox.isChecked(): self.show() def __updateCheckBox(self): print "sssss" if self.delaySpinBox.value() == 0: self.hideThisWindowCheckBox.setDisabled(True) self.hideThisWindowCheckBox.setChecked(False) else: self.hideThisWindowCheckBox.setDisabled(False) def __updateScreenshotLabel(self): self.screenshotLabel.setPixmap( self.originalPixmap.scaled(self.screenshotLabel.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))
class PhotoViewer(QScrollArea): """ Widget for viewing images by incorporating basic navigation options. """ def __init__(self, parent=None, photo_path=""): QScrollArea.__init__(self, parent) self.setBackgroundRole(QPalette.Dark) self._printer = QPrinter() self._lbl_photo = QLabel() self._lbl_photo.setBackgroundRole(QPalette.Base) self._lbl_photo.setSizePolicy(QSizePolicy.Ignored,QSizePolicy.Ignored) self._lbl_photo.setScaledContents(True) self.setWidget(self._lbl_photo) self._photo_path = photo_path self._ph_image = None self._scale_factor = 1.0 self._aspect_ratio = -1 self._create_actions() if self._photo_path: self.load_document(self._photo_path) def _create_actions(self): """ Create actions for basic image navigation. """ self._zoom_in_act = QAction( QApplication.translate("PhotoViewer","Zoom &In (25%)"), self) self._zoom_in_act.setShortcut( QApplication.translate("PhotoViewer","Ctrl++")) self._zoom_in_act.setEnabled(False) self._zoom_in_act.triggered.connect(self.zoom_in) self._zoom_out_act = QAction( QApplication.translate("PhotoViewer","Zoom &Out (25%)"), self) self._zoom_out_act.setShortcut( QApplication.translate("PhotoViewer","Ctrl+-")) self._zoom_out_act.setEnabled(False) self._zoom_out_act.triggered.connect(self.zoom_out) self._normal_size_act = QAction( QApplication.translate("PhotoViewer","&Normal Size"), self) self._normal_size_act.setShortcut( QApplication.translate("PhotoViewer","Ctrl+S")) self._normal_size_act.setEnabled(False) self._normal_size_act.triggered.connect(self.normal_size) self._fit_to_window_act = QAction( QApplication.translate("PhotoViewer","&Fit to Window"), self) self._fit_to_window_act.setShortcut( QApplication.translate("PhotoViewer","Ctrl+F")) self._fit_to_window_act.setEnabled(False) self._fit_to_window_act.setCheckable(True) self._fit_to_window_act.triggered.connect(self.fit_to_window) self._print_act = QAction( QApplication.translate("PhotoViewer","&Print"), self) self._print_act .setShortcut( QApplication.translate("PhotoViewer","Ctrl+P")) self._print_act .setEnabled(False) self._print_act .triggered.connect(self.print_photo) def zoom_in(self): self.scale_photo(1.25) def zoom_out(self): self.scale_photo(0.8) def normal_size(self): self._lbl_photo.adjustSize() self._scale_factor = 1.0 def fit_to_window(self): fit_to_win = self._fit_to_window_act.isChecked() self.setWidgetResizable(fit_to_win) if not fit_to_win: self.normal_size() self.update_actions() def print_photo(self): print_dialog = QPrintDialog(self._printer,self) if print_dialog.exec_() == QDialog.Accepted: painter = QPainter(self._printer) rect = painter.viewport() size = self._lbl_photo.pixmap().size() size.scale(rect.size(), Qt.KeepAspectRatio) painter.setViewport(rect.x(), rect.y(), size.width(), size.height()) painter.setWindow(self._lbl_photo.pixmap().rect()) painter.drawPixmap(0, 0, self._lbl_photo.pixmap()) def wheelEvent(self, event): """ Zoom the image based on the mouse wheel rotation action. :param event: Event containing the wheel rotation info. :type event: QWheelEvent """ degrees = event.delta() / 8 num_steps = degrees / 15 if num_steps < 0: abs_num_steps = abs(num_steps) zoom_factor = 1 + (abs_num_steps * 0.25) else: zoom_factor = 1 - (num_steps * 0.2) self.scale_photo(zoom_factor) def heightForWidth(self, width): if self._aspect_ratio != -1: return width / self._aspect_ratio else: return -1 def resizeEvent(self, event): """ Event for resizing the widget based on the pixmap's aspect ratio. :param event: Contains event parameters for the resize event. :type event: QResizeEvent """ super(PhotoViewer, self).resizeEvent(event) def update_actions(self): self._zoom_out_act.setEnabled(not self._fit_to_window_act.isChecked()) self._zoom_in_act.setEnabled(not self._fit_to_window_act.isChecked()) self._normal_size_act.setEnabled(not self._fit_to_window_act.isChecked()) def scale_photo(self,factor): """ :param factor: Value by which the image will be increased/decreased in the view. :type factor: float """ if not self._lbl_photo.pixmap().isNull(): self._scale_factor *= factor self._lbl_photo.resize(self._scale_factor * self._lbl_photo.pixmap().size()) self._adjust_scroll_bar(self.horizontalScrollBar(), factor) self._adjust_scroll_bar(self.verticalScrollBar(), factor) self._zoom_in_act.setEnabled(self._scale_factor < 3.0) self._zoom_out_act.setEnabled(self._scale_factor > 0.333) def _adjust_scroll_bar(self, scroll_bar, factor): scroll_bar.setValue(int(factor * scroll_bar.value() + ((factor - 1) * scroll_bar.pageStep()/2))) def load_document(self, photo_path): if photo_path: self._ph_image = QImage(photo_path) if self._ph_image.isNull(): return False self._photo_path = photo_path ph_pixmap = QPixmap.fromImage(self._ph_image) self._lbl_photo.setPixmap(ph_pixmap) self._scale_factor = 1.0 self._aspect_ratio = ph_pixmap.width() / ph_pixmap.height() self._fit_to_window_act.setEnabled(True) self._print_act.setEnabled(True) self._fit_to_window_act.trigger() self.update_actions() return ph_pixmap return True def photo_location(self): """ :returns: Absolute path of the photo in the central document repository. """ return self._photo_path def set_actions(self,menu): """ Add custom actions to the sub-window menu """ menu.addSeparator() menu.addAction(self._zoom_in_act) menu.addAction(self._zoom_out_act) menu.addAction(self._normal_size_act) menu.addAction(self._fit_to_window_act) menu.addSeparator() menu.addAction(self._print_act)
class MobileWidget(QWidget): """ Mobile widget """ RefreshScreen = pyqtSignal() RefreshAutomatic = pyqtSignal(bool) TapOn = pyqtSignal(int, int) def __init__(self, parent=None): """ Constructor """ super(MobileWidget, self).__init__(parent) self.origWidth = 0 self.origHeight = 0 self.imagePath = None self.createActions() self.createWidget() self.createToolbar() self.center() def createActions(self): """ Create qt actions """ self.refreshAction = QtHelper.createAction(self, self.tr("&Refresh"), self.refreshScreen, icon=None) self.refreshAction.setEnabled(False) self.copyAction = QtHelper.createAction(self, self.tr("&Copy"), self.copyItem, icon=None) def createWidget(self): """ Create qt widget """ self.screenResolutionLabel = QLabel(self) self.screenTapLabel = QLabel(self) mobileLayout = QVBoxLayout() self.mobileDockToolbar = QToolBar(self) self.mobileDockToolbar.setStyleSheet("QToolBar { border: 0px }") self.mobileDockToolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) self.mobileImageLabel = QLabel(self) self.mobileImageLabel.setMouseTracking(True) self.mobileImageLabel.installEventFilter(self) self.mobileImageLabel.setScaledContents(True) self.mobileImageLabel.mousePressEvent = self.pixelSelect self.refreshCheckbox = QCheckBox("Automatic Refresh", self) self.refreshCheckbox.setEnabled(False) self.refreshCheckbox.stateChanged.connect(self.onRefreshChanged) self.clickCheckbox = QCheckBox("Enable Tap", self) self.clickCheckbox.setEnabled(False) self.model = DomModel(QDomDocument(), self) self.mobileTreeView = QTreeView(self) self.mobileTreeView.setMinimumWidth(300) self.mobileTreeView.setModel(self.model) self.mobileTreeView.clicked.connect(self.onTreeViewClicked) header = ["Attribute", "Value"] self.tableModel = MyTableModel(self, [], header) self.mobileTableView = QTableView(self) self.mobileTableView.setSelectionMode( QAbstractItemView.SingleSelection) self.mobileTableView.setModel(self.tableModel) self.mobileTableView.setContextMenuPolicy(Qt.CustomContextMenu) self.mobileTableView.customContextMenuRequested.connect( self.onContextMenuEvent) self.mobileTableView.setMinimumWidth(300) mobileViewLayout = QHBoxLayout() mobileViewLayout.addWidget(self.mobileImageLabel) mobileViewLayout.addWidget(self.mobileTreeView) mobileViewLayout.addWidget(self.mobileTableView) mobileLayout.addWidget(self.mobileDockToolbar) mobileLayout.addLayout(mobileViewLayout) self.setLayout(mobileLayout) def createToolbar(self): """ Create qt toolbar """ self.mobileDockToolbar.setObjectName("Toolbar") self.mobileDockToolbar.addWidget(self.refreshCheckbox) self.mobileDockToolbar.addWidget(self.clickCheckbox) self.mobileDockToolbar.addSeparator() self.mobileDockToolbar.addAction(self.refreshAction) self.mobileDockToolbar.addSeparator() self.mobileDockToolbar.addWidget(self.screenResolutionLabel) self.mobileDockToolbar.addSeparator() self.mobileDockToolbar.addWidget(self.screenTapLabel) self.mobileDockToolbar.addSeparator() self.mobileDockToolbar.setIconSize(QSize(16, 16)) def center(self): """ Center the dialog """ qr = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) def eventFilter(self, srcEvent, event): """ On event filtering """ if srcEvent == self.mobileImageLabel: if event.type() == QEvent.MouseMove: x = event.pos().x() y = event.pos().y() pixmap = self.mobileImageLabel.pixmap() if pixmap is not None: x_scaled = int((self.origWidth * x) / pixmap.width()) y_scaled = int((self.origHeight * y) / pixmap.height()) self.mobileImageLabel.setToolTip("%sx%s" % (x_scaled, y_scaled)) return False def onContextMenuEvent(self, event): """ On context menu event """ menu = QMenu(self) menu.addAction(self.copyAction) menu.popup(QCursor.pos()) def copyItem(self): """ Copy the item """ indexes = self.mobileTableView.selectedIndexes() if len(indexes): data = self.tableModel.mylist[indexes[0].row()][ indexes[0].column()] clipboard = QApplication.clipboard() clipboard.setText(data) def onTreeViewClicked(self, qindex): """ On click in the treeview """ item = qindex.internalPointer() attributes = [] node = item.node() attributeMap = node.attributes() nodeName = node.nodeName() bounds_str = None for i in range(0, attributeMap.count()): attribute = attributeMap.item(i) attributes.append((attribute.nodeName(), attribute.nodeValue())) if attribute.nodeName() == 'bounds': bounds_str = attribute.nodeValue() self.tableModel.mylist = attributes if sys.version_info > (3, ): self.tableModel.beginResetModel() self.tableModel.endResetModel() else: self.tableModel.reset() self.mobileTableView.resizeColumnsToContents() self.mobileTableView.resizeRowsToContents() # redraw image with rectangle if bounds_str is not None: xy = bounds_str.split('][')[0].split('[')[1] wh = bounds_str.split('][')[1].split(']')[0] x, y = xy.split(',') w, h = wh.split(',') # get label size pixmap = self.mobileImageLabel.pixmap() xlabel = pixmap.width() ylabel = pixmap.height() # resize the rectangle y_scaled = (pixmap.height() * int(y)) / self.origHeight x_scaled = (pixmap.width() * int(x)) / self.origWidth h_scaled = (pixmap.height() * (int(h) - int(y))) / self.origHeight w_scaled = (pixmap.width() * (int(w) - int(x))) / self.origWidth # finally reload self.reloadScreen(x=int(x_scaled), y=int(y_scaled), w=int(w_scaled), h=int(h_scaled)) def onDeviceReady(self): """ On device ready """ self.refreshAction.setEnabled(True) self.refreshCheckbox.setEnabled(True) self.clickCheckbox.setEnabled(True) def refreshScreen(self): """ Refresh the screen """ self.RefreshScreen.emit() def onRefreshChanged(self, state): """ On refresh changed """ if state == Qt.Checked: self.RefreshAutomatic.emit(True) else: self.RefreshAutomatic.emit(False) def pixelSelect(self, event): """ Select pixel to click """ position = QPoint(event.pos().x(), event.pos().y()) x = event.pos().x() y = event.pos().y() pixmap = self.mobileImageLabel.pixmap() x_scaled = int((self.origWidth * x) / pixmap.width()) y_scaled = int((self.origHeight * y) / pixmap.height()) self.screenTapLabel.setText("Tap on (%s,%s)" % (x_scaled, y_scaled)) if self.clickCheckbox.isChecked(): self.TapOn.emit(x_scaled, y_scaled) def drawRectangle(self, x=0, y=0, w=0, h=0): """ Draw a rectangle """ self.mobileImageLabel.update() pixmap = self.mobileImageLabel.pixmap() if pixmap is not None: p = QPainter(pixmap) pen = QPen(Qt.red, 2, Qt.SolidLine) p.setPen(pen) p.drawRect(x, y, w, h) p.end() def reloadScreen(self, x, y, w, h): """ Reload the screen """ if self.imagePath is not None: self.updateScreen(filename=self.imagePath, xmlPath='', x=x, y=y, w=w, h=h, reloadMode=True) def updateScreen(self, filename, xmlPath, x=0, y=0, w=0, h=0, reloadMode=False): """ Update the screen """ self.imagePath = filename if not reloadMode: self.tableModel.mylist = [] self.tableModel.beginResetModel() self.tableModel.endResetModel() pixmap = QPixmap(filename) if pixmap is not None: self.origWidth = pixmap.width() self.origHeight = pixmap.height() self.screenResolutionLabel.setText( "Resolution=%sx%s" % (self.origWidth, self.origHeight)) #portrait if self.origWidth < self.origHeight: pixmap = pixmap.scaledToHeight(Settings.getInt( 'MobileAndroid', 'resolution-screen-height'), mode=Qt.SmoothTransformation) self.mobileImageLabel.setPixmap(pixmap) else: pixmap = pixmap.scaledToWidth(Settings.getInt( 'MobileAndroid', 'resolution-screen-width'), mode=Qt.SmoothTransformation) self.mobileImageLabel.setPixmap(pixmap) self.drawRectangle(x=x, y=y, w=w, h=h) self.resize(pixmap.width(), pixmap.height()) # convert xml to dict if len(xmlPath): f = QFile(xmlPath) if f.open(QIODevice.ReadOnly): document = QDomDocument() if document.setContent(f): newModel = DomModel(document, self) self.mobileTreeView.setModel(newModel) self.mobileTreeView.expandAll() self.mobileTreeView.resizeColumnToContents(0) f.close()
class ListViewItem(QWidget): """ Widget to show icon, title and description in a list control .. versionadded:: 0.7 """ def __init__(self, icon = None, title = '', description = ''): """ Default constructor :param icon: icon to show :type icon: QPixmap :param title: title to show :type title: string :param description: description to show :type description: string """ super().__init__() self._icon = None self._title = None self._description = None self.__set_layout(icon = icon, title = title, description = description) def __set_layout(self, icon, title, description): """ Set layout of this widget """ self._icon = QLabel() self._icon.setObjectName('no_border') self._title = QLabel() self._title.setText(title) self._title.setWordWrap(True) self._title.setObjectName('charactermenu_skill_title') self._description = QLabel() self._description.setText(description) self._description.setWordWrap(True) self._description.setObjectName('no_border') self._icon.setPixmap(icon) self._icon.setMaximumSize(32, 32) frame = QFrame() frame.setObjectName('effect') outer_layout = QVBoxLayout() frame_layout = QVBoxLayout() main_layout = QVBoxLayout() top_layout = QHBoxLayout() bottom_layout = QHBoxLayout() top_layout.addWidget(self._icon) top_layout.addWidget(self._title) bottom_layout.addWidget(self._description) frame_layout.addLayout(top_layout) frame_layout.addLayout(bottom_layout) frame.setLayout(frame_layout) outer_layout.addWidget(frame) main_layout.addLayout(outer_layout) self.setLayout(main_layout) def __get_title(self): return self._title.text() def __get_description(self): return self._description.text() def __get_icon(self): return self._icon.pixmap() title = property(__get_title) description = property(__get_description) icon = property(__get_icon)
class WTestPng(Document.WDocument): """ Test png widget """ def __init__(self, parent=None, path=None, filename=None, extension=None, nonameId=None, remoteFile=True, repoDest=None, project=0): """ Constructs WScript widget @param parent: @type parent: @param path: @type path: @param filename: @type filename: @param extension: @type extension: @param nonameId: @type nonameId: """ Document.WDocument.__init__(self, parent, path, filename, extension, nonameId, remoteFile, repoDest, project) self.scaleFactor = 0.0 self.rawContent = '' self.createWidgets() self.createActions() self.createToolbar() self.createConnections() def createActions(self): """ Create qt actions """ self.zoomInAct = QtHelper.createAction(self, "&Zoom &In (25%.", self.zoomIn, icon=QIcon(":/zoom-in.png")) self.zoomOutAct = QtHelper.createAction(self, "Zoom &Out (25%.", self.zoomOut, icon=QIcon(":/zoom-out.png")) self.normalSizeAct = QtHelper.createAction( self, "&Normal Size", self.normalSize, icon=QIcon(":/zoom-normal.png")) def createToolbar(self): """ Toolbar creation ||------|------||| || Open | Save ||| ||------|------||| """ self.dockToolbar.setObjectName("Test Config toolbar") self.dockToolbar.addAction(self.zoomInAct) self.dockToolbar.addAction(self.zoomOutAct) self.dockToolbar.addAction(self.normalSizeAct) self.dockToolbar.addSeparator() self.dockToolbar.setIconSize(QSize(16, 16)) def createWidgets(self): """ QtWidgets creation """ self.dockToolbar = QToolBar(self) self.dockToolbar.setStyleSheet( "QToolBar { border: 0px }") # remove 3D border self.imageLabel = QLabel(self) self.imageLabel.setBackgroundRole(QPalette.Base) self.imageLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored) self.imageLabel.setScaledContents(True) self.scrollArea = QScrollArea() self.scrollArea.setBackgroundRole(QPalette.Dark) self.scrollArea.setWidget(self.imageLabel) title = QLabel("Image:") title.setStyleSheet("QLabel { padding-left: 2px; padding-top: 2px }") font = QFont() font.setBold(True) title.setFont(font) layout = QVBoxLayout() layout.addWidget(title) layout.addWidget(self.dockToolbar) layout.addWidget(self.scrollArea) layout.setContentsMargins(2, 2, 2, 2) self.setLayout(layout) def zoomIn(self): """ Zoom in """ self.scaleImage(1.25) def zoomOut(self): """ Zoom out """ self.scaleImage(0.8) def normalSize(self): """ Normal size """ self.imageLabel.adjustSize() self.scaleFactor = 1.0 def scaleImage(self, factor): """ Scale image """ self.scaleFactor *= factor self.imageLabel.resize(self.scaleFactor * self.imageLabel.pixmap().size()) self.adjustScrollBar(self.scrollArea.horizontalScrollBar(), factor) self.adjustScrollBar(self.scrollArea.verticalScrollBar(), factor) def adjustScrollBar(self, scrollBar, factor): """ Adjust scrollbar """ scrollBar.setValue( int(factor * scrollBar.value() + ((factor - 1) * scrollBar.pageStep() / 2))) def createConnections(self): """ QtSignals connection """ pass def write(self, force=False): """ Save """ absPath = '%s/%s.%s' % (self.path, self.filename, self.extension) try: with open(absPath, mode='wb') as myfile: myfile.write(self.rawContent) except Exception as e: self.error("unable to write png file: %s" % e) return None else: self.setUnmodify() return True def load(self, content=None): """ Open file """ if content is None: absPath = '%s/%s.%s' % (self.path, self.filename, self.extension) file = QFile(absPath) if not file.open(QIODevice.ReadOnly): self.error("Error opening image file: %s" % absPath) return False else: content = file.readAll() self.rawContent = content image = QImage() image.loadFromData(content) if image.isNull(): self.error("cannot load image") return False else: self.imageLabel.setPixmap(QPixmap.fromImage(QImage(image))) self.scaleFactor = 1.0 self.imageLabel.adjustSize() return True def getraw_encoded(self): """ Returns raw data encoded """ encoded = '' try: encoded = base64.b64encode(self.rawContent) except Exception as e: self.error('unable to encode raw image: %s' % str(e)) return encoded
class ListViewItem(QWidget): """ Widget to show icon, title and description in a list control .. versionadded:: 0.7 """ def __init__(self, icon=None, title='', description=''): """ Default constructor :param icon: icon to show :type icon: QPixmap :param title: title to show :type title: string :param description: description to show :type description: string """ super().__init__() self._icon = None self._title = None self._description = None self.__set_layout(icon=icon, title=title, description=description) def __set_layout(self, icon, title, description): """ Set layout of this widget """ self._icon = QLabel() self._icon.setObjectName('no_border') self._title = QLabel() self._title.setText(title) self._title.setWordWrap(True) self._title.setObjectName('charactermenu_skill_title') self._description = QLabel() self._description.setText(description) self._description.setWordWrap(True) self._description.setObjectName('no_border') self._icon.setPixmap(icon) self._icon.setMaximumSize(32, 32) frame = QFrame() frame.setObjectName('effect') outer_layout = QVBoxLayout() frame_layout = QVBoxLayout() main_layout = QVBoxLayout() top_layout = QHBoxLayout() bottom_layout = QHBoxLayout() top_layout.addWidget(self._icon) top_layout.addWidget(self._title) bottom_layout.addWidget(self._description) frame_layout.addLayout(top_layout) frame_layout.addLayout(bottom_layout) frame.setLayout(frame_layout) outer_layout.addWidget(frame) main_layout.addLayout(outer_layout) self.setLayout(main_layout) def __get_title(self): return self._title.text() def __get_description(self): return self._description.text() def __get_icon(self): return self._icon.pixmap() title = property(__get_title) description = property(__get_description) icon = property(__get_icon)
class PixmapWidget( QScrollArea ): " The pixmap widget " escapePressed = pyqtSignal() formatStrings = { QImage.Format_Invalid: "invalid", QImage.Format_Mono: "1-bit per pixel", QImage.Format_MonoLSB: "1-bit per pixel", QImage.Format_Indexed8: "8-bit indexes", QImage.Format_RGB32: "32-bit RG", QImage.Format_ARGB32: "32-bit ARGB", QImage.Format_ARGB32_Premultiplied: "32-bit ARGB", QImage.Format_RGB16: "16-bit RGB", QImage.Format_ARGB8565_Premultiplied: "24-bit ARGB", QImage.Format_RGB666: "24-bit RGB", QImage.Format_ARGB6666_Premultiplied: "24-bit ARGB", QImage.Format_RGB555: "16-bit RGB", QImage.Format_ARGB8555_Premultiplied: "24-bit ARGB", QImage.Format_RGB888: "24-bit RGB", QImage.Format_RGB444: "16-bit RGB", QImage.Format_ARGB4444_Premultiplied: "16-bit ARGB" } def __init__( self, parent = None ): QScrollArea.__init__( self, parent ) self.pixmapLabel = QLabel() self.pixmapLabel.setBackgroundRole( QPalette.Base ) self.pixmapLabel.setSizePolicy( QSizePolicy.Ignored, QSizePolicy.Ignored ) self.pixmapLabel.setScaledContents( True ) self.zoom = 1.0 self.info = "" self.formatInfo = "" self.fileSize = 0 self.setBackgroundRole( QPalette.Dark ) self.setWidget( self.pixmapLabel ) self.setAlignment( Qt.AlignCenter ) return def loadFromFile( self, fileName ): " Loads a pixmap from a file " image = QImage( fileName ) if image.isNull(): raise Exception( "Unsupported pixmap format (" + fileName + ")" ) self.pixmapLabel.setPixmap( QPixmap.fromImage( image ) ) self.pixmapLabel.adjustSize() self.fileSize = os.path.getsize( fileName ) if self.fileSize < 1024: fileSizeString = str( self.fileSize ) + "bytes" else: kiloBytes = self.fileSize / 1024 if (self.fileSize % 1024) >= 512: kiloBytes += 1 fileSizeString = str( kiloBytes ) + "kb" self.info = str( image.width() ) + "px/" + \ str( image.height() ) + "px/" + fileSizeString try: self.formatInfo = self.formatStrings[ image.format() ] except: self.formatInfo = "Unknown" return def setPixmap( self, pixmap ): " Shows the provided pixmap " pix = QPixmap.fromImage( pixmap ) self.pixmapLabel.setPixmap( pix ) self.pixmapLabel.adjustSize() self.info = str( pix.width() ) + "px/" + str( pix.height() ) + "px" self.formatInfo = str( pix.depth() ) + " bpp" return def keyPressEvent( self, event ): """ Handles the key press events """ if event.key() == Qt.Key_Escape: self.escapePressed.emit() event.accept() else: QScrollArea.keyPressEvent( self, event ) return def resetZoom( self ): " Resets the zoom " self.zoom = 1.0 self.pixmapLabel.adjustSize() return def doZoom( self, factor ): " Performs zooming " self.zoom *= factor self.pixmapLabel.resize( self.zoom * self.pixmapLabel.pixmap().size() ) self.__adjustScrollBar( self.horizontalScrollBar(), factor ) self.__adjustScrollBar( self.verticalScrollBar(), factor ) return def __adjustScrollBar( self, scrollBar, factor ): " Adjusts a scrollbar by a certain factor " scrollBar.setValue( int( factor * scrollBar.value() + ( (factor - 1) * scrollBar.pageStep()/2) ) ) return def setReadOnly( self, newValue ): " Make it similar to a text editor " return