class JBApplet(plasmascript.Applet): def __init__(self,parent,args=None): plasmascript.Applet.__init__(self,parent) def init(self): self.setHasConfigurationInterface(True) self.setAspectRatioMode(Plasma.Rectangle) self.theme = Plasma.Svg(self) self.theme.setImagePath("widgets/background") self.setBackgroundHints(Plasma.Applet.DefaultBackground) self.layout = QGraphicsLinearLayout(Qt.Horizontal, self.applet) label= Plasma.Label(self.applet) label.setText("Jupiter Broadcasting") self.layout.addItem(label) self.applet.setLayout(self.layout) self.resize(640, 480) app = QApplication(sys.argv) web = QWebView() web.load(QUrl("http://jb.cdn.scaleengine.net/jw/jwplayer.swf")) web.show() def CreateApplet(parent): return JBApplet(parent)
def makeLayout(self): self.layout = QGraphicsLinearLayout(Qt.Vertical) self.flowComboLayout = QGraphicsLinearLayout(Qt.Horizontal) self.flowLabelLayout = QGraphicsGridLayout() #Flow Layout self.flowData = SvJanez() self.flowView = QGraphicsWebView() self.flowView.setUrl( QUrl(self.flowData.flowImageUrl) ) self.flowView.setEnabled(False) self.flowSelectorCombo = Plasma.ComboBox() self.flowSelectorCombo.addItem(u"Sveti Janez") self.flowSelectorCombo.addItem(u"Soteska") self.flowSelectorCombo.setMinimumWidth(125) self.flowSelectorCombo.textChanged.connect(self.flowSourceChanged) self.flowRefresh = Plasma.IconWidget() self.flowRefresh.setIcon("view-refresh") self.flowRefresh.clicked.connect(self.update) self.flowEnlargeButton = Plasma.IconWidget() self.flowEnlargeButton.setIcon("zoom-in") self.flowEnlargeButton.clicked.connect(self.showFullFlowWidget) self.flowLabel = Plasma.Label() self.flowLabel.setText(u"<b>Pretok:</b> ") self.flowDataLabel = Plasma.Label() self.flowLevelLabel = Plasma.Label() self.flowLevelLabel.setText(u"<b>Višina:</b> ") self.flowLevelDataLabel = Plasma.Label() self.flowTempLabel = Plasma.Label() self.flowTempLabel.setText(u"<b>Temperatura:</b> ") self.flowTempDataLabel = Plasma.Label() self.flowLabelLayout.addItem(self.flowLevelLabel,0,0) self.flowLabelLayout.addItem(self.flowLevelDataLabel,0,1) self.flowLabelLayout.addItem(self.flowLabel,1,0) self.flowLabelLayout.addItem(self.flowDataLabel,1,1) self.flowLabelLayout.addItem(self.flowTempLabel,2,0) self.flowLabelLayout.addItem(self.flowTempDataLabel,2,1) self.flowUpdateTimeSelector = UpdateTimeSelector() self.flowUpdateTimeSelector.setDefaultTime(4) self.flowUpdateTimeSelector.setDefaultInterval('h') self.flowUpdateTimeSelector.updateTimeSpin.valueChanged.connect(self.flowTimeChanged) self.flowUpdateTimeSelector.updateCheckBox.toggled.connect(self.flowTimerToggle) self.flowComboLayout.addItem(self.flowSelectorCombo) self.flowComboLayout.addStretch() self.flowComboLayout.addItem(self.flowEnlargeButton) self.flowComboLayout.addItem(self.flowRefresh) self.layout.addItem(self.flowComboLayout) self.layout.addItem(self.flowView) self.layout.addItem(self.flowLabelLayout) self.layout.addStretch() self.layout.addItem(self.flowUpdateTimeSelector.layout) self.layout.itemAt(0).setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed, QSizePolicy.DefaultType) self.layout.itemAt(2).setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed, QSizePolicy.DefaultType)
def setLayout(self): global label self.layout = QGraphicsLinearLayout(Qt.Vertical, self.applet) label = Plasma.Label(self.applet) setLabel() self.layout.addItem(label) self.applet.setLayout(self.layout)
class NetMonitor(plasmascript.Applet): def __init__(self, parent, args=None): plasmascript.Applet.__init__(self, parent) def init(self): self.setHasConfigurationInterface(False) self.setAspectRatioMode(Plasma.Square) self.theme = Plasma.Svg(self) self.theme.setImagePath("widgets/background") self.setBackgroundHints(Plasma.Applet.DefaultBackground) self.layout = QGraphicsLinearLayout(Qt.Horizontal, self.applet) self.monitoring = {} self.widgets = {} for source in self.connectToEngine(): label = Plasma.Label(self.applet) label.setText("%s:" % source) self.layout.addItem(label) self.widgets[str(source)] = label self.monitoring[str(source)] = {"in": 0, "out": 0} self.applet.setLayout(self.layout) def connectToEngine(self): self.engine = self.dataEngine("net_monitor_data") self.sources = self.engine.sources() for source in self.sources: self.engine.connectSource(source, self, 1000) return self.sources @pyqtSignature( "dataUpdated(const QString &, const Plasma::DataEngine::Data &)") def dataUpdated(self, sourceName, data): """Got something from data source""" iface = str(sourceName) if iface not in self.widgets: print "Error: data for %s not available yet" % iface return widget = self.widgets[iface] data_in = int(data[QString("data_in")]) data_out = int(data[QString("data_out")]) old_data_in = self.monitoring[iface]["in"] old_data_out = self.monitoring[iface]["out"] if old_data_in == -1: speed_in = 0 else: speed_in = data_in - old_data_in if old_data_out == -1: speed_out = 0 else: speed_out = data_out - old_data_out self.monitoring[iface]["in"] = data_in self.monitoring[iface]["out"] = data_out widget.setText("%s\n\/: %d\n/\: %d" % (sourceName, speed_in, speed_out)) def paintInterface(self, painter, option, rect): painter.save() painter.restore()
class hwTempApp(plasmascript.Applet): def __init__(self, parent, args=None): plasmascript.Applet.__init__(self, parent) def init(self): self.setHasConfigurationInterface(False) self.setAspectRatioMode(Plasma.Square) self.setTheme() self.setLayout() self.startTimer(10000) self.resize(100, 50) def timerEvent(self, evt): setLabel() def setTheme(self): self.theme = Plasma.Svg(self) self.theme.setImagePath("widgets/background") self.setBackgroundHints(Plasma.Applet.DefaultBackground) def setLayout(self): global label self.layout = QGraphicsLinearLayout(Qt.Vertical, self.applet) label = Plasma.Label(self.applet) setLabel() self.layout.addItem(label) self.applet.setLayout(self.layout)
def setLayout(self): global labels self.layout = QGraphicsLinearLayout(Qt.Vertical, self.applet) setLabels(self.applet) for label in labels: self.layout.addItem(label) self.applet.setLayout(self.layout)
class hwTempApp(plasmascript.Applet): def __init__(self,parent,args=None): plasmascript.Applet.__init__(self,parent) def init(self): self.setHasConfigurationInterface(False) self.setAspectRatioMode(Plasma.Square) self.setTheme() self.setLayout() self.startTimer(10000) self.resize(100,50) def timerEvent(self,evt): setLabel() def setTheme(self): self.theme = Plasma.Svg(self) self.theme.setImagePath("widgets/background") self.setBackgroundHints(Plasma.Applet.DefaultBackground) def setLayout(self): global label self.layout = QGraphicsLinearLayout(Qt.Vertical, self.applet) label = Plasma.Label(self.applet) setLabel() self.layout.addItem(label) self.applet.setLayout(self.layout)
class PythonShellApplet(plasmascript.Applet): def __init__(self,parent,args=None): plasmascript.Applet.__init__(self,parent) def init(self): logger.debug("Starting qidle...") event_loop = QEventLoop() self.factory = InsulatedFactory(event_loop = event_loop) self.factory.start() self.factory.start_event_loop() self.setHasConfigurationInterface(False) self.setAspectRatioMode(Plasma.IgnoreAspectRatio) self.theme = Plasma.Svg(self) self.theme.setImagePath("widgets/background") self.setBackgroundHints(Plasma.Applet.DefaultBackground) self.layout = QGraphicsLinearLayout(Qt.Vertical, self.applet) self.editorWidget = Plasma.TextEdit(self.applet) self.shell_widget = ShellWidget(self.factory,self.editorWidget.nativeWidget()) self.shell_widget._disable_completion() self.editorWidget.nativeWidget().setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.editorWidget.keyPressEvent = self.shell_widget.console_widget.keyPressEvent self.layout.addItem(self.editorWidget) self.resize(600,500) def __del__(self): self.shell_widget.quit() self.factory.terminate()
def init(self): #TODO: have a configuration interface to set keybroad shortcut #self.setHasConfigurationInterface(True) self.setAspectRatioMode(Plasma.ConstrainedSquare) self.setBackgroundHints(self.NoBackground) self.sessionBus = dbus.SessionBus() self.powerdevil = self.sessionBus.get_object( 'org.freedesktop.PowerManagement', '/modules/powerdevil') self.icon = Plasma.IconWidget(KIcon('preferences-desktop-screensaver'), '', self.applet) if KGlobalSettings.singleClick(): self.connect(self.icon, SIGNAL('clicked()'), self.turn_off_screen) else: self.connect(self.icon, SIGNAL('doubleClicked()'), self.turn_off_screen) self.connect(self, SIGNAL('active()'), self.turn_off_screen) self.layout = QGraphicsLinearLayout(self.applet) self.layout.setContentsMargins(0, 0, 0, 0) self.layout.setSpacing(0) self.layout.addItem(self.icon) self.setLayout(self.layout) self.resize(25, 25)
class MPDClient(plasmascript.Applet): def __init__(self, parent, args=None): plasmascript.Applet.__init__(self, parent) def init(self): self.setHasConfigurationInterface(False) self.setAspectRatioMode(Plasma.IgnoreAspectRatio) self.layout = QGraphicsLinearLayout(Qt.Vertical, self.applet) self.label = Plasma.Label(self.applet) self.label.setWordWrap(False) self.layout.addItem(self.label) self.mpd = mpd.MPDClient() try: self.mpd.connect(HOST, PORT) except: pass self.timer = QTimer() self.timer.connect(self.timer, SIGNAL("timeout()"), self.timeout) self.timer.start(1000) self.timeout() def timeout(self): status = "" try: status = self.mpd.status()["state"] except: try: self.mpd = mpd.MPDClient() self.mpd.connect(HOST, PORT) except: pass if status != "play": self.label.setText("Music stopped") return currentSong = self.mpd.currentsong() title = album = artist = "" longstr = "<b>" str = "" try: title = currentSong["title"] except: title = currentSong["file"].split("/")[-1] try: str = str + currentSong["artist"] + " - " + title except: str = str + title try: album = currentSong["album"] except: pass self.label.setText(str.decode("utf-8")[0:50])
class NetMonitor(plasmascript.Applet): def __init__(self,parent,args=None): plasmascript.Applet.__init__(self,parent) def init(self): self.setHasConfigurationInterface(False) self.setAspectRatioMode(Plasma.Square) self.theme = Plasma.Svg(self) self.theme.setImagePath("widgets/background") self.setBackgroundHints(Plasma.Applet.DefaultBackground) self.layout = QGraphicsLinearLayout(Qt.Horizontal, self.applet) self.monitoring = {} self.widgets = {} for source in self.connectToEngine(): label = Plasma.Label(self.applet) label.setText("%s:" % source) self.layout.addItem(label) self.widgets[str(source)] = label self.monitoring[str(source)] = {"in": 0, "out": 0} self.applet.setLayout(self.layout) def connectToEngine(self): self.engine = self.dataEngine("net_monitor_data") self.sources = self.engine.sources() for source in self.sources: self.engine.connectSource(source, self, 1000) return self.sources @pyqtSignature("dataUpdated(const QString &, const Plasma::DataEngine::Data &)") def dataUpdated(self, sourceName, data): """Got something from data source""" iface = str(sourceName) if iface not in self.widgets: print "Error: data for %s not available yet" % iface return widget = self.widgets[iface] data_in = int(data[QString("data_in")]) data_out = int(data[QString("data_out")]) old_data_in = self.monitoring[iface]["in"] old_data_out = self.monitoring[iface]["out"] if old_data_in == -1: speed_in = 0 else: speed_in = data_in - old_data_in if old_data_out == -1: speed_out = 0 else: speed_out = data_out - old_data_out self.monitoring[iface]["in"] = data_in self.monitoring[iface]["out"] = data_out widget.setText("%s\n\/: %d\n/\: %d" % (sourceName, speed_in, speed_out)) def paintInterface(self, painter, option, rect): painter.save() painter.restore()
class Kountdown(plasmascript.Applet): def __init__(self,parent,args=None): plasmascript.Applet.__init__(self,parent) def init(self): self.setHasConfigurationInterface(True) self.model = KountdownModel(self.configScheme()) if self.model.needsConfiguration: self.setConfigurationRequired(True) else: self.setupMainUI() self.resize(300,125) def setupMainUI(self): print 'setup' self.setAspectRatioMode(Plasma.IgnoreAspectRatio) self.setBackgroundHints(Plasma.Applet.TranslucentBackground) self.layout = QGraphicsLinearLayout(Qt.Vertical,self.applet) self.label = Plasma.Label(self.applet) self.label.setText(self.model.message) self.label.setStyleSheet('''font-size: 18pt;''') self.label.setAlignment(Qt.AlignCenter | Qt.AlignVCenter) self.layout.addItem(self.label) self.applet.setLayout(self.layout) self.connectToEngine() self.model.messageChanged.connect(self.handleMessageChanged) def configChanged(self): '''handle changes in configuration''' plasmascript.Applet.configChanged(self) self.updatedConfig() def updatedConfig(self): config = self.config() if self.configurationRequired() and not self.model.needsConfiguration: self.setConfigurationRequired(False) self.setupMainUI() def connectToEngine(self): self.timeEngine = self.dataEngine("time") self.model.connectToEngine(self.timeEngine) def handleMessageChanged(self, newMessage): '''Update the view when the message changes.''' self.label.setText(newMessage) self.update()
def __init__(self, labels=[], orientation=Qt.Vertical, alignment=Qt.AlignCenter, parent=None): QGraphicsWidget.__init__(self, parent) layout = QGraphicsLinearLayout(orientation) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(0) self.setLayout(layout) self.orientation = orientation self.alignment = alignment self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.label_items = [] self.set_labels(labels)
class Kountdown(plasmascript.Applet): def __init__(self, parent, args=None): plasmascript.Applet.__init__(self, parent) def init(self): self.setHasConfigurationInterface(True) self.model = KountdownModel(self.configScheme()) if self.model.needsConfiguration: self.setConfigurationRequired(True) else: self.setupMainUI() self.resize(300, 125) def setupMainUI(self): print 'setup' self.setAspectRatioMode(Plasma.IgnoreAspectRatio) self.setBackgroundHints(Plasma.Applet.TranslucentBackground) self.layout = QGraphicsLinearLayout(Qt.Vertical, self.applet) self.label = Plasma.Label(self.applet) self.label.setText(self.model.message) self.label.setStyleSheet('''font-size: 18pt;''') self.label.setAlignment(Qt.AlignCenter | Qt.AlignVCenter) self.layout.addItem(self.label) self.applet.setLayout(self.layout) self.connectToEngine() self.model.messageChanged.connect(self.handleMessageChanged) def configChanged(self): '''handle changes in configuration''' plasmascript.Applet.configChanged(self) self.updatedConfig() def updatedConfig(self): config = self.config() if self.configurationRequired() and not self.model.needsConfiguration: self.setConfigurationRequired(False) self.setupMainUI() def connectToEngine(self): self.timeEngine = self.dataEngine("time") self.model.connectToEngine(self.timeEngine) def handleMessageChanged(self, newMessage): '''Update the view when the message changes.''' self.label.setText(newMessage) self.update()
class XMonadLogPlasmoid(plasmascript.Applet): def __init__(self, parent, args=None): plasmascript.Applet.__init__(self, parent) @staticmethod def getToolButton(): x = Plasma.ToolButton() x.setContentsMargins(0, 0, 0, 0) x.nativeWidget().setToolButtonStyle(Qt.ToolButtonTextBesideIcon) return x @staticmethod def setToolButtonStyle(x, text, icon, color="#383838", font_weight="normal", text_decoration="none"): x.setIcon(KIcon(icon)) x.setText(text) style_sheet = "QToolButton { color: %s; font-weight: %s; text-decoration: %s; font-size: 11px; max-height: 18px; padding-top: 0; padding-bottom: 0; }" % (color, font_weight, text_decoration) x.nativeWidget().setStyleSheet(style_sheet) @staticmethod def getLabel(text, color="#383838", font_weight="normal", text_decoration="none"): x = Plasma.Label() x.setText(text) x.setContentsMargins(0, 0, 0, 0) x.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) x.setWordWrap(False) style_sheet = "QLabel { color: %s; font-weight: %s; text-decoration: %s; font-size: 11px; max-height: 20px; padding-left: 6px }" % (color, font_weight, text_decoration) x.nativeWidget().setStyleSheet(style_sheet) return x def setup_dbus(self): self.log = Log(self.layout) def init(self): global label self.setHasConfigurationInterface(False) self.setAspectRatioMode(Plasma.IgnoreAspectRatio) self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)) self.layout = QGraphicsLinearLayout(Qt.Horizontal) self.layout.setContentsMargins(0, 0, 0, 0) self.setContentsMargins(0, 0, 0, 0) self.applet.setLayout(self.layout) self.setMinimumHeight(30) self.setMaximumHeight(100) self.setMaximumWidth(900) self.layout.setMaximumHeight(100) self.setup_dbus()
def setupMainUI(self): print 'setup' self.setAspectRatioMode(Plasma.IgnoreAspectRatio) self.setBackgroundHints(Plasma.Applet.TranslucentBackground) self.layout = QGraphicsLinearLayout(Qt.Vertical, self.applet) self.label = Plasma.Label(self.applet) self.label.setText(self.model.message) self.label.setStyleSheet('''font-size: 18pt;''') self.label.setAlignment(Qt.AlignCenter | Qt.AlignVCenter) self.layout.addItem(self.label) self.applet.setLayout(self.layout) self.connectToEngine() self.model.messageChanged.connect(self.handleMessageChanged)
def init(self): global labels self.setHasConfigurationInterface(False) self.setAspectRatioMode(Plasma.Square) self.theme = Plasma.Svg(self) self.theme.setImagePath("widgets/background") self.setBackgroundHints(Plasma.Applet.DefaultBackground) self.layout = QGraphicsLinearLayout(Qt.Vertical, self.applet) makeLabels(self.applet) for label in labels: self.layout.addItem(label) self.applet.setLayout(self.layout) self.startTimer(8000) self.resize(400, 200)
def create_frame(self): self.frame = Plasma.Frame() self.frame_layout = QGraphicsLinearLayout(Qt.Vertical) self.frame.setEnabledBorders (Plasma.FrameSvg.NoBorder) self.frame.setFrameShadow(Plasma.Frame.Plain) self.frame_layout.setContentsMargins(0,0,0,0) self.frame.setLayout(self.frame_layout)
def init(self): global label self.setHasConfigurationInterface(False) self.setAspectRatioMode(Plasma.IgnoreAspectRatio) self.setSizePolicy( QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)) self.setMinimumWidth(425) self.layout = QGraphicsLinearLayout(Qt.Horizontal, self.applet) label = Plasma.Label(self.applet) label.setText("Waiting for XMonad...") self.layout.addItem(label) self.applet.setLayout(self.layout) self.setup_dbus() self.label_signal.connect(update_label)
def init(self): self.layout = QGraphicsLinearLayout(Qt.Vertical) self.layout.setContentsMargins(2,2,2,0) self.setLayout(self.layout) self.initArrangement() self.composeArrangement() self.setAcceptDrops(True) self._on_upate_expander_enabled()
def makeLayout(self): self.layout = QGraphicsLinearLayout(Qt.Vertical) self.topCamLayout = QGraphicsLinearLayout(Qt.Horizontal) # Cam layout self.camRefreshButton = Plasma.IconWidget() self.camRefreshButton.setIcon("view-refresh") self.camRefreshButton.clicked.connect(self.update) self.camTimeLabel = Plasma.Label() self.camTimeLabel.setText(u"ob") self.camEnlargeButton = Plasma.IconWidget() self.camEnlargeButton.setIcon("zoom-in") self.camEnlargeButton.clicked.connect(self.showFullCamWidget) self.camSelectorCombo = Plasma.ComboBox() for source in sorted(self.camUrls.keys()): self.camSelectorCombo.addItem(source) self.camSelectorCombo.setMinimumWidth(125) self.camSelectorCombo.textChanged.connect(self.camChanged) self.camView = QGraphicsWebView() self.camView.setEnabled(False) self.camTimeDataLabel = Plasma.Label() self.camUpdateTimeSelector = UpdateTimeSelector() self.camUpdateTimeSelector.setDefaultTime(30) self.camUpdateTimeSelector.setDefaultInterval('min') self.camUpdateTimeSelector.updateTimeSpin.valueChanged.connect(self.camTimeChanged) self.camUpdateTimeSelector.updateCheckBox.toggled.connect(self.camTimerToggle) self.topCamLayout.addItem(self.camSelectorCombo) self.topCamLayout.addItem(self.camTimeLabel) self.topCamLayout.addItem(self.camTimeDataLabel) self.topCamLayout.addStretch() self.topCamLayout.addItem(self.camEnlargeButton) self.topCamLayout.addItem(self.camRefreshButton) self.layout.addItem(self.topCamLayout) self.layout.addItem(self.camView) self.layout.addItem(self.camUpdateTimeSelector.layout) self.layout.itemAt(0).setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed, QSizePolicy.DefaultType) self.layout.itemAt(2).setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed, QSizePolicy.DefaultType)
class weatherApplet(plasmascript.Applet): def __init__(self,parent,args=None): plasmascript.Applet.__init__(self,parent) def init(self): self.setHasConfigurationInterface(False) self.setAspectRatioMode(Plasma.Square) self.theme = Plasma.Svg(self) self.theme.setImagePath("widgets/background") self.setBackgroundHints(Plasma.Applet.DefaultBackground) self.layout = QGraphicsLinearLayout(Qt.Horizontal, self.applet) label = Plasma.Label(self.applet) label.setText("Hello world!") self.layout.addItem(label) self.applet.setLayout(self.layout) self.resize(125,125)
def createMiddle(self): self.middle = QGraphicsWidget() self.middle_layout = QGraphicsLinearLayout(Qt.Vertical) #self.middle_layout.setContentsMargins(6,8,6,0) self.middle_layout.setContentsMargins(0,0,0,0) self.middle.setLayout(self.middle_layout) self.middle.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)) self.createSlider() self.middle_layout.addItem(self.slider)
def createMiddle(self): self.middle = Plasma.IconWidget() self.middle_layout = QGraphicsLinearLayout(Qt.Vertical) self.middle_layout.setContentsMargins(0,0,0,0) self.middle.setLayout(self.middle_layout) self.set_middle_size() self.middle.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)) if self.veromix.is_albumart_enabled(): self.middle.setIcon(KIcon(self.get_pauseIcon()))
class rssWidget(plasmascript.Applet): def __init__(self, parent, args=None): plasmascript.Applet.__init__(self, parent) def init(self): self.setLayout() self.startTimer(10000) def timerEvent(self, evt): setLabels(self.applet) def setLayout(self): global labels self.layout = QGraphicsLinearLayout(Qt.Vertical, self.applet) setLabels(self.applet) for label in labels: self.layout.addItem(label) self.applet.setLayout(self.layout)
def showModalWidget(self,mainWidget): #mainWidget.widgetClose.connect(self.destroyMessageOverlay) if self.messageOverlay: return if self.messageDialog: return corona = self.scene() mainWidget.adjustSize() hint = mainWidget.preferredSize() if (hint.height() > self.widget.size().height()) or (hint.width() > self.widget.size().width()): ## either a collapsed popup in h/v form factor or just too small, ## so show it in a dialog associated with ourselves #pass if (corona): corona.addOffscreenWidget(mainWidget) if (self.messageDialog): pass else: self.messageDialog = Plasma.Dialog() self.messageDialog.setGraphicsWidget(mainWidget) mainWidget.setParentItem(self.messageDialog.graphicsWidget ()) else: self.messageOverlay = self.createMessageOverlay() self.formatOverlay() self.messageOverlay.opacity = 0.8 mainWidget.setParentItem(self.messageOverlay) l = QGraphicsLinearLayout(self.messageOverlay) l.addItem(mainWidget) if self.messageDialog: pos = self.geometry().topLeft().toPoint() if (corona): pos = corona.popupPosition(self.applet, self.messageDialog.size()) self.messageDialog.move(pos) #self.locationToDirection(self.location()) self.messageDialog.animatedShow(Plasma.Direction(0)) self.hidePopup() else: self.messageOverlay.show()
def init(self): self.setAcceptsHoverEvents (True) self.layout = QGraphicsLinearLayout(Qt.Vertical, self) self.layout.setSizePolicy(QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)) self.scroller = LockableScrollWidget(self) self.scroller.setMinimumSize(120,90) self.layout.addItem(self.scroller) if self.applet.formFactor() != Plasma.Planar : self.scroller.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.source_panel = QGraphicsWidget() self.sink_panel = QGraphicsWidget() self.scrolled_panel_layout = QGraphicsLinearLayout(Qt.Vertical) self.scrolled_panel_widget = QGraphicsWidget() self.scrolled_panel_widget.setLayout(self.scrolled_panel_layout) self.scrolled_panel_layout.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)) self.scrolled_panel_layout.setContentsMargins(0,0,0,6) self.showsTabs = not self.applet.useTabs() self.switchView(True) self.source_panel_layout = SortedLayout(Qt.Vertical, False) self.source_panel_layout.setSpacing(0) self.source_panel.setLayout(self.source_panel_layout) self.source_panel_layout.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)) if self.showsTabs: self.source_panel_layout.addStretch() self.sink_panel_layout = SortedLayout(Qt.Vertical, False) self.sink_panel_layout.setSpacing(0) self.sink_panel.setLayout(self.sink_panel_layout) self.sink_panel_layout.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)) self.layout.setContentsMargins(0,0,0,0) self.source_panel_layout.setContentsMargins(0,0,0,0) self.sink_panel_layout.setContentsMargins(0,0,0,0) #QTimer.singleShot(4000, self.start_pa) self.start_pa() self.connect_mediaplayers()
def init(self): self.setHasConfigurationInterface(False) self.setAspectRatioMode(Plasma.Square) self.theme = Plasma.Svg(self) self.theme.setImagePath("widgets/background") self.setBackgroundHints(Plasma.Applet.DefaultBackground) self.layout = QGraphicsLinearLayout(Qt.Horizontal, self.applet) self.monitoring = {} self.widgets = {} for source in self.connectToEngine(): label = Plasma.Label(self.applet) label.setText("%s:" % source) self.layout.addItem(label) self.widgets[str(source)] = label self.monitoring[str(source)] = {"in": 0, "out": 0} self.applet.setLayout(self.layout)
def layout_widgets(self): # Layout if self.grid_layout <> None: del self.grid_layout self.grid_layout = QGraphicsGridLayout() header_layout = QGraphicsLinearLayout() header_layout.addItem(self.invert_button) header_layout.addItem(self.title_label) self.grid_layout.addItem(header_layout, 0, 0, 1, 2) #self.grid_layout.addItem(self.collapse_button, 0, 0) #self.grid_layout.addItem(self.title_label, 0, 1) self.grid_layout.addItem(self.from_label, 1, 0) self.grid_layout.addItem(self.currency_from, 1, 1) self.grid_layout.addItem(self.to_label, 2, 0) self.grid_layout.addItem(self.currency_to, 2, 1) self.grid_layout.addItem(self.amount_label, 3, 0) self.amount_layout = QGraphicsLinearLayout() self.amount_layout.addItem(self.amount) self.amount_layout.addItem(self.from_amount_label) self.amount_layout.addItem(self.equal_label) self.amount_layout.addItem(self.conversion_result) self.amount_layout.addItem(self.to_amount_label) self.grid_layout.addItem(self.amount_layout, 3, 1) self.grid_layout.addItem(self.credits_label, 4, 0, 1, 2) self.setLayout(self.grid_layout)
class TurnOffScreen(plasmascript.Applet): def __init__(self, parent, args = None): plasmascript.Applet.__init__(self, parent) def init(self): #TODO: have a configuration interface to set keybroad shortcut #self.setHasConfigurationInterface(True) self.setAspectRatioMode(Plasma.ConstrainedSquare) self.setBackgroundHints(self.NoBackground) self.sessionBus = dbus.SessionBus() self.powerdevil = self.sessionBus.get_object('org.freedesktop.PowerManagement', '/modules/powerdevil') self.icon= Plasma.IconWidget(KIcon('preferences-desktop-screensaver'), '', self.applet) if KGlobalSettings.singleClick(): self.connect(self.icon, SIGNAL('clicked()'), self.turn_off_screen) else: self.connect(self.icon, SIGNAL('doubleClicked()'), self.turn_off_screen) self.connect(self, SIGNAL('active()'), self.turn_off_screen) self.layout = QGraphicsLinearLayout(self.applet) self.layout.setContentsMargins(0, 0, 0, 0) self.layout.setSpacing(0) self.layout.addItem(self.icon) self.setLayout(self.layout) self.resize(25, 25) #def showConfigurationInterface(self): # self.con_short = KShortcutWidget(None) # self.con_short.show() def turn_off_screen(self): self.powerdevil.turnOffScreen(dbus_interface='org.kde.PowerDevil')
def init(self): self.setHasConfigurationInterface(False) #interface de configuration self.setAspectRatioMode(Plasma.IgnoreAspectRatio) #Possibilité de redimensionner / Plasma.IgnoreAspectRatio self.layout = QGraphicsLinearLayout(Qt.Horizontal, self.applet) #Création du layout self.label = Plasma.Label(self.applet) #Création du label self.layout.addItem(self.label) #Ajout du label au layout #self.setMinimumWidth(1000) #Largeur minimum #self.setMaximumHeight(900) #Hauteur maximum self.startTimer(1000)
class CommandesApplet(plasmascript.Applet): def __init__(self,parent,args=None): plasmascript.Applet.__init__(self,parent) def init(self): self.setHasConfigurationInterface(False) #interface de configuration self.setAspectRatioMode(Plasma.IgnoreAspectRatio) #Possibilité de redimensionner / Plasma.IgnoreAspectRatio self.layout = QGraphicsLinearLayout(Qt.Horizontal, self.applet) #Création du layout self.label = Plasma.Label(self.applet) #Création du label self.layout.addItem(self.label) #Ajout du label au layout #self.setMinimumWidth(1000) #Largeur minimum #self.setMaximumHeight(900) #Hauteur maximum self.startTimer(1000) def timerEvent(self, event): text = "%s" % os.popen(str('who')).read() self.label.setText(text) self.update()
class XMonadLogPlasmoid(plasmascript.Applet): label_signal = QtCore.pyqtSignal(str) session_bus = None def __init__(self, parent, args=None): plasmascript.Applet.__init__(self, parent) def init(self): global label self.setHasConfigurationInterface(False) self.setAspectRatioMode(Plasma.IgnoreAspectRatio) self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)) self.setMinimumWidth(425) self.layout = QGraphicsLinearLayout(Qt.Horizontal, self.applet) label = Plasma.Label(self.applet) label.setText("Waiting for XMonad...") self.layout.addItem(label) self.applet.setLayout(self.layout) self.setup_dbus() self.label_signal.connect(update_label) def setup_dbus(self): self.session_bus = dbus.SessionBus() proxy = self.session_bus.get_object( bus_name='org.xmonad.Log', object_path='/org/xmonad/Log') self.session_bus.add_signal_receiver( handler_function=self.msg_receive, signal_name='Update', dbus_interface='org.xmonad.Log') def msg_receive(self, msg): self.label_signal.emit(msg)
class hwTempApp(plasmascript.Applet): def __init__(self,parent,args=None): plasmascript.Applet.__init__(self,parent) def init(self): global labels self.setHasConfigurationInterface(False) self.setAspectRatioMode(Plasma.Square) self.theme = Plasma.Svg(self) self.theme.setImagePath("widgets/background") self.setBackgroundHints(Plasma.Applet.DefaultBackground) self.layout = QGraphicsLinearLayout(Qt.Vertical, self.applet) makeLabels(self.applet) for label in labels: self.layout.addItem(label) self.applet.setLayout(self.layout) self.startTimer(8000) self.resize(400,200) def timerEvent(self,evt): strings = getStrings() updateLabels(strings)
class XMonadLogPlasmoid(plasmascript.Applet): label_signal = QtCore.pyqtSignal(str) session_bus = None def __init__(self, parent, args=None): plasmascript.Applet.__init__(self, parent) def init(self): global label self.setHasConfigurationInterface(False) self.setAspectRatioMode(Plasma.IgnoreAspectRatio) self.setSizePolicy( QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)) self.setMinimumWidth(425) self.layout = QGraphicsLinearLayout(Qt.Horizontal, self.applet) label = Plasma.Label(self.applet) label.setText("Waiting for XMonad...") self.layout.addItem(label) self.applet.setLayout(self.layout) self.setup_dbus() self.label_signal.connect(update_label) def setup_dbus(self): self.session_bus = dbus.SessionBus() proxy = self.session_bus.get_object(bus_name='org.xmonad.Log', object_path='/org/xmonad/Log') self.session_bus.add_signal_receiver(handler_function=self.msg_receive, signal_name='Update', dbus_interface='org.xmonad.Log') def msg_receive(self, msg): self.label_signal.emit(msg)
def init_applet(self): self.setHasConfigurationInterface(False) self.setAspectRatioMode(Plasma.IgnoreAspectRatio) self.theme = Plasma.Svg(self) self.theme.setImagePath("widgets/background") self.setBackgroundHints(Plasma.Applet.DefaultBackground) self.layout = QGraphicsLinearLayout(Qt.Horizontal, self.applet) self.output = Plasma.TextBrowser(self.applet) self.output.setText('initializing please wait ...') self.layout.addItem(self.output) self.applet.setLayout(self.layout) self.resize(600, 300)
def create_settings_widget(self): self.createLengthLabel() self.createPositionLabel() self.createSlider() self.extended_panel = QGraphicsWidget(self.frame) self.extended_panel_layout = QGraphicsLinearLayout(Qt.Horizontal) self.extended_panel.setLayout(self.extended_panel_layout) self.extended_panel.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)) self.position_label.setSizePolicy(QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)) self.length_label.setSizePolicy(QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)) self.extended_panel_layout.addItem(self.position_label) self.extended_panel_layout.addItem(self.slider) self.extended_panel_layout.addItem(self.length_label)
class hwTempApp(plasmascript.Applet): def __init__(self, parent, args=None): plasmascript.Applet.__init__(self, parent) def init(self): global labels self.setHasConfigurationInterface(False) self.setAspectRatioMode(Plasma.Square) self.theme = Plasma.Svg(self) self.theme.setImagePath("widgets/background") self.setBackgroundHints(Plasma.Applet.DefaultBackground) self.layout = QGraphicsLinearLayout(Qt.Vertical, self.applet) makeLabels(self.applet) for label in labels: self.layout.addItem(label) self.applet.setLayout(self.layout) self.startTimer(8000) self.resize(400, 200) def timerEvent(self, evt): strings = getStrings() updateLabels(strings)
def init(self): global label self.setHasConfigurationInterface(False) self.setAspectRatioMode(Plasma.IgnoreAspectRatio) self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)) self.setMinimumWidth(425) self.layout = QGraphicsLinearLayout(Qt.Horizontal, self.applet) label = Plasma.Label(self.applet) label.setText("Waiting for XMonad...") self.layout.addItem(label) self.applet.setLayout(self.layout) self.setup_dbus() self.label_signal.connect(update_label)
def init(self): global label self.setHasConfigurationInterface(False) self.setAspectRatioMode(Plasma.IgnoreAspectRatio) self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)) self.layout = QGraphicsLinearLayout(Qt.Horizontal) self.layout.setContentsMargins(0, 0, 0, 0) self.setContentsMargins(0, 0, 0, 0) self.applet.setLayout(self.layout) self.setMinimumHeight(30) self.setMaximumHeight(100) self.setMaximumWidth(900) self.layout.setMaximumHeight(100) self.setup_dbus()
def __init__(self, show_unit_value = False, unit_symbol="%"): QGraphicsWidget.__init__(self) self.meter = None self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed,True)) self.slider = LabelSlider(show_unit_value, unit_symbol) self.slider.setParent(self) self.slider.volumeChanged.connect(self.on_volume_changed) self.layout = QGraphicsLinearLayout(Qt.Vertical) self.layout.setContentsMargins(2,2,2,0) self.setLayout(self.layout) self.layout.addItem(self.slider) self.connect(self, SIGNAL("geometryChanged()"), self._resize_widgets)
def init(self): global labels self.setHasConfigurationInterface(False) self.setAspectRatioMode(Plasma.Square) self.theme = Plasma.Svg(self) self.theme.setImagePath("widgets/background") self.setBackgroundHints(Plasma.Applet.DefaultBackground) self.layout = QGraphicsLinearLayout(Qt.Vertical, self.applet) makeLabels(self.applet) for label in labels: self.layout.addItem(label) self.applet.setLayout(self.layout) self.startTimer(8000) self.resize(400,200)
def __init__(self, labels=[], orientation=Qt.Vertical, parent=None): QGraphicsWidget.__init__(self, parent) layout = QGraphicsLinearLayout(orientation) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(0) self.setLayout(layout) self.orientation = orientation self.alignment = Qt.AlignCenter self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.label_items = [] self.set_labels(labels)
def __init__(self, parent=None, direction=Qt.LeftToRight, node=None, icon=None, iconSize=None, **args): QGraphicsWidget.__init__(self, parent, **args) self.setAcceptedMouseButtons(Qt.NoButton) self.__direction = direction self.setLayout(QGraphicsLinearLayout(Qt.Horizontal)) # Set the maximum size, otherwise the layout can't grow beyond its # sizeHint (and we need it to grow so the widget can grow and keep the # contents centered vertically. self.layout().setMaximumSize(QSizeF(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX)) self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) self.__iconSize = iconSize or QSize(64, 64) self.__icon = icon self.__iconItem = QGraphicsPixmapItem(self) self.__iconLayoutItem = GraphicsItemLayoutItem(item=self.__iconItem) self.__channelLayout = QGraphicsGridLayout() self.__channelAnchors = [] if self.__direction == Qt.LeftToRight: self.layout().addItem(self.__iconLayoutItem) self.layout().addItem(self.__channelLayout) channel_alignemnt = Qt.AlignRight else: self.layout().addItem(self.__channelLayout) self.layout().addItem(self.__iconLayoutItem) channel_alignemnt = Qt.AlignLeft self.layout().setAlignment(self.__iconLayoutItem, Qt.AlignCenter) self.layout().setAlignment(self.__channelLayout, Qt.AlignVCenter | channel_alignemnt) if node is not None: self.setSchemeNode(node)
def __init__(self, *args, **kwargs): QGraphicsWidget.__init__(self, *args, **kwargs) self.setAcceptedMouseButtons(Qt.LeftButton | Qt.RightButton) self.source = None self.sink = None # QGraphicsWidget/Items in the scene. self.sourceNodeWidget = None self.sourceNodeTitle = None self.sinkNodeWidget = None self.sinkNodeTitle = None self.__links = [] self.__textItems = [] self.__iconItems = [] self.__tmpLine = None self.__dragStartItem = None self.setLayout(QGraphicsLinearLayout(Qt.Vertical)) self.layout().setContentsMargins(0, 0, 0, 0)
def __init__(self, parent=None): super().__init__(parent) self.matrix = None self.items = None self.linkmatrix = None self.root = None self._displayed_root = None self.cutoff_height = 0.0 self._invalidated = False gui.comboBox(gui.widgetBox(self.controlArea, "Linkage"), self, "linkage", items=LINKAGE, callback=self._invalidate_clustering) box = gui.widgetBox(self.controlArea, "Annotation") self.label_cb = gui.comboBox(box, self, "annotation_idx", callback=self._update_labels) self.label_cb.setModel(itemmodels.VariableListModel()) self.label_cb.model()[:] = ["None", "Enumeration"] box = gui.radioButtons(self.controlArea, self, "pruning", box="Pruning", callback=self._invalidate_pruning) grid = QGridLayout() box.layout().addLayout(grid) grid.addWidget(gui.appendRadioButton(box, "None", addToLayout=False), 0, 0) self.max_depth_spin = gui.spin(box, self, "max_depth", minv=1, maxv=100, callback=self._invalidate_pruning, keyboardTracking=False) grid.addWidget( gui.appendRadioButton(box, "Max depth", addToLayout=False), 1, 0) grid.addWidget(self.max_depth_spin, 1, 1) box = gui.radioButtons(self.controlArea, self, "selection_method", box="Selection", callback=self._selection_method_changed) grid = QGridLayout() box.layout().addLayout(grid) grid.addWidget(gui.appendRadioButton(box, "Manual", addToLayout=False), 0, 0) grid.addWidget( gui.appendRadioButton(box, "Height ratio", addToLayout=False), 1, 0) self.cut_ratio_spin = gui.spin(box, self, "cut_ratio", 0, 100, step=1e-1, spinType=float, callback=self._selection_method_changed) self.cut_ratio_spin.setSuffix("%") grid.addWidget(self.cut_ratio_spin, 1, 1) grid.addWidget(gui.appendRadioButton(box, "Top N", addToLayout=False), 2, 0) self.top_n_spin = gui.spin(box, self, "top_n", 1, 20, callback=self._selection_method_changed) grid.addWidget(self.top_n_spin, 2, 1) box.layout().addLayout(grid) self.controlArea.layout().addStretch() box = gui.widgetBox(self.controlArea, "Output") gui.checkBox(box, self, "append_clusters", "Append cluster IDs", callback=self._invalidate_output) ibox = gui.indentedBox(box) name_edit = gui.lineEdit(ibox, self, "cluster_name") name_edit.editingFinished.connect(self._invalidate_output) cb = gui.comboBox( ibox, self, "cluster_role", callback=self._invalidate_output, items=["Attribute", "Class variable", "Meta variable"]) form = QFormLayout(fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow, labelAlignment=Qt.AlignLeft, spacing=8) form.addRow("Name", name_edit) form.addRow("Place", cb) ibox.layout().addSpacing(5) ibox.layout().addLayout(form) ibox.layout().addSpacing(5) cb = gui.checkBox(box, self, "autocommit", "Commit automatically") b = gui.button(box, self, "Commit", callback=self.commit, default=True) gui.setStopper(self, b, cb, "_invalidated", callback=self.commit) self.scene = QGraphicsScene() self.view = QGraphicsView( self.scene, horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOff, verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn, alignment=Qt.AlignLeft | Qt.AlignVCenter) def axis_view(orientation): ax = pg.AxisItem(orientation=orientation, maxTickLength=7) scene = QGraphicsScene() scene.addItem(ax) view = QGraphicsView( scene, horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOff, verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn, alignment=Qt.AlignLeft | Qt.AlignVCenter) view.setFixedHeight(ax.size().height()) ax.line = SliderLine(orientation=Qt.Horizontal, length=ax.size().height()) scene.addItem(ax.line) return view, ax self.top_axis_view, self.top_axis = axis_view("top") self.mainArea.layout().setSpacing(1) self.mainArea.layout().addWidget(self.top_axis_view) self.mainArea.layout().addWidget(self.view) self.bottom_axis_view, self.bottom_axis = axis_view("bottom") self.mainArea.layout().addWidget(self.bottom_axis_view) self._main_graphics = QGraphicsWidget() self._main_layout = QGraphicsLinearLayout(Qt.Horizontal) self._main_layout.setSpacing(1) self._main_graphics.setLayout(self._main_layout) self.scene.addItem(self._main_graphics) self.dendrogram = DendrogramWidget() self.dendrogram.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) self.dendrogram.selectionChanged.connect(self._invalidate_output) self.dendrogram.selectionEdited.connect(self._selection_edited) fm = self.fontMetrics() self.dendrogram.setContentsMargins(5, fm.lineSpacing() / 2, 5, fm.lineSpacing() / 2) self.labels = GraphicsSimpleTextList() self.labels.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) self.labels.setAlignment(Qt.AlignLeft) self.labels.setMaximumWidth(200) self.labels.layout().setSpacing(0) self._main_layout.addItem(self.dendrogram) self._main_layout.addItem(self.labels) self._main_layout.setAlignment(self.dendrogram, Qt.AlignLeft | Qt.AlignVCenter) self._main_layout.setAlignment(self.labels, Qt.AlignLeft | Qt.AlignVCenter) self.view.viewport().installEventFilter(self) self.top_axis_view.viewport().installEventFilter(self) self.bottom_axis_view.viewport().installEventFilter(self) self._main_graphics.installEventFilter(self) self.cut_line = SliderLine(self.dendrogram, orientation=Qt.Horizontal) self.cut_line.valueChanged.connect(self._dendrogram_slider_changed) self.cut_line.hide() self.bottom_axis.line.valueChanged.connect(self._axis_slider_changed) self.top_axis.line.valueChanged.connect(self._axis_slider_changed) self.dendrogram.geometryChanged.connect(self._dendrogram_geom_changed) self._set_cut_line_visible(self.selection_method == 1)
def init(self): # Setting some Plasma-specific settings self.setHasConfigurationInterface( False) # We dont have a configuration interface, yet. self.setAspectRatioMode(Plasma.IgnoreAspectRatio) self.theme = Plasma.Svg(self) self.setBackgroundHints(Plasma.Applet.DefaultBackground) self.layout = QGraphicsLinearLayout(Qt.Vertical, self.applet) self.applet.setLayout(self.layout) self.icon = self.package().path( ) + "plasmafreq.svg" # Finding a path for our apps icon # Adding a nice-looking GroupBox for RadioButtons self.setGovernorBox = Plasma.GroupBox(self.applet) self.setGovernorBox.setText("Mode selection") self.setGovernorBox.setLayout( QGraphicsLinearLayout(Qt.Vertical, self.setGovernorBox)) self.setGovernorBox.setSizePolicy( QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)) self.layout.addItem(self.setGovernorBox) self.governorGroup = QButtonGroup( self.applet ) # Creating a abstract ButtonGroup in order to link RadioButtons together # Creating a QFileSystemWatcher to watch changes in current frequency and governor self.watcher = QFileSystemWatcher(self) QObject.connect(self.watcher, SIGNAL("fileChanged(const QString&)"), self.file_changed) # Setting paths for cpufreq self.cpuCores = glob(path.join("/sys/devices/system/cpu/", "cpu?")) # List all CPU cores self.cpufreqGovPath = [] # This is going to be ugly...but hey, it works (at least if you dont have many physical CPUs. Cores are ok) for x in self.cpuCores: self.cpufreqGovPath.append( x + "/cpufreq/scaling_governor" ) # path.join doesn't work here, dunno why # Initializing some variables and setting variables to them. self.availableFrequencies = self.listFrequencies() self.availableGovernors = self.listGovernors() self.currentGovernorStr = self.currentGovernor() self.currentFrequencyStr = self.currentFrequency() self.radioButton = {} # This contains texts and tooltips for RadioButtons self.governorTextsDict = { 'conservative': [ 'Conservative', 'Similiar to On Demand, but CPU clock speed switches gradually through all its available frequencies based on system load ' ], 'ondemand': [ 'On Demand', 'Dynamically switches between the CPU available clock speeds based on system load ' ], 'userspace': ['User Defined', 'Lets user to manually configure clock speeds'], 'powersave': ['Powersave', 'Runs the CPU at minimum clock speeds'], 'performance': ['Performance', 'Runs the CPU at maximum clock speeds'] } for x in self.availableGovernors: # Makes a RadioButton for each governor available. self.radioButton[x] = Plasma.RadioButton(self.applet) self.radioButton[x].setText( self.governorTextsDict[x][0] ) # Sets the text for radioButton from governorTextsDict above self.radioButton[x].setToolTip(self.governorTextsDict[x][1]) self.radioButton[x].setSizePolicy( QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)) self.governorGroup.addButton(self.radioButton[x].nativeWidget( )) # We need to add radioButton's native widget self.setGovernorBox.layout().addItem(self.radioButton[x]) if x == self.currentGovernorStr: self.radioButton[x].setChecked( True ) # Checks if x is current governor and should we have a tick on RadioButton # Add a button for applying changes self.applyButton = Plasma.PushButton(self.applet) self.applyButton.setText("Apply") self.applyButton.setSizePolicy( QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Maximum)) self.layout.addItem(self.applyButton) QObject.connect(self.applyButton, SIGNAL("clicked()"), self.applyChanges)
class PlasmaFreq(plasmascript.Applet): def __init__(self, parent, args=None): # Init for plasma applet plasmascript.Applet.__init__(self, parent) def listGovernors(self): # Lists governors aka power modes available in current system. self.listGovPath = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors" governorsFile = open(self.listGovPath, 'r') # Open the file availableGovernors = governorsFile.read() governorsList = split( " +", availableGovernors ) # Splitting the string to list, space is the separator governorsList.remove( "\n") # Remove newline item from list, added by split governorsFile.close() return governorsList def listFrequencies(self): # Lists processor core frequencies available for scaling self.listFreqPath = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies" frequenciesFile = open(self.listFreqPath, 'r') availableFrequencies = frequenciesFile.read() frequenciesList = split(" +", availableFrequencies) frequenciesList.remove("\n") frequenciesFile.close() return frequenciesList def currentFrequency(self): # Returns a string containing the current governor self.curFreqPath = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq" frequencyFile = open(self.curFreqPath, 'r') if self.curFreqPath not in self.watcher.files(): self.watcher.addPath(self.curFreqPath) currentFrequency = frequencyFile.read() currentFrequency = currentFrequency.rstrip( ) # Removes newline from string, since we don't need a list for this. frequencyFile.close() return currentFrequency def currentGovernor(self): self.curGovPath = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor" governorFile = open(self.curGovPath, 'r') if self.curGovPath not in self.watcher.files( ): # Not adding file to watcher in case of it excists already self.watcher.addPath(self.curGovPath) currentGovernor = governorFile.read() currentGovernor = currentGovernor.rstrip( ) # Removes newline from string, since we don't need a list for this. governorFile.close() return currentGovernor def file_changed(self, path): if path == self.curGovPath: # When scaling governor has changed, this is true self.currentGovernorStr = self.currentGovernor() self.radioButton[self.currentGovernorStr].setChecked( True) # Check radioButton that represents the new governor if path == self.curFreqPath: self.currentFrequencyStr = self.currentFrequency() def applyChanges(self): # With some Linux distros kdesudo is not default/not even available in official software repositories kdesudoY = True try: call(["kdesudo", "--"]) except OSError: kdesudoY = False #kdesudoY := just a flag to change command in the cycle below while keeping changes to code separated # We basically run a for-loop to try out that which radioButton is checked. Better ways warmly welcome. for x in self.availableGovernors: if self.radioButton[x].isChecked( ) == True: # radioButton for x governor is checked cpufreqFiles = " ".join( self.cpufreqGovPath ) # Converting list to space-separated string if kdesudoY: governor = '"%s"' % x # Adding quotes to governor name # Insert some variables to command. We should use KAuth instead of kdesudo but I have no idea how to use KAuth in python cmd = "kdesudo -i %s --comment '<b>PlasmaFreq</b> need administrative priviledges. Please enter your password.' -c 'echo %s | tee %s'" % ( self.icon, governor, cpufreqFiles) else: # no kdesudo: use kdesu in cmd governor = "%s" % x # Adding single (to work with kdesu + tee) quotes to governor name # Insert some variables to command. We should use KAuth instead of kdesu(do) but I have no idea how to use KAuth in python cmd = "kdesu -i %s -c 'echo %s | tee %s'" % ( self.icon, governor, cpufreqFiles) # Run the command. shell=True would be a security vulnerability (shell injection) if the cmd parameter would have something from user input fnull = open( devnull, 'w') # Open /dev/null for stdout/stderr redirection call(cmd, shell=True, stdout=fnull, stderr=fnull) fnull.close() def init(self): # Setting some Plasma-specific settings self.setHasConfigurationInterface( False) # We dont have a configuration interface, yet. self.setAspectRatioMode(Plasma.IgnoreAspectRatio) self.theme = Plasma.Svg(self) self.setBackgroundHints(Plasma.Applet.DefaultBackground) self.layout = QGraphicsLinearLayout(Qt.Vertical, self.applet) self.applet.setLayout(self.layout) self.icon = self.package().path( ) + "plasmafreq.svg" # Finding a path for our apps icon # Adding a nice-looking GroupBox for RadioButtons self.setGovernorBox = Plasma.GroupBox(self.applet) self.setGovernorBox.setText("Mode selection") self.setGovernorBox.setLayout( QGraphicsLinearLayout(Qt.Vertical, self.setGovernorBox)) self.setGovernorBox.setSizePolicy( QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)) self.layout.addItem(self.setGovernorBox) self.governorGroup = QButtonGroup( self.applet ) # Creating a abstract ButtonGroup in order to link RadioButtons together # Creating a QFileSystemWatcher to watch changes in current frequency and governor self.watcher = QFileSystemWatcher(self) QObject.connect(self.watcher, SIGNAL("fileChanged(const QString&)"), self.file_changed) # Setting paths for cpufreq self.cpuCores = glob(path.join("/sys/devices/system/cpu/", "cpu?")) # List all CPU cores self.cpufreqGovPath = [] # This is going to be ugly...but hey, it works (at least if you dont have many physical CPUs. Cores are ok) for x in self.cpuCores: self.cpufreqGovPath.append( x + "/cpufreq/scaling_governor" ) # path.join doesn't work here, dunno why # Initializing some variables and setting variables to them. self.availableFrequencies = self.listFrequencies() self.availableGovernors = self.listGovernors() self.currentGovernorStr = self.currentGovernor() self.currentFrequencyStr = self.currentFrequency() self.radioButton = {} # This contains texts and tooltips for RadioButtons self.governorTextsDict = { 'conservative': [ 'Conservative', 'Similiar to On Demand, but CPU clock speed switches gradually through all its available frequencies based on system load ' ], 'ondemand': [ 'On Demand', 'Dynamically switches between the CPU available clock speeds based on system load ' ], 'userspace': ['User Defined', 'Lets user to manually configure clock speeds'], 'powersave': ['Powersave', 'Runs the CPU at minimum clock speeds'], 'performance': ['Performance', 'Runs the CPU at maximum clock speeds'] } for x in self.availableGovernors: # Makes a RadioButton for each governor available. self.radioButton[x] = Plasma.RadioButton(self.applet) self.radioButton[x].setText( self.governorTextsDict[x][0] ) # Sets the text for radioButton from governorTextsDict above self.radioButton[x].setToolTip(self.governorTextsDict[x][1]) self.radioButton[x].setSizePolicy( QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)) self.governorGroup.addButton(self.radioButton[x].nativeWidget( )) # We need to add radioButton's native widget self.setGovernorBox.layout().addItem(self.radioButton[x]) if x == self.currentGovernorStr: self.radioButton[x].setChecked( True ) # Checks if x is current governor and should we have a tick on RadioButton # Add a button for applying changes self.applyButton = Plasma.PushButton(self.applet) self.applyButton.setText("Apply") self.applyButton.setSizePolicy( QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Maximum)) self.layout.addItem(self.applyButton) QObject.connect(self.applyButton, SIGNAL("clicked()"), self.applyChanges)
class OWHierarchicalClustering(widget.OWWidget): name = "Hierarchical Clustering" description = ("Hierarchical clustering based on distance matrix, and " "a dendrogram viewer.") icon = "icons/HierarchicalClustering.svg" priority = 2100 inputs = [("Distances", Orange.misc.DistMatrix, "set_distances")] outputs = [("Selected Data", Orange.data.Table), ("Other Data", Orange.data.Table)] #: Selected linkage linkage = settings.Setting(1) #: Index of the selected annotation item (variable, ...) annotation_idx = settings.Setting(0) #: Selected tree pruning (none/max depth) pruning = settings.Setting(0) #: Maximum depth when max depth pruning is selected max_depth = settings.Setting(10) #: Selected cluster selection method (none, cut distance, top n) selection_method = settings.Setting(0) #: Cut height ratio wrt root height cut_ratio = settings.Setting(75.0) #: Number of top clusters to select top_n = settings.Setting(3) append_clusters = settings.Setting(True) cluster_role = settings.Setting(2) cluster_name = settings.Setting("Cluster") autocommit = settings.Setting(False) #: Cluster variable domain role AttributeRole, ClassRole, MetaRole = 0, 1, 2 def __init__(self, parent=None): super().__init__(parent) self.matrix = None self.items = None self.linkmatrix = None self.root = None self._displayed_root = None self.cutoff_height = 0.0 self._invalidated = False gui.comboBox(gui.widgetBox(self.controlArea, "Linkage"), self, "linkage", items=LINKAGE, callback=self._invalidate_clustering) box = gui.widgetBox(self.controlArea, "Annotation") self.label_cb = gui.comboBox(box, self, "annotation_idx", callback=self._update_labels) self.label_cb.setModel(itemmodels.VariableListModel()) self.label_cb.model()[:] = ["None", "Enumeration"] box = gui.radioButtons(self.controlArea, self, "pruning", box="Pruning", callback=self._invalidate_pruning) grid = QGridLayout() box.layout().addLayout(grid) grid.addWidget(gui.appendRadioButton(box, "None", addToLayout=False), 0, 0) self.max_depth_spin = gui.spin(box, self, "max_depth", minv=1, maxv=100, callback=self._invalidate_pruning, keyboardTracking=False) grid.addWidget( gui.appendRadioButton(box, "Max depth", addToLayout=False), 1, 0) grid.addWidget(self.max_depth_spin, 1, 1) box = gui.radioButtons(self.controlArea, self, "selection_method", box="Selection", callback=self._selection_method_changed) grid = QGridLayout() box.layout().addLayout(grid) grid.addWidget(gui.appendRadioButton(box, "Manual", addToLayout=False), 0, 0) grid.addWidget( gui.appendRadioButton(box, "Height ratio", addToLayout=False), 1, 0) self.cut_ratio_spin = gui.spin(box, self, "cut_ratio", 0, 100, step=1e-1, spinType=float, callback=self._selection_method_changed) self.cut_ratio_spin.setSuffix("%") grid.addWidget(self.cut_ratio_spin, 1, 1) grid.addWidget(gui.appendRadioButton(box, "Top N", addToLayout=False), 2, 0) self.top_n_spin = gui.spin(box, self, "top_n", 1, 20, callback=self._selection_method_changed) grid.addWidget(self.top_n_spin, 2, 1) box.layout().addLayout(grid) self.controlArea.layout().addStretch() box = gui.widgetBox(self.controlArea, "Output") gui.checkBox(box, self, "append_clusters", "Append cluster IDs", callback=self._invalidate_output) ibox = gui.indentedBox(box) name_edit = gui.lineEdit(ibox, self, "cluster_name") name_edit.editingFinished.connect(self._invalidate_output) cb = gui.comboBox( ibox, self, "cluster_role", callback=self._invalidate_output, items=["Attribute", "Class variable", "Meta variable"]) form = QFormLayout(fieldGrowthPolicy=QFormLayout.AllNonFixedFieldsGrow, labelAlignment=Qt.AlignLeft, spacing=8) form.addRow("Name", name_edit) form.addRow("Place", cb) ibox.layout().addSpacing(5) ibox.layout().addLayout(form) ibox.layout().addSpacing(5) cb = gui.checkBox(box, self, "autocommit", "Commit automatically") b = gui.button(box, self, "Commit", callback=self.commit, default=True) gui.setStopper(self, b, cb, "_invalidated", callback=self.commit) self.scene = QGraphicsScene() self.view = QGraphicsView( self.scene, horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOff, verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn, alignment=Qt.AlignLeft | Qt.AlignVCenter) def axis_view(orientation): ax = pg.AxisItem(orientation=orientation, maxTickLength=7) scene = QGraphicsScene() scene.addItem(ax) view = QGraphicsView( scene, horizontalScrollBarPolicy=Qt.ScrollBarAlwaysOff, verticalScrollBarPolicy=Qt.ScrollBarAlwaysOn, alignment=Qt.AlignLeft | Qt.AlignVCenter) view.setFixedHeight(ax.size().height()) ax.line = SliderLine(orientation=Qt.Horizontal, length=ax.size().height()) scene.addItem(ax.line) return view, ax self.top_axis_view, self.top_axis = axis_view("top") self.mainArea.layout().setSpacing(1) self.mainArea.layout().addWidget(self.top_axis_view) self.mainArea.layout().addWidget(self.view) self.bottom_axis_view, self.bottom_axis = axis_view("bottom") self.mainArea.layout().addWidget(self.bottom_axis_view) self._main_graphics = QGraphicsWidget() self._main_layout = QGraphicsLinearLayout(Qt.Horizontal) self._main_layout.setSpacing(1) self._main_graphics.setLayout(self._main_layout) self.scene.addItem(self._main_graphics) self.dendrogram = DendrogramWidget() self.dendrogram.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) self.dendrogram.selectionChanged.connect(self._invalidate_output) self.dendrogram.selectionEdited.connect(self._selection_edited) fm = self.fontMetrics() self.dendrogram.setContentsMargins(5, fm.lineSpacing() / 2, 5, fm.lineSpacing() / 2) self.labels = GraphicsSimpleTextList() self.labels.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) self.labels.setAlignment(Qt.AlignLeft) self.labels.setMaximumWidth(200) self.labels.layout().setSpacing(0) self._main_layout.addItem(self.dendrogram) self._main_layout.addItem(self.labels) self._main_layout.setAlignment(self.dendrogram, Qt.AlignLeft | Qt.AlignVCenter) self._main_layout.setAlignment(self.labels, Qt.AlignLeft | Qt.AlignVCenter) self.view.viewport().installEventFilter(self) self.top_axis_view.viewport().installEventFilter(self) self.bottom_axis_view.viewport().installEventFilter(self) self._main_graphics.installEventFilter(self) self.cut_line = SliderLine(self.dendrogram, orientation=Qt.Horizontal) self.cut_line.valueChanged.connect(self._dendrogram_slider_changed) self.cut_line.hide() self.bottom_axis.line.valueChanged.connect(self._axis_slider_changed) self.top_axis.line.valueChanged.connect(self._axis_slider_changed) self.dendrogram.geometryChanged.connect(self._dendrogram_geom_changed) self._set_cut_line_visible(self.selection_method == 1) def set_distances(self, matrix): self.matrix = matrix self._invalidate_clustering() self._set_items(matrix.row_items if matrix is not None else None) def _set_items(self, items): self.items = items if items is None: self.label_cb.model()[:] = ["None", "Enumeration"] elif isinstance(items, Orange.data.Table): vars = list(items.domain) self.label_cb.model()[:] = ["None", "Enumeration"] + vars elif isinstance(items, list) and \ all(isinstance(var, Orange.data.Variable) for var in items): self.label_cb.model()[:] = ["None", "Enumeration", "Name"] else: self.label_cb.model()[:] = ["None", "Enumeration"] self.annotation_idx = min(self.annotation_idx, len(self.label_cb.model()) - 1) def handleNewSignals(self): self._update_labels() def _clear_plot(self): self.labels.set_labels([]) self.dendrogram.set_root(None) def _set_displayed_root(self, root): self._clear_plot() self._displayed_root = root self.dendrogram.set_root(root) self._update_labels() self._main_graphics.resize( self._main_graphics.size().width(), self._main_graphics.sizeHint(Qt.PreferredSize).height()) self._main_graphics.layout().activate() def _update(self): self._clear_plot() distances = self.matrix if distances is not None: # Convert to flat upper triangular distances i, j = numpy.triu_indices(distances.X.shape[0], k=1) distances = distances.X[i, j] method = LINKAGE[self.linkage].lower() Z = scipy.cluster.hierarchy.linkage(distances, method=method) tree = tree_from_linkage(Z) self.linkmatrix = Z self.root = tree self.top_axis.setRange(tree.value.height, 0.0) self.bottom_axis.setRange(tree.value.height, 0.0) if self.pruning: self._set_displayed_root(prune(tree, level=self.max_depth)) else: self._set_displayed_root(tree) else: self.linkmatrix = None self.root = None self._set_displayed_root(None) self._apply_selection() def _update_labels(self): labels = [] if self.root and self._displayed_root: indices = [leaf.value.index for leaf in leaves(self.root)] if self.annotation_idx == 0: labels = [] elif self.annotation_idx == 1: labels = [str(i) for i in indices] elif isinstance(self.items, Orange.data.Table): var = self.label_cb.model()[self.annotation_idx] col = self.items[:, var] labels = [var.repr_val(next(iter(row))) for row in col] labels = [labels[idx] for idx in indices] else: labels = [] if labels and self._displayed_root is not self.root: joined = leaves(self._displayed_root) labels = [ ", ".join(labels[leaf.value.first:leaf.value.last]) for leaf in joined ] self.labels.set_labels(labels) self.labels.setMinimumWidth(1 if labels else -1) def _invalidate_clustering(self): self._update() self._update_labels() def _invalidate_output(self): self._invalidated = True if self.autocommit: self.commit() def _invalidate_pruning(self): if self.root: selection = self.dendrogram.selected_nodes() ranges = [node.value.range for node in selection] if self.pruning: self._set_displayed_root(prune(self.root, level=self.max_depth)) else: self._set_displayed_root(self.root) selected = [ node for node in preorder(self._displayed_root) if node.value.range in ranges ] self.dendrogram.set_selected_clusters(selected) self._apply_selection() def commit(self): self._invalidated = False items = getattr(self.matrix, "items", self.items) if not items: # nothing to commit return selection = self.dendrogram.selected_nodes() selection = sorted(selection, key=lambda c: c.value.first) indices = [leaf.value.index for leaf in leaves(self.root)] maps = [ indices[node.value.first:node.value.last] for node in selection ] selected_indices = list(chain(*maps)) unselected_indices = sorted( set(range(self.root.value.last)) - set(selected_indices)) selected = [items[k] for k in selected_indices] unselected = [items[k] for k in unselected_indices] if not selected: self.send("Selected Data", None) self.send("Other Data", None) return selected_data = unselected_data = None if isinstance(items, Orange.data.Table): c = numpy.zeros(len(items)) for i, indices in enumerate(maps): c[indices] = i c[unselected_indices] = len(maps) mask = c != len(maps) if self.append_clusters: clust_var = Orange.data.DiscreteVariable( str(self.cluster_name), values=[ "Cluster {}".format(i + 1) for i in range(len(maps)) ] + ["Other"]) data, domain = items, items.domain attrs = domain.attributes class_ = domain.class_vars metas = domain.metas X, Y, M = data.X, data.Y, data.metas if self.cluster_role == self.AttributeRole: attrs = attrs + (clust_var, ) X = numpy.c_[X, c] elif self.cluster_role == self.ClassRole: class_ = class_ + (clust_var, ) Y = numpy.c_[Y, c] elif self.cluster_role == self.MetaRole: metas = metas + (clust_var, ) M = numpy.c_[M, c] domain = Orange.data.Domain(attrs, class_, metas) data = Orange.data.Table(domain, X, Y, M) else: data = items if selected: selected_data = data[mask] if unselected: unselected_data = data[~mask] self.send("Selected Data", selected_data) self.send("Other Data", unselected_data) def sizeHint(self): return QSize(800, 500) def eventFilter(self, obj, event): if obj is self.view.viewport() and event.type() == QEvent.Resize: width = self.view.viewport().width() - 2 self._main_graphics.setMaximumWidth(width) self._main_graphics.setMinimumWidth(width) self._main_graphics.layout().activate() elif event.type() == QEvent.MouseButtonPress and \ (obj is self.top_axis_view.viewport() or obj is self.bottom_axis_view.viewport()): self.selection_method = 1 # Map click point to cut line local coordinates pos = self.top_axis_view.mapToScene(event.pos()) cut = self.top_axis.line.mapFromScene(pos) self.top_axis.line.setValue(cut.x()) # update the line visibility, output, ... self._selection_method_changed() return super().eventFilter(obj, event) def _dendrogram_geom_changed(self): pos = self.dendrogram.pos_at_height(self.cutoff_height) geom = self.dendrogram.geometry() crect = self.dendrogram.contentsRect() self._set_slider_value(pos.x(), geom.width()) self.cut_line.setLength(geom.height()) self.top_axis.resize(crect.width(), self.top_axis.height()) self.top_axis.setPos(geom.left() + crect.left(), 0) self.top_axis.line.setPos(self.cut_line.scenePos().x(), 0) self.bottom_axis.resize(crect.width(), self.bottom_axis.height()) self.bottom_axis.setPos(geom.left() + crect.left(), 0) self.bottom_axis.line.setPos(self.cut_line.scenePos().x(), 0) geom = self._main_graphics.geometry() assert geom.topLeft() == QPointF(0, 0) self.scene.setSceneRect(geom) geom.setHeight(self.top_axis.size().height()) self.top_axis.scene().setSceneRect(geom) self.bottom_axis.scene().setSceneRect(geom) def _axis_slider_changed(self, value): self.cut_line.setValue(value) def _dendrogram_slider_changed(self, value): p = QPointF(value, 0) cl_height = self.dendrogram.height_at(p) self.set_cutoff_height(cl_height) # Sync the cut positions between the dendrogram and the axis. self._set_slider_value(value, self.dendrogram.size().width()) def _set_slider_value(self, value, span): with blocked(self.cut_line): self.cut_line.setValue(value) self.cut_line.setRange(0, span) with blocked(self.top_axis.line): self.top_axis.line.setValue(value) self.top_axis.line.setRange(0, span) with blocked(self.bottom_axis.line): self.bottom_axis.line.setValue(value) self.bottom_axis.line.setRange(0, span) def set_cutoff_height(self, height): self.cutoff_height = height if self.root: self.cut_ratio = 100 * height / self.root.value.height self.select_max_height(height) def _set_cut_line_visible(self, visible): self.cut_line.setVisible(visible) self.top_axis.line.setVisible(visible) self.bottom_axis.line.setVisible(visible) def select_top_n(self, n): root = self._displayed_root if root: clusters = top_clusters(root, n) self.dendrogram.set_selected_clusters(clusters) def select_max_height(self, height): root = self._displayed_root if root: clusters = clusters_at_height(root, height) self.dendrogram.set_selected_clusters(clusters) def _selection_method_changed(self): self._set_cut_line_visible(self.selection_method == 1) if self.root: self._apply_selection() def _apply_selection(self): if not self.root: return if self.selection_method == 0: pass elif self.selection_method == 1: height = self.cut_ratio * self.root.value.height / 100 self.set_cutoff_height(height) pos = self.dendrogram.pos_at_height(height) self._set_slider_value(pos.x(), self.dendrogram.size().width()) elif self.selection_method == 2: self.select_top_n(self.top_n) def _selection_edited(self): # Selection was edited by clicking on a cluster in the # dendrogram view. self.selection_method = 0 self._selection_method_changed()
def __init__(self, pixmap, title="", parentItem=None, **kwargs): super().__init__(parentItem, **kwargs) self.setFocusPolicy(Qt.StrongFocus) self._title = None self._size = QSizeF() layout = QGraphicsLinearLayout(Qt.Vertical, self) layout.setSpacing(2) layout.setContentsMargins(5, 5, 5, 5) self.setContentsMargins(0, 0, 0, 0) self.pixmapWidget = GraphicsPixmapWidget(pixmap, self) self.labelWidget = GraphicsTextWidget(title, self) layout.addItem(self.pixmapWidget) layout.addItem(self.labelWidget) layout.addStretch() layout.setAlignment(self.pixmapWidget, Qt.AlignCenter) layout.setAlignment(self.labelWidget, Qt.AlignHCenter | Qt.AlignBottom) self.setLayout(layout) self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) self.setFlag(QGraphicsItem.ItemIsSelectable, True) self.setTitle(title) self.setTitleWidth(100)
def __init__(self, pixmap, title="", parent=None): QGraphicsWidget.__init__(self, parent) self._title = None self._size = QSizeF() layout = QGraphicsLinearLayout(Qt.Vertical, self) layout.setSpacing(2) layout.setContentsMargins(5, 5, 5, 5) self.setContentsMargins(0, 0, 0, 0) self.pixmapWidget = GraphicsPixmapWidget(pixmap, self) self.labelWidget = GraphicsTextWidget(title, self) layout.addItem(self.pixmapWidget) layout.addItem(self.labelWidget) layout.setAlignment(self.pixmapWidget, Qt.AlignCenter) layout.setAlignment(self.labelWidget, Qt.AlignHCenter | Qt.AlignBottom) self.setLayout(layout) self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) self.setFlag(QGraphicsItem.ItemIsSelectable, True) self.setTitle(title) self.setTitleWidth(100)