def main(argv=None): import sys import sip argv = sys.argv[1:] if argv is None else argv if argv: filename = argv[0] else: filename = "heart_disease" data = Table(filename) app = QApplication([]) w = OWRadviz() w.set_data(data) w.set_subset_data(data[::10]) w.handleNewSignals() w.show() w.raise_() r = app.exec() w.set_data(None) w.saveSettings() sip.delete(w) del w return r
def main(argv=None): import sip from AnyQt.QtWidgets import QApplication if argv is None: argv = sys.argv argv = list(argv) app = QApplication(argv) w = OWScatterMap() w.show() w.raise_() if len(argv) > 1: filename = argv[1] else: filename = "adult" data = Orange.data.Table(filename) w.set_data(data) rval = app.exec_() w.set_data(None) w.onDeleteWidget() sip.delete(w) del w app.processEvents() return rval
def main(): # example from https://github.com/marinkaz/scikit-fusion import numpy as np from AnyQt.QtWidgets import QApplication R12 = np.random.rand(50, 100) R32 = np.random.rand(100, 150) R33 = np.random.rand(150, 150) R13 = np.random.rand(50, 150) t1 = fusion.ObjectType('Users', 10) t2 = fusion.ObjectType('Movies', 30) t3 = fusion.ObjectType('Actors', 40) relations = [fusion.Relation(R12, t1, t2, name='like'), fusion.Relation(R13, t1, t3, name='are fans of'), fusion.Relation(R12, t1, t2, name='don\'t like'), fusion.Relation(R33, t3, t3, name='married to'), fusion.Relation(R32, t2, t3, name='feature')] G = fusion.FusionGraph() for rel in relations: G.add_relation(rel) fuser = fusion.Dfmf() fuser.fuse(G) app = QApplication([]) w = OWChaining() w.on_fuser_change(FittedFusionGraph(fuser)) w.show() app.exec()
def test(): import sklearn.cross_validation as skl_cross_validation app = QApplication([]) w = OWVennDiagram() data = Orange.data.Table("brown-selected") data = append_column(data, "M", Orange.data.StringVariable("Test"), numpy.arange(len(data)).reshape(-1, 1) % 30) indices = skl_cross_validation.ShuffleSplit(len(data), n_iter=5, test_size=0.7) indices = iter(indices) def select(data): sample, _ = next(indices) return data[sample] d1 = select(data) d2 = select(data) d3 = select(data) d4 = select(data) d5 = select(data) for i, data in enumerate([d1, d2, d3, d4, d5]): data.name = chr(ord("A") + i) w.setData(data, key=i) w.handleNewSignals() w.show() app.exec_() del w app.processEvents() return app
def main(): import gc import sip from AnyQt.QtWidgets import QApplication from Orange.classification import (LogisticRegressionLearner, SVMLearner, NuSVMLearner) app = QApplication([]) w = OWROCAnalysis() w.show() w.raise_() # data = Orange.data.Table("iris") data = Orange.data.Table("ionosphere") results = Orange.evaluation.CrossValidation( data, [LogisticRegressionLearner(), LogisticRegressionLearner(penalty="l1"), SVMLearner(probability=True), NuSVMLearner(probability=True)], k=5, store_data=True, ) results.learner_names = ["Logistic", "Logistic (L1 reg.)", "SVM", "NuSVM"] w.set_results(results) rval = app.exec_() w.deleteLater() sip.delete(w) del w app.processEvents() sip.delete(app) del app gc.collect() return rval
def main(): # pragma: no cover from AnyQt.QtWidgets import QApplication a = QApplication([]) ow = OWGrep() ow.show() a.exec_() ow.saveSettings()
def invalidate_plot(self): """ Schedule a delayed replot. """ if not self.__replot_requested: self.__replot_requested = True QApplication.postEvent(self, QEvent(self.ReplotRequest), Qt.LowEventPriority - 10)
def main(): from Orange.data import Table, Domain, ContinuousVariable, StringVariable words = 'hey~mr. tallyman tally~me banana daylight come and me wanna go home' words = np.array([w.replace('~', ' ') for w in words.split()], dtype=object, ndmin=2).T weights = np.random.random((len(words), 1)) data = np.zeros((len(words), 0)) metas = [] for i, w in enumerate(weights.T): data = np.column_stack((data, words, w)) metas = metas + [StringVariable('Topic' + str(i)), ContinuousVariable('weights')] domain = Domain([], metas=metas) table = Table.from_numpy(domain, X=np.zeros((len(words), 0)), metas=data) app = QApplication(['']) w = OWWordCloud() w.on_topic_change(table) domain = Domain([], metas=[StringVariable('text')]) data = Corpus(domain=domain, metas=np.array([[' '.join(words.flat)]])) # data = Corpus.from_numpy(domain, X=np.zeros((1, 0)), metas=np.array([[' '.join(words.flat)]])) w.on_corpus_change(data) w.show() app.exec()
def main(argv=sys.argv): from AnyQt.QtWidgets import QApplication import Orange app = QApplication(list(argv)) argv = app.arguments() if len(argv) > 1: filename = argv[1] else: filename = 'iris' ow = OWPythagorasTree() data = Orange.data.Table(filename) if data.domain.has_discrete_class: from Orange.classification.tree import TreeLearner else: from Orange.regression.tree import TreeLearner model = TreeLearner(max_depth=1000)(data) model.instances = data ow.set_tree(model) ow.show() ow.raise_() ow.handleNewSignals() app.exec_() sys.exit(0)
def copy_to_clipboard(self): img = self.get_selection() if img.isNull(): QMessageBox.critical(self, self.tr('Error'), self.tr('No image was selected!')) return QApplication.clipboard().setPixmap(img) self.reject()
def test(argv=sys.argv): app = QApplication(list(argv)) argv = app.arguments() if len(argv) > 1: filename = argv[1] else: filename = "iris" import sip import Orange.distance w = OWDistanceMap() w.show() w.raise_() data = Orange.data.Table(filename) dist = Orange.distance.Euclidean(data) w.set_distances(dist) w.handleNewSignals() rval = app.exec_() w.set_distances(None) w.saveSettings() w.onDeleteWidget() sip.delete(w) del w return rval
class TestIconLoader(unittest.TestCase): def setUp(self): from AnyQt.QtWidgets import QApplication self.app = QApplication([]) def tearDown(self): self.app.exit() del self.app def test_loader(self): loader = icon_loader() self.assertEqual(loader.search_paths(), DEFAULT_SEARCH_PATHS) icon = loader.get("icons/CanvasIcon.png") self.assertTrue(not icon.isNull()) path = loader.find(":icons/CanvasIcon.png") self.assertTrue(os.path.isfile(path)) icon = loader.get(":icons/CanvasIcon.png") self.assertTrue(not icon.isNull()) def test_from_desc(self): from .registry.description import ( WidgetDescription, CategoryDescription ) desc = WidgetDescription.from_module( "Orange.widgets.data.owfile" ) loader = icon_loader.from_description(desc) path = loader.find(desc.icon) self.assertTrue(os.path.isfile(path)) icon = loader.get(desc.icon) self.assertTrue(not icon.isNull()) desc = CategoryDescription.from_package("Orange.widgets.data") loader = icon_loader.from_description(desc) path = loader.find("icons/file.svg") self.assertTrue(os.path.isfile(path)) icon = loader.get("icons/file.svg") self.assertTrue(not icon.isNull()) def test_package_reflection(self): from Orange.widgets.data import owfile from Orange.widgets import data package_name = data.__name__ p1 = package("Orange.widgets.data.owfile.OWFile") self.assertEqual(p1, package_name) p2 = package("Orange.widgets.data.owfile") self.assertEqual(p2, package_name) p3 = package("Orange.widgets.data") self.assertEqual(p3, package_name) p4 = package(owfile.__name__) self.assertEqual(p4, package_name) dirname = package_dirname(package_name) self.assertEqual(dirname, os.path.dirname(data.__file__))
def test(): from AnyQt.QtWidgets import QApplication app = QApplication([]) w = OWSelectRows() w.set_data(Table("zoo")) w.show() app.exec_()
def main(): from AnyQt.QtWidgets import QApplication t1 = fusion.ObjectType('Users', 10) t2 = fusion.ObjectType('Movies', 30) t3 = fusion.ObjectType('Actors', 40) # test that MeanFuser completes correctly R = np.ma.array([[1, 1, 0], [3, 0, 0]], mask=[[0, 0, 1], [0, 1, 1]], dtype=float) rel = fusion.Relation(R, t1, t2) assert (MeanFuser(0).complete(rel) == [[1, 1, 5/3], [3, 1, 5/3]]).all() assert (MeanFuser(1).complete(rel) == [[1, 1, 1], [3, 3, 3]]).all() assert (MeanFuser(2).complete(rel) == [[1, 1, 5/3], [3, 5/3, 5/3]]).all() R1 = np.ma.array(np.random.random((20, 20))) R2 = np.ma.array(np.random.random((40, 40)), mask=np.random.random((40,40)) > .8) relations = [ fusion.Relation(R1, t1, t2, name='like'), fusion.Relation(R2, t3, t2, name='feature in'), ] G = fusion.FusionGraph() G.add_relations_from(relations) app = QApplication([]) w = OWMeanFuser() w.on_fusion_graph_change(G) w.show() app.exec()
def main(argv=None): import sys from orangecontrib.imageanalytics.import_images import ImportImages from orangecontrib.imageanalytics.image_embedder import ImageEmbedder if argv is None: argv = sys.argv argv = list(argv) app = QApplication(argv) if len(argv) > 1: image_dir = argv[1] else: raise ValueError("Provide the image directory as the first argument.") import_images = ImportImages() images, err = import_images(image_dir) image_embedder = ImageEmbedder() embeddings, _, _ = image_embedder(images) ow = OWImageGrid() ow.show() ow.raise_() ow.set_data(Orange.data.Table(embeddings)) rval = app.exec() ow.saveSettings() ow.onDeleteWidget() return rval
def test_main(): app = QApplication([]) data = Table("iris") w = OWDataSampler() w.set_data(data) w.show() return app.exec_()
def main(argv=None): import sys if argv is None: argv = sys.argv argv = list(argv) a = QApplication(argv) if len(argv) > 1: filename = argv[1] else: filename = "heart_disease" ow = OWScatterPlot() ow.show() ow.raise_() data = Orange.data.Table(filename) ow.set_data(data) ow.set_subset_data(data[:30]) ow.handleNewSignals() rval = a.exec() ow.set_data(None) ow.set_subset_data(None) ow.handleNewSignals() ow.saveSettings() ow.onDeleteWidget() return rval
def __setupUi(self): layout = QVBoxLayout() label = QLabel(self) pixmap, _ = config.splash_screen() label.setPixmap(pixmap) layout.addWidget(label, Qt.AlignCenter) name = QApplication.applicationName() version = QApplication.applicationVersion() text = ABOUT_TEMPLATE.format( name=escape(name), version=escape(version), ) # TODO: Also list all known add-on versions??. text_label = QLabel(text) layout.addWidget(text_label, Qt.AlignCenter) buttons = QDialogButtonBox( QDialogButtonBox.Close, Qt.Horizontal, self) layout.addWidget(buttons) buttons.rejected.connect(self.accept) layout.setSizeConstraint(QVBoxLayout.SetFixedSize) self.setLayout(layout)
def main(): import sip from AnyQt.QtWidgets import QApplication from Orange.classification import (LogisticRegressionLearner, SVMLearner, NuSVMLearner) app = QApplication([]) w = OWCalibrationPlot() w.show() w.raise_() data = Orange.data.Table("ionosphere") results = Orange.evaluation.CrossValidation( data, [LogisticRegressionLearner(penalty="l2"), LogisticRegressionLearner(penalty="l1"), SVMLearner(probability=True), NuSVMLearner(probability=True) ], store_data=True ) results.learner_names = ["LR l2", "LR l1", "SVM", "Nu SVM"] w.set_results(results) rval = app.exec_() sip.delete(w) del w app.processEvents() del app return rval
def main(argv=None): if argv is None: argv = sys.argv import gc app = QApplication(list(argv)) argv = app.arguments() if len(argv) > 1: filename = argv[1] else: filename = "iris" data = Orange.data.Table(filename) w = OWMDS() w.set_data(data) w.set_subset_data(data[np.random.choice(len(data), 10)]) w.handleNewSignals() w.show() w.raise_() rval = app.exec_() w.set_subset_data(None) w.set_data(None) w.handleNewSignals() w.saveSettings() w.onDeleteWidget() w.deleteLater() del w gc.collect() app.processEvents() return rval
def pixmap(self, size, mode, state): # type: (QSize, QIcon.Mode, QIcon.State) -> QPixmap if not self.__generator.isValid(): return QPixmap() dsize = self.__generator.defaultSize() # type: QSize if not dsize.isNull(): dsize.scale(size, Qt.KeepAspectRatio) size = dsize key = "{}.SVGIconEngine/{}/{}x{}".format( __name__, self.__cache_id, size.width(), size.height() ) pm = QPixmapCache.find(key) if pm is None or pm.isNull(): pm = QPixmap(size) pm.fill(Qt.transparent) painter = QPainter(pm) try: self.__generator.render( painter, QRectF(0, 0, size.width(), size.height())) finally: painter.end() QPixmapCache.insert(key, pm) style = QApplication.style() if style is not None: opt = QStyleOption() opt.palette = QApplication.palette() pm = style.generatedIconPixmap(mode, pm, opt) return pm
def main(): from AnyQt.QtWidgets import QApplication app = QApplication(sys.argv) ow = TestConnected() ow.show() ow.raise_() app.exec_() return 0
def main(): app = QApplication([]) widget = OWSentimentAnalysis() corpus = Corpus.from_file('book-excerpts') corpus = corpus[:3] widget.set_corpus(corpus) widget.show() app.exec()
def main(): import sys from AnyQt.QtWidgets import QApplication a = QApplication(sys.argv) ow = OWFile() ow.show() a.exec_() ow.saveSettings()
def main_test(): from AnyQt.QtWidgets import QApplication app = QApplication([]) w = OWGEODatasets() w.show() w.raise_() r = app.exec_() w.saveSettings() return r
def main(): app = QApplication([]) w = OWExplainPredictions() data = Orange.data.Table("iris.tab") data_subset = data[:20] w.set_data(data_subset) w.set_data(None) w.show() app.exec_()
def test_main(): from AnyQt.QtWidgets import QApplication app = QApplication([]) data = Table("iris") w = OWOutliers() w.set_data(data) w.commit() w.show() return app.exec_()
def main(): app = QApplication([]) w = OWDiscretize() data = Orange.data.Table("brown-selected") w.set_data(data) w.set_data(None) w.set_data(data) w.show() return app.exec_()
def test_main(): from AnyQt.QtWidgets import QApplication app = QApplication(sys.argv) dicty.verbose = True w = OWPIPAx() w.show() r = app.exec_() w.saveSettings() return r
def main(): from AnyQt.QtWidgets import QApplication app = QApplication([]) w = OWEditDomain() data = Orange.data.Table("iris") w.set_data(data) w.show() w.raise_() return app.exec_()
def eventFilter(self, obj, event): # pylint: disable=too-many-branches # type: (QObject, QEvent) -> bool """Reimplemented.""" etype = event.type() if etype == QEvent.FocusOut and self.__popup is not None: self.hidePopup() return True if etype == QEvent.Hide and self.__popup is not None: self.hidePopup() return False if etype == QEvent.KeyPress or etype == QEvent.KeyRelease or \ etype == QEvent.ShortcutOverride and obj is self.__popup: event = event # type: QKeyEvent key, modifiers = event.key(), event.modifiers() if key in (Qt.Key_Enter, Qt.Key_Return, Qt.Key_Select): current = self.__popup.currentIndex() if current.isValid(): self.__activateProxyIndex(current) elif key in (Qt.Key_Up, Qt.Key_Down, Qt.Key_PageUp, Qt.Key_PageDown): return False # elif key in (Qt.Key_Tab, Qt.Key_Backtab): pass elif key == Qt.Key_Escape or \ (key == Qt.Key_F4 and modifiers & Qt.AltModifier): self.__popup.hide() return True else: # pass the input events to the filter edit line (no propagation # up the parent chain). self.__searchline.event(event) if event.isAccepted(): return True if etype == QEvent.MouseButtonRelease and self.__popup is not None \ and obj is self.__popup.viewport() \ and self.__popupTimer.elapsed() >= \ QApplication.doubleClickInterval(): event = event # type: QMouseEvent index = self.__popup.indexAt(event.pos()) if index.isValid(): self.__activateProxyIndex(index) if etype == QEvent.MouseMove and self.__popup is not None \ and obj is self.__popup.viewport(): event = event # type: QMouseEvent opt = QStyleOptionComboBox() self.initStyleOption(opt) style = self.style() # type: QStyle if style.styleHint(QStyle.SH_ComboBox_ListMouseTracking, opt, self): index = self.__popup.indexAt(event.pos()) if index.isValid() and \ index.flags() & (Qt.ItemIsEnabled | Qt.ItemIsSelectable): self.__popup.setCurrentIndex(index) if etype == QEvent.MouseButtonPress and self.__popup is obj: # Popup border or out of window mouse button press/release. # At least on windows this needs to be handled. style = self.style() opt = QStyleOptionComboBox() self.initStyleOption(opt) opt.subControls = QStyle.SC_All opt.activeSubControls = QStyle.SC_ComboBoxArrow pos = self.mapFromGlobal(event.globalPos()) sc = style.hitTestComplexControl(QStyle.CC_ComboBox, opt, pos, self) if sc != QStyle.SC_None: self.__popup.setAttribute(Qt.WA_NoMouseReplay) self.hidePopup() return super().eventFilter(obj, event)
def copy_to_clipboard(self): text = self._web_view.selectedText() QApplication.clipboard().setText(text)
def showPopup(self): # type: () -> None # reimplemented super().showPopup() if self.__in_mousePressEvent: self.__yamrit.start(QApplication.doubleClickInterval())
def main(): # pragma: no cover from AnyQt.QtWidgets import QApplication from orangewidget.widget import OWBaseWidget app = QApplication([]) save_plot(None, OWBaseWidget.graph_writers)
def setUp(self): self.app = QApplication([]) QTimer.singleShot(20000, self.app.exit)
def __init__(self): super().__init__() #: widget's runtime state self.__state = State.NoState self.data = None self._n_image_categories = 0 self._n_image_data = 0 self._n_skipped = 0 self.__invalidated = False self.__pendingTask = None vbox = gui.vBox(self.controlArea) hbox = gui.hBox(vbox) self.recent_cb = QComboBox( sizeAdjustPolicy=QComboBox.AdjustToMinimumContentsLengthWithIcon, minimumContentsLength=16, acceptDrops=True) self.recent_cb.installEventFilter(self) self.recent_cb.activated[int].connect(self.__onRecentActivated) icons = standard_icons(self) browseaction = QAction( "Open/Load Images", self, iconText="\N{HORIZONTAL ELLIPSIS}", icon=icons.dir_open_icon, toolTip="Select a directory from which to load the images") browseaction.triggered.connect(self.__runOpenDialog) reloadaction = QAction("Reload", self, icon=icons.reload_icon, toolTip="Reload current image set") reloadaction.triggered.connect(self.reload) self.__actions = namespace( browse=browseaction, reload=reloadaction, ) browsebutton = QPushButton(browseaction.iconText(), icon=browseaction.icon(), toolTip=browseaction.toolTip(), clicked=browseaction.trigger) reloadbutton = QPushButton( reloadaction.iconText(), icon=reloadaction.icon(), clicked=reloadaction.trigger, default=True, ) hbox.layout().addWidget(self.recent_cb) hbox.layout().addWidget(browsebutton) hbox.layout().addWidget(reloadbutton) self.addActions([browseaction, reloadaction]) reloadaction.changed.connect( lambda: reloadbutton.setEnabled(reloadaction.isEnabled())) box = gui.vBox(vbox, "Info") self.infostack = QStackedWidget() self.info_area = QLabel(text="No image set selected", wordWrap=True) self.progress_widget = QProgressBar(minimum=0, maximum=0) self.cancel_button = QPushButton( "Cancel", icon=icons.cancel_icon, ) self.cancel_button.clicked.connect(self.cancel) w = QWidget() vlayout = QVBoxLayout() vlayout.setContentsMargins(0, 0, 0, 0) hlayout = QHBoxLayout() hlayout.setContentsMargins(0, 0, 0, 0) hlayout.addWidget(self.progress_widget) hlayout.addWidget(self.cancel_button) vlayout.addLayout(hlayout) self.pathlabel = TextLabel() self.pathlabel.setTextElideMode(Qt.ElideMiddle) self.pathlabel.setAttribute(Qt.WA_MacSmallSize) vlayout.addWidget(self.pathlabel) w.setLayout(vlayout) self.infostack.addWidget(self.info_area) self.infostack.addWidget(w) box.layout().addWidget(self.infostack) self.__initRecentItemsModel() self.__invalidated = True self.__executor = ThreadExecutor(self) QApplication.postEvent(self, QEvent(RuntimeEvent.Init))
def get_instance(): app_inst = QApplication.instance() if not hasattr(app_inst, "_report_window"): report = OWReport() app_inst._report_window = report return app_inst._report_window
genes_column.setData( set(gene_set.genes), Qt.UserRole ) # store genes to get then on output on selection model_items.append( [count_column, genes_column, category_column, term_column]) return model_items def init_item_model(self): if self.data_model: self.data_model.clear() self.setup_filter_model() else: self.data_model = QStandardItemModel() self.data_model.setSortRole(Qt.UserRole) self.data_model.setHorizontalHeaderLabels(self.DATA_HEADER_LABELS) def sizeHint(self): return QSize(1280, 960) if __name__ == "__main__": from AnyQt.QtWidgets import QApplication app = QApplication([]) ow = OWGeneSets() ow.show() app.exec_()
def _invalidate(self): self.__invalidated = True QApplication.postEvent(self, QEvent(self.Invalidate))
self, "weight_type", orientation=Qt.Horizontal, label="Weight:", items=[i.capitalize() for i in self.weights], callback=self.settings_changed) def create_learner(self): return self.LEARNER(n_neighbors=self.n_neighbors, metric=self.metrics[self.metric_index], weights=self.weights[self.weight_type], preprocessors=self.preprocessors) def get_learner_parameters(self): return (("Number of neighbours", self.n_neighbors), ("Metric", self.metrics[self.metric_index].capitalize()), ("Weight", self.weights[self.weight_type].capitalize())) if __name__ == "__main__": import sys from AnyQt.QtWidgets import QApplication a = QApplication(sys.argv) ow = OWKNNLearner() d = Table('iris') ow.set_data(d) ow.show() a.exec_() ow.saveSettings()
times.append(key_time) subset = data[list(indices)] xs, ys, ms = [], [], [] for attr, func in self.model: values = Table.from_table( Domain([], [], [attr], source=data.domain), subset).metas out = (xs if attr in data.domain.attributes else ys if attr in data.domain.class_vars else ms) out.append(func(values)) X.append(xs) Y.append(ys) M.append(ms) ts = Timeseries(Domain([data.time_variable] + attrs, cvars, metas), np.column_stack((times, np.row_stack(X))), np.array(Y), np.array(np.row_stack(M), dtype=object)) self.Outputs.time_series.send(ts) if __name__ == "__main__": from AnyQt.QtWidgets import QApplication a = QApplication([]) ow = OWAggregate() ow.set_data(Timeseries.from_file('airpassengers')) ow.show() a.exec()
def mousePressEvent(self, ev: QGraphicsSceneMouseEvent): keys = QApplication.keyboardModifiers() if self.__state == SELECT and not keys & Qt.ShiftModifier: ev.accept() self.sigDeselect.emit() super().mousePressEvent(ev)
def commit(self): if not self._invalidated: self._invalidated = True QApplication.postEvent(self, QEvent(QEvent.User))
def get_canvas_instance(): for widget in QApplication.topLevelWidgets(): if isinstance(widget, CanvasMainWindow): return widget if __name__ == "__main__": import sys from Orange.data import Table from Orange.widgets.data.owfile import OWFile from Orange.widgets.data.owtable import OWDataTable from Orange.widgets.data.owdiscretize import OWDiscretize from Orange.widgets.classify.owrandomforest import OWRandomForest iris = Table("iris") app = QApplication(sys.argv) main = OWReport.get_instance() file = OWFile() file.create_report_html() main.make_report(file) table = OWDataTable() table.set_dataset(iris) table.create_report_html() main.make_report(table) main = OWReport.get_instance() disc = OWDiscretize() disc.create_report_html() main.make_report(disc)
def showPopup(self): # type: () -> None """ Reimplemented from QComboBox.showPopup Popup up a customized view and filter edit line. Note ---- The .popup(), .lineEdit(), .completer() of the base class are not used. """ if self.__popup is not None: # We have user entered state that cannot be disturbed # (entered filter text, scroll offset, ...) return # pragma: no cover if self.count() == 0: return opt = QStyleOptionComboBox() self.initStyleOption(opt) popup = QListView( uniformItemSizes=True, horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOff, verticalScrollBarPolicy=Qt.ScrollBarAsNeeded, iconSize=self.iconSize(), ) popup.setFocusProxy(self.__searchline) popup.setParent(self, Qt.Popup | Qt.FramelessWindowHint) popup.setItemDelegate(_ComboBoxListDelegate(popup)) proxy = QSortFilterProxyModel( popup, filterCaseSensitivity=Qt.CaseInsensitive ) proxy.setFilterKeyColumn(self.modelColumn()) proxy.setSourceModel(self.model()) popup.setModel(proxy) root = proxy.mapFromSource(self.rootModelIndex()) popup.setRootIndex(root) self.__popup = popup self.__proxy = proxy self.__searchline.setText("") self.__searchline.setPlaceholderText("Filter...") self.__searchline.setVisible(True) self.__searchline.textEdited.connect(proxy.setFilterFixedString) style = self.style() # type: QStyle popuprect_origin = style.subControlRect( QStyle.CC_ComboBox, opt, QStyle.SC_ComboBoxListBoxPopup, self ) # type: QRect if sys.platform == "darwin": slmargin = self.__searchline.style() \ .pixelMetric(QStyle.PM_FocusFrameVMargin) popuprect_origin.adjust(slmargin // 2, 0, -(slmargin * 3) // 2, slmargin) popuprect_origin = QRect( self.mapToGlobal(popuprect_origin.topLeft()), popuprect_origin.size() ) editrect = style.subControlRect( QStyle.CC_ComboBox, opt, QStyle.SC_ComboBoxEditField, self ) # type: QRect self.__searchline.setGeometry(editrect) screenrect = self.screen().availableGeometry() # get the height for the view listrect = QRect() for i in range(min(proxy.rowCount(root), self.maxVisibleItems())): index = proxy.index(i, self.modelColumn(), root) if index.isValid(): listrect = listrect.united(popup.visualRect(index)) if listrect.height() >= screenrect.height(): break window = popup.window() # type: QWidget window.ensurePolished() if window.layout() is not None: window.layout().activate() else: QApplication.sendEvent(window, QEvent(QEvent.LayoutRequest)) margins = qwidget_margin_within(popup.viewport(), window) height = (listrect.height() + 2 * popup.spacing() + margins.top() + margins.bottom()) popup_size = (QSize(popuprect_origin.width(), height) .expandedTo(window.minimumSize()) .boundedTo(window.maximumSize()) .boundedTo(screenrect.size())) popuprect = QRect(popuprect_origin.bottomLeft(), popup_size) popuprect = dropdown_popup_geometry( popuprect, popuprect_origin, screenrect) popup.setGeometry(popuprect) current = proxy.mapFromSource( self.model().index(self.currentIndex(), self.modelColumn(), self.rootModelIndex())) popup.setCurrentIndex(current) popup.scrollTo(current, QAbstractItemView.EnsureVisible) popup.show() popup.setFocus(Qt.PopupFocusReason) popup.installEventFilter(self) popup.viewport().installEventFilter(self) popup.viewport().setMouseTracking(True) self.update() self.__popupTimer.restart()
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 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 __init__(self, widget=None): self.widget = widget if widget is None: self.style = QApplication.instance().style() else: self.style = widget.style()
def setUp(self): from AnyQt.QtWidgets import QApplication self.app = QApplication.instance() if self.app is None: self.app = QApplication([])
def set_corner_text(self, table, text): """Set table corner text.""" # As this is an ugly hack, do everything in # try - except blocks, as it may stop working in newer Qt. # pylint: disable=broad-except if not hasattr(table, "btn") and not hasattr(table, "btnfailed"): try: btn = table.findChild(QAbstractButton) class Efc(QObject): @staticmethod def eventFilter(o, e): if (isinstance(o, QAbstractButton) and e.type() == QEvent.Paint): # paint by hand (borrowed from QTableCornerButton) btn = o opt = QStyleOptionHeader() opt.initFrom(btn) state = QStyle.State_None if btn.isEnabled(): state |= QStyle.State_Enabled if btn.isActiveWindow(): state |= QStyle.State_Active if btn.isDown(): state |= QStyle.State_Sunken opt.state = state opt.rect = btn.rect() opt.text = btn.text() opt.position = QStyleOptionHeader.OnlyOneSection painter = QStylePainter(btn) painter.drawControl(QStyle.CE_Header, opt) return True # eat event return False table.efc = Efc() # disconnect default handler for clicks and connect a new one, which supports # both selection and deselection of all data btn.clicked.disconnect() btn.installEventFilter(table.efc) btn.clicked.connect(self._on_select_all) table.btn = btn if sys.platform == "darwin": btn.setAttribute(Qt.WA_MacSmallSize) except Exception: table.btnfailed = True if hasattr(table, "btn"): try: btn = table.btn btn.setText(text) opt = QStyleOptionHeader() opt.text = btn.text() s = btn.style().sizeFromContents( QStyle.CT_HeaderSection, opt, QSize(), btn).expandedTo(QApplication.globalStrut()) if s.isValid(): table.verticalHeader().setMinimumWidth(s.width()) except Exception: pass
def _export(exporter, _): buffer = exporter.export(toBytes=True) mimedata = QMimeData() mimedata.setData("image/png", buffer) QApplication.clipboard().setMimeData(mimedata)
def main(): from AnyQt.QtWidgets import QApplication app = QApplication([]) w = OWLoadModel() w.show() return app.exec_()
def _save_buffer(buffer, _): QApplication.clipboard().setPixmap(buffer)
def copy_to_clipboard(self): self._save_selected(actual=True) if self.selected is not None: output = "\n".join( [str(self.classifier.rule_list[i]) for i in self.selected]) QApplication.clipboard().setText(output)
return QRectF(0, 0, self.width, self.height) def sizeHint(self, which, constraint): return QSizeF(self.width, self.height) def sizePolicy(self): return QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) if __name__ == '__main__': import sys from Orange.data.table import Table from AnyQt.QtWidgets import ( # pylint: disable=ungrouped-imports QGraphicsView, QGraphicsScene, QApplication, QWidget) app = QApplication(sys.argv) widget = QWidget() widget.resize(500, 300) scene = QGraphicsScene(widget) view = QGraphicsView(scene, widget) dataset = Table(sys.argv[1] if len(sys.argv) > 1 else 'iris') histogram = Histogram( dataset, variable=0, height=300, width=500, n_bins=20, bar_spacing=2, border=(0, 0, 5, 0), border_color='#000', color_attribute='iris',
def get_canvas_instance(): for widget in QApplication.topLevelWidgets(): if isinstance(widget, CanvasMainWindow): return widget
def set_instance(report): app_inst = QApplication.instance() app_inst._report_window = report
class WidgetCatalog: def __init__(self, output_dir, image_url_prefix): self.output_dir = output_dir self.image_url_prefix = image_url_prefix self.app = QApplication([]) self.app.setAttribute(Qt.AA_EnableHighDpiScaling) self.app.setAttribute(Qt.AA_UseHighDpiPixmaps) print("Generating widget repository") self.registry = self.__get_widget_registry() print("Locating help files") self.help_manager = HelpManager() self.help_manager.set_registry(self.registry) # Help manager needs QApplication running to get the urls # of widget documentation. 5 seconds should be enough. QTimer.singleShot(5000, self.app.quit) self.app.exec() self.__scene = QGraphicsScene() self.__nodes = [] print("Ready to go") def create(self): print("Generating catalog") try: makedirs(path.join(self.output_dir, "icons")) except FileExistsError: pass result = [] for category in self.registry.categories(): widgets = [] result.append((category.name, widgets)) for widget in category.widgets: widgets.append({ "text": widget.name, "doc": self.__get_help(widget), "img": self.__get_icon(widget, category), "keyword": widget.keywords, }) with open(path.join(self.output_dir, "widgets.json"), 'wt') as f: json.dump(result, f, indent=1) print("Done") @staticmethod def __get_widget_registry(): widget_discovery = QtWidgetDiscovery() widget_registry = QtWidgetRegistry() widget_discovery.found_category.connect( widget_registry.register_category) widget_discovery.found_widget.connect(widget_registry.register_widget) widget_discovery.run(config.widgets_entry_points()) # Fixup category.widgets list for cat, widgets in widget_registry._categories_dict.values(): cat.widgets = widgets return widget_registry def __get_icon(self, widget, category=None): # Set remove inputs/outputs so the "ears" are not drawn widget = copy(widget) widget.inputs = [] widget.outputs = [] w = IconWidget() w.set_widget(widget, category) w.show() #self.app.processEvents() filename = "icons/{}.png".format(widget.qualified_name) w.render_as_png(path.join(self.output_dir, filename)) w.hide() if self.image_url_prefix: return self.image_url_prefix + filename else: return filename def __get_help(self, widget): query = dict(id=widget.qualified_name) try: return self.help_manager.search(query).url() except KeyError: return None
def paint(self, painter, option, index): dist = self.distribution(index) if dist is None or self.__colors is None: return super().paint(painter, option, index) if not numpy.isfinite(numpy.sum(dist)): return super().paint(painter, option, index) nvalues = len(dist) if len(self.__colors) < nvalues: colors = colorpalette.ColorPaletteGenerator(nvalues) colors = [colors[i] for i in range(nvalues)] else: colors = self.__colors if option.widget is not None: style = option.widget.style() else: style = QApplication.style() self.initStyleOption(option, index) text = option.text metrics = option.fontMetrics margin = style.pixelMetric(QStyle.PM_FocusFrameHMargin, option, option.widget) + 1 bottommargin = min(margin, 1) rect = option.rect.adjusted(margin, margin, -margin, -bottommargin) textrect = style.subElementRect(QStyle.SE_ItemViewItemText, option, option.widget) # Are the margins included in the subElementRect?? -> No! textrect = textrect.adjusted(margin, margin, -margin, -bottommargin) text = option.fontMetrics.elidedText(text, option.textElideMode, textrect.width()) spacing = max(metrics.leading(), 1) distheight = rect.height() - metrics.height() - spacing distheight = numpy.clip(distheight, 2, metrics.height()) painter.save() painter.setClipRect(option.rect) painter.setFont(option.font) painter.setRenderHint(QPainter.Antialiasing) style.drawPrimitive(QStyle.PE_PanelItemViewRow, option, painter, option.widget) style.drawPrimitive(QStyle.PE_PanelItemViewItem, option, painter, option.widget) if option.state & QStyle.State_Selected: color = option.palette.highlightedText().color() else: color = option.palette.text().color() painter.setPen(QtGui.QPen(color)) textrect = textrect.adjusted(0, 0, 0, -distheight - spacing) distrect = QtCore.QRect( textrect.bottomLeft() + QtCore.QPoint(0, spacing), QtCore.QSize(rect.width(), distheight)) painter.setPen(QtGui.QPen(Qt.lightGray, 0.3)) drawDistBar(painter, distrect, dist, colors) painter.restore() if text: style.drawItemText(painter, textrect, option.displayAlignment, option.palette, option.state & QStyle.State_Enabled, text)
def setUp(self): from AnyQt.QtWidgets import QApplication self.app = QApplication([])
self.fillCurve.setData([0, 1], [0]) if not len(values): self.curve.setData([0, 1], [0]) self.setBoundary(0, 0) self.autoRange() return nbins = min(len(values), 100) freq, edges = np.histogram(values, bins=nbins) self.curve.setData(edges, freq) self.setBoundary(edges[0], edges[-1]) self.autoRange() @property def xData(self): return self.curve.xData @property def yData(self): return self.curve.yData if __name__ == "__main__": from Orange.distance import Euclidean appl = QApplication([]) data = Table('iris') dm = Euclidean(data) ow = OWDuplicates() ow.set_distances(dm) ow.show() appl.exec_()