def mouseMoveEvent(self, event): super(TimelineWidget, self).mouseMoveEvent(event) self.parent_control.mouse_moveover_timeline_event(event) self._mouse_current_pos = event.x(), event.y() # Do nothing if no event bar is selected if self._selected is None: return # Set cursors if self._selected.canSlideBegin( event.x(), event.y()) or self._selected.canSlideEnd( event.x(), event.y()): self.setCursor(QCursor(QtCore.Qt.SizeHorCursor)) elif self._selected.collide(event.x(), event.y()): self.setCursor(QCursor(QtCore.Qt.SizeAllCursor)) else: self.setCursor(QCursor(QtCore.Qt.ArrowCursor)) if self._selected is None: return if event.buttons() == QtCore.Qt.LeftButton: if self._lastMouseY is not None: diff = event.x() - self._lastMouseY if diff != 0: if self._moving: self._selected.move(diff, event.y()) elif self._resizingBegin: self._selected.moveBegin(diff) elif self._resizingEnd: self._selected.moveEnd(diff) self.repaint() self._lastMouseY = event.x()
def mouseMoveEvent(self, event): super(GaugeWidgetVertical, self).mouseMoveEvent(event) y_start = self.height() - (self._minVal - self._lower) * self._step * self.scale y_end = self.height() - (self._maxVal - self._lower) * self._step * self.scale if y_start < event.y() or event.y() < y_end: self.setCursor(QCursor(QtCore.Qt.SizeVerCursor)) else: self.setCursor(QCursor(QtCore.Qt.ArrowCursor)) if event.buttons() == QtCore.Qt.LeftButton: if self._lastMouseY != None: diff = self._lastMouseY - event.y() if diff != 0: if self._moving: new_min = self._minVal * self.scale + diff * 1 / self._step new_max = self._maxVal * self.scale + diff * 1 / self._step if new_min < new_max: self._minVal = new_min / self.scale self._maxVal = new_max / self.scale elif self._resizingTop: new_max = self._maxVal * self.scale + diff * 1 / self._step if self._minVal < (new_max / self.scale): self._maxVal = new_max / self.scale elif self._resizingBottom: new_min = self._minVal * self.scale + diff * 1 / self._step if (new_min / self.scale) < self._maxVal: self._minVal = new_min / self.scale self.repaint() self.changed_event() self._lastMouseY = event.y()
def mouseMoveEvent(self, event): super(GaugeWidgetVertical, self).mouseMoveEvent(event) x_start = (self._minVal - self._lower) * self._step * self.scale x_end = (self._maxVal - self._lower) * self._step * self.scale # set the cursors if x_start >= event.x() or event.x() >= x_end: self.setCursor(QCursor(QtCore.Qt.SizeHorCursor)) else: self.setCursor(QCursor(QtCore.Qt.ArrowCursor)) if event.buttons() == QtCore.Qt.LeftButton: if self._lastMouseY != None: diff = self._lastMouseY - event.x() if diff != 0: if self._moving: new_min = self._minVal * self.scale - diff * 1 / self._step new_max = self._maxVal * self.scale - diff * 1 / self._step if new_min < new_max: self._minVal = new_min / self.scale self._maxVal = new_max / self.scale elif self._resizingLeft: new_max = self._maxVal * self.scale - diff * 1 / self._step if self._minVal < (new_max / self.scale): self._maxVal = new_max / self.scale elif self._resizingRight: new_min = self._minVal * self.scale - diff * 1 / self._step if (new_min / self.scale) < self._maxVal: self._minVal = new_min / self.scale self.repaint() self.changed_event() self._lastMouseY = event.x()
def _repaint(self, index): row, column = index.row(), index.column() if column in (Column.remove, Column.scheme): self.setCursor(QCursor(Qt.PointingHandCursor)) else: self.setCursor(QCursor(Qt.ArrowCursor)) if row >= 0: self.model().item(row, Column.remove).setIcon(self._icon_remove) self.model().item(row, Column.scheme).setIcon(self._icon_scheme)
class FreeVizInteractiveViewBox(InteractiveViewBox): def __init__(self, graph, enable_menu=False): self.mousestate = 0 self.point_i = None self.cursor = QCursor() super().__init__(graph, enable_menu) def _dragtip_pos(self): return 10, 10 def mouseDragEvent(self, ev, axis=None): master = self.graph.master if master.data is None: super().mouseDragEvent(ev, axis) return pos = self.childGroup.mapFromParent(ev.pos()) minradius = master.radius / 100 + 1e-5 points = master.plotdata.anchors mask = np.zeros((len(points)), dtype=bool) for i, point in enumerate(points): if np.linalg.norm(point) > minradius: mask[i] = True np_pos = np.array([[pos.x(), pos.y()]]) distances = distance.cdist(np_pos, points[:, :2])[0] is_near = False if not len( distances[mask]) else np.min(distances[mask]) < 0.1 if ev.button() != Qt.LeftButton or (ev.start and not is_near): self.mousestate = 2 # finished if self.mousestate == 2: if ev.finish: self.mousestate = 0 # ready for new task super().mouseDragEvent(ev, axis) return ev.accept() if ev.start: self.cursor.setShape(Qt.ClosedHandCursor) self.mousestate = 1 # working self.point_i = np.flatnonzero(mask)[np.argmin(distances[mask])] master.randomize_indices() is_moving = True if self.mousestate == 1: if ev.finish: self.cursor.setShape(Qt.OpenHandCursor) self.mousestate = 0 is_moving = False points[self.point_i][0] = pos.x() points[self.point_i][1] = pos.y() if is_moving: master.manual_move_anchor() else: master.setup_plot(reset_view=False) self.graph.show_indicator(point_i=self.point_i) self.setCursor(self.cursor)
class FreeVizInteractiveViewBox(InteractiveViewBox): def __init__(self, graph, enable_menu=False): self.mousestate = 0 self.point_i = None self.cursor = QCursor() super().__init__(graph, enable_menu) def _dragtip_pos(self): return 10, 10 def mouseDragEvent(self, ev, axis=None): master = self.graph.master if master.data is None: super().mouseDragEvent(ev, axis) return pos = self.childGroup.mapFromParent(ev.pos()) minradius = master.radius / 100 + 1e-5 points = master.plotdata.anchors mask = np.zeros((len(points)), dtype=bool) for i, point in enumerate(points): if np.linalg.norm(point) > minradius: mask[i] = True np_pos = np.array([[pos.x(), pos.y()]]) distances = distance.cdist(np_pos, points[:, :2])[0] is_near = False if not len(distances[mask]) else np.min(distances[mask]) < 0.1 if ev.button() != Qt.LeftButton or (ev.start and not is_near): self.mousestate = 2 # finished if self.mousestate == 2: if ev.finish: self.mousestate = 0 # ready for new task super().mouseDragEvent(ev, axis) return ev.accept() if ev.start: self.cursor.setShape(Qt.ClosedHandCursor) self.mousestate = 1 # working self.point_i = np.flatnonzero(mask)[np.argmin(distances[mask])] master.randomize_indices() is_moving = True if self.mousestate == 1: if ev.finish: self.cursor.setShape(Qt.OpenHandCursor) self.mousestate = 0 is_moving = False points[self.point_i][0] = pos.x() points[self.point_i][1] = pos.y() if is_moving: master.manual_move_anchor() else: master.setup_plot(reset_view=False) self.graph.show_indicator(point_i=self.point_i) self.setCursor(self.cursor)
class RadvizInteractiveViewBox(InteractiveViewBox): def __init__(self, graph, enable_menu=False): self.mouse_state = 0 self.point_i = None self.cursor = QCursor() super().__init__(graph, enable_menu) def _dragtip_pos(self): return 10, 10 def mouseDragEvent(self, ev, axis=None): master = self.graph.master if master.data is None or master.graph.data is None: super().mouseDragEvent(ev, axis) return pos = self.childGroup.mapFromParent(ev.pos()) points = master.plotdata.points np_pos = np.array([[pos.x(), pos.y()]]) distances = distance.cdist(np_pos, points[:, :2]) is_near = np.min(distances) < 0.1 if ev.button() != Qt.LeftButton or (ev.start and not is_near): self.mouse_state = 2 if self.mouse_state == 2: if ev.finish: self.mouse_state = 0 super().mouseDragEvent(ev, axis) return ev.accept() if ev.start: self.cursor.setShape(Qt.ClosedHandCursor) self.setCursor(self.cursor) self.mouse_state = 1 self.point_i = np.argmin(distances) master.randomize_indices() if self.mouse_state == 1: if ev.finish: self.cursor.setShape(Qt.ArrowCursor) self.setCursor(self.cursor) self.mouse_state = 0 angle = np.arctan2(pos.y(), pos.x()) QToolTip.showText( QPoint(ev.screenPos().x(), ev.screenPos().y()), "{:.2f}".format(np.rad2deg(angle))) points[self.point_i][0] = np.cos(angle) points[self.point_i][1] = np.sin(angle) if ev.finish: master.setup_plot() master.commit() else: master.manual_move() self.graph.show_arc_arrow(pos.x(), pos.y())
def mouseMoveEvent(self, event): """ Event called when the mouse is moved :param event: Mouse move event. """ super(TimelineWidget, self).mouseMoveEvent(event) self.control.mouse_moveover_timeline_event(event) xcoord, ycoord = event.x(), event.y() self._mouse_current_pos = xcoord, ycoord # Do nothing if no event bar is selected if self._selected is None: return # set cursors if self._selected.can_slide_begin(xcoord, ycoord) or \ self._selected.can_slide_end(xcoord, ycoord): # resize cursor. self.setCursor(QCursor(QtCore.Qt.SizeHorCursor)) elif self._selected.collide(xcoord, ycoord): # move cursor self.setCursor(QCursor(QtCore.Qt.SizeAllCursor)) else: # normal cursor self.setCursor(QCursor(QtCore.Qt.ArrowCursor)) if event.buttons() == QtCore.Qt.LeftButton: # move the period if self._last_mousex is not None: diff = xcoord - self._last_mousex if diff != 0: if self._moving: # move the selected period self._selected.move(diff, ycoord) elif self._resizing_began: # resize the beginning of the period self._selected.move_begin(diff) elif self._resizing_ended: # resize the end of the period self._selected.move_end(diff) self.repaint() self._last_mousex = xcoord
def __autoScrollAdvance(self): """Advance the auto scroll """ pos = QCursor.pos() pos = self.mapFromGlobal(pos) margin = self.__autoScrollMargin vvalue = self.verticalScrollBar().value() hvalue = self.horizontalScrollBar().value() vrect = QRect(0, 0, self.width(), self.height()) # What should be the speed advance = 10 # We only do auto scroll if the mouse is inside the view. if vrect.contains(pos): if pos.x() < vrect.left() + margin: self.horizontalScrollBar().setValue(hvalue - advance) if pos.y() < vrect.top() + margin: self.verticalScrollBar().setValue(vvalue - advance) if pos.x() > vrect.right() - margin: self.horizontalScrollBar().setValue(hvalue + advance) if pos.y() > vrect.bottom() - margin: self.verticalScrollBar().setValue(vvalue + advance) if self.verticalScrollBar().value() == vvalue and \ self.horizontalScrollBar().value() == hvalue: self.__stopAutoScroll() else: self.__stopAutoScroll() log.debug("Auto scroll advance")
def dropEvent(self, event): """Reimplemented.""" layout = self.__flowlayout index = self.__insertIndexAt(self.mapFromGlobal(QCursor.pos())) if event.mimeData().hasFormat("application/x-internal-move") and \ event.source() is self: # Complete the internal move frame, oldindex, _ = self.__dragstart # Remove the drop indicator spacer item before re-inserting # the frame self.__setDropIndicatorAt(None) if index > oldindex: index = index - 1 if index != oldindex: item = layout.takeAt(oldindex) assert item.widget() is frame layout.insertWidget(index, frame) self.widgetMoved.emit(oldindex, index) event.accept() self.__dragstart = None, None, None
def initStyleOptionForIndex(self, option: QStyleOptionHeader, logicalIndex: int) -> None: """ Similar to initStyleOptionForIndex in Qt 6.0 with the difference that `isSectionSelected` is not used, only `sectionIntersectsSelection` is used (isSectionSelected will scan the entire model column/row when the whole column/row is selected). """ hover = self.logicalIndexAt(self.mapFromGlobal(QCursor.pos())) pressed = self.__pressed if self.highlightSections(): is_selected = self.__sectionIntersectsSelection else: is_selected = lambda _: False state = QStyle.State_None if self.isEnabled(): state |= QStyle.State_Enabled if self.window().isActiveWindow(): state |= QStyle.State_Active if self.sectionsClickable(): if logicalIndex == hover: state |= QStyle.State_MouseOver if logicalIndex == pressed: state |= QStyle.State_Sunken if self.highlightSections(): if is_selected(logicalIndex): state |= QStyle.State_On if self.isSortIndicatorShown() and \ self.sortIndicatorSection() == logicalIndex: option.sortIndicator = ( QStyleOptionHeader.SortDown if self.sortIndicatorOrder() == Qt.AscendingOrder else QStyleOptionHeader.SortUp) style = self.style() model = self.model() orientation = self.orientation() textAlignment = model.headerData(logicalIndex, self.orientation(), Qt.TextAlignmentRole) defaultAlignment = self.defaultAlignment() textAlignment = (textAlignment if isinstance(textAlignment, int) else defaultAlignment) option.section = logicalIndex option.state = QStyle.State(int(option.state) | int(state)) option.textAlignment = Qt.Alignment(int(textAlignment)) option.iconAlignment = Qt.AlignVCenter text = model.headerData(logicalIndex, self.orientation(), Qt.DisplayRole) text = str(text) if text is not None else "" option.text = text icon = model.headerData(logicalIndex, self.orientation(), Qt.DecorationRole) try: option.icon = QIcon(icon) except (TypeError, ValueError): # pragma: no cover pass margin = 2 * style.pixelMetric(QStyle.PM_HeaderMargin, None, self) headerArrowAlignment = style.styleHint(QStyle.SH_Header_ArrowAlignment, None, self) isHeaderArrowOnTheSide = headerArrowAlignment & Qt.AlignVCenter if self.isSortIndicatorShown() and \ self.sortIndicatorSection() == logicalIndex \ and isHeaderArrowOnTheSide: margin += style.pixelMetric(QStyle.PM_HeaderMarkSize, None, self) if not option.icon.isNull(): margin += style.pixelMetric(QStyle.PM_SmallIconSize, None, self) margin += style.pixelMetric(QStyle.PM_HeaderMargin, None, self) if self.textElideMode() != Qt.ElideNone: elideMode = self.textElideMode() if hasattr(option, 'textElideMode'): # Qt 6.0 option.textElideMode = elideMode # pragma: no cover else: option.text = option.fontMetrics.elidedText( option.text, elideMode, option.rect.width() - margin) foregroundBrush = model.headerData(logicalIndex, orientation, Qt.ForegroundRole) try: foregroundBrush = QBrush(foregroundBrush) except (TypeError, ValueError): pass else: option.palette.setBrush(QPalette.ButtonText, foregroundBrush) backgroundBrush = model.headerData(logicalIndex, orientation, Qt.BackgroundRole) try: backgroundBrush = QBrush(backgroundBrush) except (TypeError, ValueError): pass else: option.palette.setBrush(QPalette.Button, backgroundBrush) option.palette.setBrush(QPalette.Window, backgroundBrush) # the section position visual = self.visualIndex(logicalIndex) assert visual != -1 first = self.__isFirstVisibleSection(visual) last = self.__isLastVisibleSection(visual) if first and last: option.position = QStyleOptionHeader.OnlyOneSection elif first: option.position = QStyleOptionHeader.Beginning elif last: option.position = QStyleOptionHeader.End else: option.position = QStyleOptionHeader.Middle option.orientation = orientation # the selected position (in QHeaderView this is always computed even if # highlightSections is False). if self.highlightSections(): previousSelected = is_selected(self.logicalIndex(visual - 1)) nextSelected = is_selected(self.logicalIndex(visual + 1)) else: previousSelected = nextSelected = False if previousSelected and nextSelected: option.selectedPosition = QStyleOptionHeader.NextAndPreviousAreSelected elif previousSelected: option.selectedPosition = QStyleOptionHeader.PreviousIsSelected elif nextSelected: option.selectedPosition = QStyleOptionHeader.NextIsSelected else: option.selectedPosition = QStyleOptionHeader.NotAdjacent
def _on_mouse_moved(self, pos): target = self.target_index selected = self.selected_classifiers curves = [(clf_idx, self.plot_curves(target, clf_idx)) for clf_idx in selected ] # type: List[Tuple[int, PlotCurves]] valid_thresh, valid_clf = [], [] pt, ave_mode = None, self.roc_averaging for clf_idx, crv in curves: if self.roc_averaging == OWROCAnalysis.Merge: curve = crv.merge() elif self.roc_averaging == OWROCAnalysis.Vertical: curve = crv.avg_vertical() elif self.roc_averaging == OWROCAnalysis.Threshold: curve = crv.avg_threshold() else: # currently not implemented for 'Show Individual Curves' return sp = curve.curve_item.childItems()[0] # type: pg.ScatterPlotItem act_pos = sp.mapFromScene(pos) pts = sp.pointsAt(act_pos) if pts: mouse_pt = pts[0].pos() if self._tooltip_cache: cache_pt, cache_thresh, cache_clf, cache_ave = self._tooltip_cache curr_thresh, curr_clf = [], [] if np.linalg.norm(mouse_pt - cache_pt) < 10e-6 \ and cache_ave == self.roc_averaging: mask = np.equal(cache_clf, clf_idx) curr_thresh = np.compress(mask, cache_thresh).tolist() curr_clf = np.compress(mask, cache_clf).tolist() else: QToolTip.showText(QCursor.pos(), "") self._tooltip_cache = None if curr_thresh: valid_thresh.append(*curr_thresh) valid_clf.append(*curr_clf) pt = cache_pt continue curve_pts = curve.curve.points roc_points = np.column_stack((curve_pts.fpr, curve_pts.tpr)) diff = np.subtract(roc_points, mouse_pt) # Find closest point on curve and save the corresponding threshold idx_closest = np.argmin(np.linalg.norm(diff, axis=1)) thresh = curve_pts.thresholds[idx_closest] if not np.isnan(thresh): valid_thresh.append(thresh) valid_clf.append(clf_idx) pt = [ curve_pts.fpr[idx_closest], curve_pts.tpr[idx_closest] ] if valid_thresh: clf_names = self.classifier_names msg = "Thresholds:\n" + "\n".join([ "({:s}) {:.3f}".format(clf_names[i], thresh) for i, thresh in zip(valid_clf, valid_thresh) ]) QToolTip.showText(QCursor.pos(), msg) self._tooltip_cache = (pt, valid_thresh, valid_clf, ave_mode)
def setCursor(self, cursor): if self._cursor != cursor: self._cursor = QCursor(cursor) self.cursorChanged.emit()
def cursor(self): return QCursor(self._cursor)
def __init__(self, graph, enable_menu=False): self.mousestate = 0 self.point_i = None self.cursor = QCursor() super().__init__(graph, enable_menu)
def dragMoveEvent(self, event): """Reimplemented.""" pos = self.mapFromGlobal(QCursor.pos()) self.__setDropIndicatorAt(pos)
def _on_mouse_moved(self, pos): target = self.target_index selected = self.selected_classifiers curves = [(clf_idx, self.plot_curves(target, clf_idx)) for clf_idx in selected] # type: List[Tuple[int, plot_curves]] valid_thresh, valid_clf = [], [] pt, ave_mode = None, self.roc_averaging for clf_idx, crv in curves: if self.roc_averaging == OWROCAnalysis.Merge: curve = crv.merge() elif self.roc_averaging == OWROCAnalysis.Vertical: curve = crv.avg_vertical() elif self.roc_averaging == OWROCAnalysis.Threshold: curve = crv.avg_threshold() else: # currently not implemented for 'Show Individual Curves' return sp = curve.curve_item.childItems()[0] # type: pg.ScatterPlotItem act_pos = sp.mapFromScene(pos) pts = sp.pointsAt(act_pos) if len(pts) > 0: mouse_pt = pts[0].pos() if self._tooltip_cache: cache_pt, cache_thresh, cache_clf, cache_ave = self._tooltip_cache curr_thresh, curr_clf = [], [] if numpy.linalg.norm(mouse_pt - cache_pt) < 10e-6 \ and cache_ave == self.roc_averaging: mask = numpy.equal(cache_clf, clf_idx) curr_thresh = numpy.compress(mask, cache_thresh).tolist() curr_clf = numpy.compress(mask, cache_clf).tolist() else: QToolTip.showText(QCursor.pos(), "") self._tooltip_cache = None if curr_thresh: valid_thresh.append(*curr_thresh) valid_clf.append(*curr_clf) pt = cache_pt continue curve_pts = curve.curve.points roc_points = numpy.column_stack((curve_pts.fpr, curve_pts.tpr)) diff = numpy.subtract(roc_points, mouse_pt) # Find closest point on curve and save the corresponding threshold idx_closest = numpy.argmin(numpy.linalg.norm(diff, axis=1)) thresh = curve_pts.thresholds[idx_closest] if not numpy.isnan(thresh): valid_thresh.append(thresh) valid_clf.append(clf_idx) pt = [curve_pts.fpr[idx_closest], curve_pts.tpr[idx_closest]] if valid_thresh: clf_names = self.classifier_names msg = "Thresholds:\n" + "\n".join(["({:s}) {:.3f}".format(clf_names[i], thresh) for i, thresh in zip(valid_clf, valid_thresh)]) QToolTip.showText(QCursor.pos(), msg) self._tooltip_cache = (pt, valid_thresh, valid_clf, ave_mode)
def get_table(self): if self.tablecombo.currentIndex() <= 0: if self.database_desc: self.database_desc["Table"] = "(None)" self.data_desc_table = None return if self.tablecombo.currentIndex() < self.tablecombo.count() - 1: self.table = self.tablemodel[self.tablecombo.currentIndex()] self.database_desc["Table"] = self.table if "Query" in self.database_desc: del self.database_desc["Query"] else: self.sql = self.table = self.sqltext.toPlainText() if self.materialize: import psycopg2 if not self.materialize_table_name: self.Error.connection( "Specify a table name to materialize the query") return try: with self.backend.execute_sql_query( "DROP TABLE IF EXISTS " + self.materialize_table_name): pass with self.backend.execute_sql_query( "CREATE TABLE " + self.materialize_table_name + " AS " + self.table): pass with self.backend.execute_sql_query( "ANALYZE " + self.materialize_table_name): pass self.table = self.materialize_table_name except (psycopg2.ProgrammingError, BackendError) as ex: self.Error.connection(str(ex)) return try: table = SqlTable(dict(host=self.host, port=self.port, database=self.database, user=self.username, password=self.password), self.table, backend=type(self.backend), inspect_values=False) except BackendError as ex: self.Error.connection(str(ex)) return self.Error.connection.clear() sample = False if table.approx_len() > LARGE_TABLE and self.guess_values: confirm = QMessageBox(self) confirm.setIcon(QMessageBox.Warning) confirm.setText("Attribute discovery might take " "a long time on large tables.\n" "Do you want to auto discover attributes?") confirm.addButton("Yes", QMessageBox.YesRole) no_button = confirm.addButton("No", QMessageBox.NoRole) sample_button = confirm.addButton("Yes, on a sample", QMessageBox.YesRole) confirm.exec() if confirm.clickedButton() == no_button: self.guess_values = False elif confirm.clickedButton() == sample_button: sample = True self.Information.clear() if self.guess_values: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) if sample: s = table.sample_time(1) domain = s.get_domain(inspect_values=True) self.Information.data_sampled() else: domain = table.get_domain(inspect_values=True) QApplication.restoreOverrideCursor() table.domain = domain if self.download: if table.approx_len() > MAX_DL_LIMIT: QMessageBox.warning( self, 'Warning', "Data is too big to download.\n" "Consider using the Data Sampler widget to download " "a sample instead.") self.download = False elif table.approx_len() > AUTO_DL_LIMIT: confirm = QMessageBox.question( self, 'Question', "Data appears to be big. Do you really " "want to download it to local memory?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if confirm == QMessageBox.No: self.download = False if self.download: table.download_data(MAX_DL_LIMIT) table = Table(table) return table
def show_tray_menu(self): self._menu.popup(QCursor.pos())
def position(self): return QPointF(self.view.mapFromGlobal(QCursor.pos()))