def setData(self, index, value, role=Qt.EditRole): if role == Qt.EditRole and index.column() == ColumnID.Color: row = index.row() brushColor = QColor(value[0]) pmapColor = QColor(value[1]) if brushColor.isValid() and pmapColor.isValid(): print "setData: brushColor = {}, pmapColor = {}".format( brushColor.name(), pmapColor.name()) print " self._labels[row] has type {}".format( type(self._labels[row])) self._labels[row].setBrushColor(brushColor) self._labels[row].setPmapColor(pmapColor) print " self._labels[row].brushColor = {}".format( self._labels[row].brushColor().name()) print " self._labels[row].pmapColor = {}".format( self._labels[row].pmapColor().name()) self.dataChanged.emit(index, index) return True if role == Qt.EditRole and index.column() == ColumnID.Name: row = index.row() name = value self._labels[row].name = str(name.toString()) self.dataChanged.emit(index, index) return True return False
class QColorButton(QPushButton): colorChanged = pyqtSignal() def __init__(self, *args, **kwargs): super(QColorButton, self).__init__(*args, **kwargs) self._color = QColor(255, 0, 0) self.setStyleSheet("background-color: %s;" % self._color.name()) self.setMaximumWidth(32) self.pressed.connect(self.onColorPicker) def set_color(self, color): if color != self._color: self._color = color self.colorChanged.emit() self.setStyleSheet("background-color: %s;" % self._color.name()) def color(self): return self._color def onColorPicker(self): dialog = QColorDialog() dialog.setCurrentColor(self._color) if dialog.exec_(): self.set_color(dialog.currentColor()) def mousePressEvent(self, e): return super(QColorButton, self).mousePressEvent(e)
def setElectricalPreferences(self): self.view.electricalSimulationDt.setText( str(float(self.preferences["electrical"]["simulation"]["simulation-dt"])) ) self.view.electricalPlotUpdateInterval.setText( str(float(self.preferences["electrical"]["simulation"]["plot-update-interval"])) ) self.view.electricalDefaultSimulationRuntime.setText( str(float(self.preferences["electrical"]["simulation"]["default-runtime"])) ) self.view.electricalGuiUpdateInterval.setText( str(float(self.preferences["electrical"]["simulation"]["gui-update-interval"])) ) self.view.electricalSolvers[str(self.preferences["electrical"]["simulation"]["solver"])].setChecked(True) self.view.electricalPeakMembraneVoltage.setText( str(float(self.preferences["electrical"]["visualization"]["peak-membrane-voltage"])) ) self.view.electricalBaseMembraneVoltage.setText( str(float(self.preferences["electrical"]["visualization"]["base-membrane-voltage"])) ) (r, g, b, a) = self.preferences["electrical"]["visualization"]["base-color"] # print((r,g,b,a)) color = QColor(r, g, b, a) # print(color.name()) self.view.electricalBaseColorDialog.setCurrentColor(color) self.view.electricalBaseColorButton.setStyleSheet( "QPushButton {" + "background-color: {0}; color: {0};".format(color.name()) + "}" ) (r, g, b, a) = self.preferences["electrical"]["visualization"]["peak-color"] # print((r,g,b,a)) color = QColor(r, g, b, a) # print(color.name()) self.view.electricalPeakColorDialog.setCurrentColor(QColor(r, g, b, a)) self.view.electricalPeakColorButton.setStyleSheet( "QPushButton {" + "background-color: {0}; color: {0};".format(color.name()) + "}" ) (r, g, b, a) = self.preferences["electrical"]["visualization"]["background-color"] # print((r,g,b,a)) color = QColor(r, g, b, a) # print(color.name()) self.view.electricalBackgroundColorDialog.setCurrentColor(QColor(r, g, b, a)) self.view.electricalBackgroundColorButton.setStyleSheet( "QPushButton {" + "background-color: {0}; color: {0};".format(color.name()) + "}" )
def pixel_color_in_area(self, rectangle, color): """ Searches the rectangle area 'rectangle' for the color 'color'. If the 'color' is found inside 'rectangle' then it returns True as first argument and the point where the pixel was found as the 2nd argument If nothing is found then it simply returns False. The rectangle is a tuple [x, y, width, height], where x, y the coordinates of the top left corner and width, height the width and the height of the rectangle. The color is a string with a hexadecimal representation of a color (e.g. #000000) """ x = rectangle[0] y = rectangle[1] width = rectangle[2] height = rectangle[3] color = to_lower(color) img = QPixmap.grabWindow(QApplication.desktop().winId()).toImage().copy(x, y, width + 1, height + 1) cur_y = cur_x = 0 while cur_y <= height: cur_x = 0 while cur_x <= width: cur_color = QColor(img.pixel(QPoint(cur_x, cur_y))) if str(color) == str(cur_color.name()): return True, [cur_x + x, cur_y + y] cur_x += self.pixel_search_speed cur_y += 1 return False, [-1, -1]
def pixel_color_in_area_counter(self, rectangle, color): """ Searches the rectangle area 'rectangle' for the color 'color'. It returns an integer indicating the times that the 'color' was found inside the 'rectangle'. The rectangle is a tuple [x, y, width, height], where x, y the coordinates of the top left corner and width, height the width and the height of the rectangle. The color is a string with a hexadecimal representation of a color (e.g. #000000) """ x = rectangle[0] y = rectangle[1] width = rectangle[2] height = rectangle[3] color = to_lower(color) img = QPixmap.grabWindow(QApplication.desktop().winId()).toImage().copy(x, y, width + 1, height + 1) counter = cur_y = cur_x = 0 while cur_y <= height: cur_x = 0 while cur_x <= width: cur_color = QColor(img.pixel(QPoint(cur_x, cur_y))) if str(color) == str(cur_color.name()): counter += 1 cur_x += self.pixel_search_speed cur_y += 1 return counter
class ColorComboBox(QComboBox): def __init__(self, parent=None): QComboBox.__init__(self, parent) self.custom = QColor(Qt.black) self.populateList() self.connect(self, SIGNAL('activated(int)'), self.onActivated) def color(self): return self.itemData(self.currentIndex(), Qt.DecorationRole).toPyObject() def setColor(self, color): index = self.findData(color, Qt.DecorationRole) if index >= 0: self.setCurrentIndex(index) else: self.setCurrentIndex(self.count() - 1) self.custom = color self.updateCustomColor() def populateList(self): colorNames = QColor.colorNames() for i, name in enumerate(colorNames): self.insertItem(i, str(name).capitalize()) self.setItemData(i, QColor(name), Qt.DecorationRole) self.insertItem(len(colorNames), "") self.updateCustomColor() def updateCustomColor(self): self.setItemText(self.count() - 1, "Custom (%s)" % self.custom.name()) self.setItemData(self.count() - 1, self.custom, Qt.DecorationRole) def onActivated(self, index): if index == self.count() - 1: color = QColorDialog.getColor(self.custom, self) if color.isValid(): self.custom = color self.updateCustomColor() def paintEvent(self, _): painter = QStylePainter(self) painter.setPen(self.palette().color(QPalette.Text)) opt = QStyleOptionComboBox() self.initStyleOption(opt) painter.drawComplexControl(QStyle.CC_ComboBox, opt) frame = self.style().subControlRect(QStyle.CC_ComboBox, opt, QStyle.SC_ComboBoxEditField, self) painter.setRenderHint(QPainter.Antialiasing) painter.setPen(Qt.transparent) painter.setBrush(self.color()) painter.drawRoundedRect(frame.adjusted(1, 1, -1, -2), 2, 2)
class ColorComboBox( QComboBox ): def __init__( self, parent = None ): QComboBox.__init__( self, parent ) self.custom = QColor( Qt.black ) self.populateList() self.connect( self, SIGNAL( 'activated(int)' ), self.onActivated ) def color( self ): return self.itemData( self.currentIndex(), Qt.DecorationRole ).toPyObject() def setColor( self, color ): index = self.findData( color, Qt.DecorationRole ) if index >= 0: self.setCurrentIndex( index ) else: self.setCurrentIndex( self.count() - 1 ) self.custom = color self.updateCustomColor() def populateList( self ): colorNames = QColor.colorNames() for i, name in enumerate( colorNames ): self.insertItem( i, str( name ).capitalize() ) self.setItemData( i, QColor( name ), Qt.DecorationRole ) self.insertItem( len( colorNames ), "" ) self.updateCustomColor() def updateCustomColor( self ): self.setItemText( self.count() - 1, "Custom (%s)" % self.custom.name() ) self.setItemData( self.count() - 1, self.custom, Qt.DecorationRole ) def onActivated( self, index ): if index == self.count() - 1: color = QColorDialog.getColor( self.custom, self ) if color.isValid(): self.custom = color self.updateCustomColor() def paintEvent( self, _ ): painter = QStylePainter( self ) painter.setPen( self.palette().color( QPalette.Text ) ) opt = QStyleOptionComboBox() self.initStyleOption( opt ) painter.drawComplexControl( QStyle.CC_ComboBox, opt ) frame = self.style().subControlRect( QStyle.CC_ComboBox, opt, QStyle.SC_ComboBoxEditField, self ) painter.setRenderHint( QPainter.Antialiasing ) painter.setPen( Qt.transparent ) painter.setBrush( self.color() ) painter.drawRoundedRect( frame.adjusted( 1, 1, -1, -2 ), 2, 2 )
def setData(self, index, value, role=Qt.EditRole): if role == Qt.EditRole and index.column() == self.ColumnID.Color: row = index.row() brushColor = QColor(value[0]) pmapColor = QColor(value[1]) if brushColor.isValid() and pmapColor.isValid(): print "setData: brushColor = {}, pmapColor = {}".format( brushColor.name(), pmapColor.name()) print " self._elements[row] has type {}".format( type(self._elements[row])) self._elements[row].setBrushColor(brushColor) self._elements[row].setPmapColor(pmapColor) print " self._elements[row].brushColor = {}".format( self._elements[row].brushColor().name()) print " self._elements[row].pmapColor = {}".format( self._elements[row].pmapColor().name()) self.dataChanged.emit(index, index) return True else: return ListModel.setData(self, index, value, role)
def setData(self, index, value, role=Qt.EditRole): if role == Qt.EditRole and index.column() == self.ColumnID.Color: row = index.row() brushColor = QColor(value[0]) pmapColor = QColor(value[1]) if brushColor.isValid() and pmapColor.isValid(): logger.debug("setData: brushColor = {}, pmapColor = {}" "".format(brushColor.name(), pmapColor.name())) logger.debug(" self._elements[row] has type {}" "".format(type(self._elements[row]))) self._elements[row].setBrushColor(brushColor) self._elements[row].setPmapColor(pmapColor) logger.debug(" self._elements[row].brushColor = {}" "".format(self._elements[row].brushColor().name())) logger.debug(" self._elements[row].pmapColor = {}" "".format(self._elements[row].pmapColor().name())) self.dataChanged.emit(index, index) return True else: return ListModel.setData(self, index, value, role)
def createARange(self, color_value=u"yellow", lower_value=u"", upper_value=u""): delete_btn = QPushButton(self) delete_icon = QIcon( os.path.join(cmd_folder, u"..", u'images', u'delete.png')) delete_btn.setIcon(delete_icon) delete_btn.setIconSize(QSize(25, 25)) delete_btn.setFixedSize(30, 30) delete_btn.setFocusPolicy(Qt.NoFocus) self.connect(delete_btn, SIGNAL("clicked()"), self.delete_range_box) color = QColor(color_value) color_btn = QPushButton(self) color_btn.setStyleSheet('QWidget {background-color:%s}' % color.name()) color_btn.clicked.connect(self.colordialog) lower_edit = QLineEdit(lower_value) # 下限 upper_edit = QLineEdit(upper_value) # 上限 validator = QDoubleValidator(-9999999.9999, 9999999.9999, 4, self) # 取值范围为-9999999.9999~9999999.9999 lower_edit.setValidator(validator) upper_edit.setValidator(validator) label1 = QLabel(u" : ") label2 = QLabel(u'—') range_widget = QWidget() range_box = QHBoxLayout() range_box.setSpacing(10) range_box.addWidget(delete_btn) range_box.addWidget(color_btn) range_box.addWidget(label1) range_box.addWidget(lower_edit) range_box.addWidget(label2) range_box.addWidget(upper_edit) range_box.setStretchFactor(color_btn, 1.5) range_box.setStretchFactor(lower_edit, 1) range_box.setStretchFactor(upper_edit, 1) range_widget.setLayout(range_box) self.color_btn_list.append(color_btn) self.delete_btn_list.append(delete_btn) self.range_widget_list.append(range_widget) self.setting_list.append([color, lower_edit, upper_edit]) return range_widget
def setTheme(self, color): c = QColor() c.setNamedColor(color) c.setRed(self.qMin(c.red() + 40, 255)) c.setGreen(self.qMin(c.green() + 40, 255)) c.setBlue(self.qMin(c.blue() + 40, 255)) self.myTheme[0] = color self.myTheme[1] = c.name() try: f = open(COLOR_PATH, "w") for item in self.myTheme: f.write("%s\n" % item) f.close() except IOError: self.createConfig()
def insertColor(): """Insert/edit color string using color chooser dialog If cursor positioned in a color string, this action will edit it, otherwise a new color string will be inserted into a document. """ document = kate.activeDocument() view = kate.activeView() cursor = view.cursorPosition() if view.selection(): # Some text selected, just use it as input... color_range = view.selectionRange() else: # If no selection, try to get a #color under cursor color_range = common.getBoundTextRangeSL( common.IDENTIFIER_BOUNDARIES - {'#'}, common.IDENTIFIER_BOUNDARIES, cursor, document) if color_range.isValid(): current_color = document.text(color_range) else: current_color = kate.configuration[_INSERT_COLOR_LCC] color = QColor(current_color) # If no text selected (i.e. user doesn’t want to override selection) # and (guessed) color string is not valid, entered color will # be inserted at the current cursor position. if not color.isValid(): color = QColor(kate.configuration[_INSERT_COLOR_LCC]) if not view.selection(): color_range = KTextEditor.Range( cursor, 0) # Will not override the text under cursor… # Choose a color via dialog result = KColorDialog.getColor(color) if result == KColorDialog.Accepted: # Did user press OK? color_str = color.name() # Get it as color string # Remember for future use kate.configuration[_INSERT_COLOR_LCC] = color_str document.startEditing() document.replaceText( color_range, color_str) # Replace selected/found range w/ a new text document.endEditing() # Select just entered #color, if something was selected before if view.selection(): start_pos = color_range.start() view.setSelection(KTextEditor.Range(start_pos, len(color_str)))
def pixel_color_in_area(self, rectangle, color): """ > Description Searches for a pixel with a specific color in an area of the screen. Note that this function is 100% accurate and will return the 1st occurrence only with a pixel search speed of 1. See more at @ref:set_pixel_search_speed > Parameters rectangle (list): the area of the screen to search in the format [x, y, width, height] color (string): the HTML representation of the color to search for > Returns found (bool): true if the function found a pixel with the specified color point (list): a list with the x, y coordinates of the found pixel. If `found` is false, then `point` will be `[-1, -1]` > Example # search for a blue pixel in an area of the screen. By default the pixel search speed is 1 so we don't need to manually set it found, point = Macro().pixel_color_in_area([0, 0, 1000, 500], '#0000ff') # if there was a pixel, click on it if found: Macro.left_click_to(point[0], point[1]) """ x = rectangle[0] y = rectangle[1] width = rectangle[2] height = rectangle[3] color = to_lower(color) img = Macro.__grabDesktop().copy(x, y, width + 1, height + 1); cur_y = cur_x = 0 while( cur_y <= height ): cur_x = 0 while ( cur_x <= width ): cur_color = QColor(img.pixel(QPoint(cur_x, cur_y))) if(str(color) == str(cur_color.name())): return True, [cur_x+x, cur_y+y] cur_x += self.pixel_search_speed cur_y += 1 return False, [-1, -1]
def pixel_color_in_area(self, rectangle, color): """ > Description Searches for a pixel with a specific color in an area of the screen. Note that this function is 100% accurate and will return the 1st occurrence only with a pixel search speed of 1. See more at @ref:set_pixel_search_speed > Parameters rectangle (list): the area of the screen to search in the format [x, y, width, height] color (string): the HTML representation of the color to search for > Returns found (bool): true if the function found a pixel with the specified color point (list): a list with the x, y coordinates of the found pixel. If `found` is false, then `point` will be `[-1, -1]` > Example # search for a blue pixel in an area of the screen. By default the pixel search speed is 1 so we don't need to manually set it found, point = Macro().pixel_color_in_area([0, 0, 1000, 500], '#0000ff') # if there was a pixel, click on it if found: Macro.left_click_to(point[0], point[1]) """ x = rectangle[0] y = rectangle[1] width = rectangle[2] height = rectangle[3] color = to_lower(color) img = Macro.__grabDesktop().copy(x, y, width + 1, height + 1) cur_y = cur_x = 0 while (cur_y <= height): cur_x = 0 while (cur_x <= width): cur_color = QColor(img.pixel(QPoint(cur_x, cur_y))) if (str(color) == str(cur_color.name())): return True, [cur_x + x, cur_y + y] cur_x += self.pixel_search_speed cur_y += 1 return False, [-1, -1]
def init_colorframes(self): col = QColor(0, 0, 0) for frm in self.color_frames: frm.setStyleSheet("QWidget { background-color: %s }" % col.name()) self.DATA['colors'][unicode(frm.objectName())] = unicode(col.name()) col = QColor(85, 170, 255) for frm in [self.frame_fillOceanColor, self.frame_fillRiverColor]: frm.setStyleSheet("QWidget { background-color: %s }" % col.name()) self.DATA['colors'][unicode(frm.objectName())] = unicode(col.name()) col = QColor(170, 85, 0) for frm in [self.frame_fillContinentColor]: frm.setStyleSheet("QWidget { background-color: %s }" % col.name()) self.DATA['colors'][unicode(frm.objectName())] = unicode(col.name())
def pixel_count_in_area(self, rectangle, color): """ > Description Count the number of occurrences of a specific color on an area of the screen. You can modify which pixels to search for with the pixel search speed. Note that the number of occurences will be 100% accurate only with a pixel search speed of 1. See more at @ref:set_pixel_search_speed > Parameters rectangle (list): the area of the screen to search in the format [x, y, width, height] color (string): the HTML representation of the color to search for > Returns counter (int): the number of occurrences of the color in the searched pixels > Example m = Macro() # search every pixel m.set_pixel_search_speed(1) print 'There are', m.pixel_count_in_area([0, 0, 100, 100], '#000000'), 'black pixels in some part of the screen' """ x = rectangle[0] y = rectangle[1] width = rectangle[2] height = rectangle[3] color = to_lower(color) img = Macro.__grabDesktop().copy(x, y, width + 1, height + 1); counter = cur_y = cur_x = 0 for cur_y in range(0, height + 1): for cur_x in range(0, width + 1, self.pixel_search_speed): cur_color = QColor(img.pixel(QPoint(cur_x, cur_y))) if(str(color) == str(cur_color.name())): counter += 1 return counter;
def pixel_count_in_area(self, rectangle, color): """ > Description Count the number of occurrences of a specific color on an area of the screen. You can modify which pixels to search for with the pixel search speed. Note that the number of occurences will be 100% accurate only with a pixel search speed of 1. See more at @ref:set_pixel_search_speed > Parameters rectangle (list): the area of the screen to search in the format [x, y, width, height] color (string): the HTML representation of the color to search for > Returns counter (int): the number of occurrences of the color in the searched pixels > Example m = Macro() # search every pixel m.set_pixel_search_speed(1) print 'There are', m.pixel_count_in_area([0, 0, 100, 100], '#000000'), 'black pixels in some part of the screen' """ x = rectangle[0] y = rectangle[1] width = rectangle[2] height = rectangle[3] color = to_lower(color) img = Macro.__grabDesktop().copy(x, y, width + 1, height + 1) counter = cur_y = cur_x = 0 for cur_y in range(0, height + 1): for cur_x in range(0, width + 1, self.pixel_search_speed): cur_color = QColor(img.pixel(QPoint(cur_x, cur_y))) if (str(color) == str(cur_color.name())): counter += 1 return counter
def paint(self, painter, option, index): # This method will be called every time a particular cell is # in view and that view is changed in some way. We ask the # delegates parent (in this case a table view) if the index # in question (the table cell) already has a widget associated # with it. If not, create one with the text for this index and # connect its clicked signal to a slot in the parent view so # we are notified when its used and can do something. if not self.parent().indexWidget(index): rowData = Settings.getLogLevelsModel().getRowData(index) col = QColor(rowData[2]) self.frm = ColorPickerFrame() # Set index of current table row self.frm.setIndex(index) self.frm.setStyleSheet("QWidget { background-color: %s }" % col.name()) self.frm.setGeometry(130, 22, 100, 100) self.frm.setLineWidth(0) self.frm.setMidLineWidth(2) self.frm.setFrameStyle(QFrame.Box) self.frm.setFrameShadow(QFrame.Sunken) self.connect(self.frm, QtCore.SIGNAL('colorPickerClicked'), self.colorPickerClicked) self.parent().setIndexWidget(index, self.frm)
def createAValue(self, color_value=u"yellow", value=u""): delete_btn = QPushButton(self) delete_icon = QIcon(os.path.join(cmd_folder, u"..", u'images', u'delete.png')) delete_btn.setIcon(delete_icon) delete_btn.setIconSize(QSize(25, 25)) delete_btn.setFixedSize(30, 30) delete_btn.setFocusPolicy(Qt.NoFocus) self.connect(delete_btn, SIGNAL("clicked()"), self.delete_value_box) color = QColor(color_value) color_btn = QPushButton(self) color_btn.setStyleSheet('QWidget {background-color:%s}' % color.name()) color_btn.clicked.connect(self.colordialog) value_edit = QLineEdit(value) # 搜索值 label1 = QLabel(u" : ") value_widget = QWidget() value_box = QHBoxLayout() value_box.setSpacing(10) value_box.addWidget(delete_btn) value_box.addWidget(color_btn) value_box.addWidget(label1) value_box.addWidget(value_edit) value_box.setStretchFactor(color_btn, 1.5) value_box.setStretchFactor(value_edit, 1) value_widget.setLayout(value_box) self.color_btn_list.append(color_btn) self.delete_btn_list.append(delete_btn) self.value_widget_list.append(value_widget) self.setting_list.append([color, value_edit]) return value_widget
def init_colorframes(self): col = QColor(0, 0, 0) for frm in self.color_frames: frm.setStyleSheet("QWidget { background-color: %s }" % col.name()) self.DATA['colors'][unicode(frm.objectName())] = unicode( col.name()) col = QColor(85, 170, 255) for frm in [self.frame_fillOceanColor, self.frame_fillRiverColor]: frm.setStyleSheet("QWidget { background-color: %s }" % col.name()) self.DATA['colors'][unicode(frm.objectName())] = unicode( col.name()) col = QColor(170, 85, 0) for frm in [self.frame_fillContinentColor]: frm.setStyleSheet("QWidget { background-color: %s }" % col.name()) self.DATA['colors'][unicode(frm.objectName())] = unicode( col.name())
class PylouApplet(Applet): """Main Applet containing the UI of Pylou.""" def __init__(self, parent, args=None): """Init class.""" Applet.__init__(self, parent) def init(self): """Start the Applet.""" self._widget = None self.setHasConfigurationInterface(True) self.setAspectRatioMode(Plasma.IgnoreAspectRatio) self.configurations = self.config() self._widget = PylouWidget(self) self._widget.init() self.setGraphicsWidget(self._widget) self.applet.setPassivePopup(True) self.setPopupIcon(QIcon.fromTheme("edit-find")) # for some odd reason this has to be called twice? self.setGraphicsWidget(self._widget) self.prepareConfigDialog() def update_db(self): """Update the DB.""" return call("kdesudo --noignorebutton -c updatedb", shell=True) def prepareConfigDialog(self): """Prepare the Configuration Dialog.""" self.bcolor, self.dialog = QColor(), KDialog() self.dialog.setWindowTitle(__package__ + "Settings") self.layBox = QGridLayout(self.dialog.mainWidget()) self.title = KTitleWidget(self.dialog) self.title.setText(__doc__ + " !") self.title.setAutoHideTimeout(3000) self.FontButton = KFontRequester(self.dialog) self.tfont = QFont(QVariant(self.configurations.readEntry("TextFont", QVariant(QFont())))) self.FontButton.setFont(self.tfont) self.ColorButton = KColorButton(self.dialog) self.tcolor = QColor(self.configurations.readEntry("TextColor", QColor("#000").name())) self.ColorButton.setColor(self.tcolor) self.BColorButton = KColorButton(self.dialog) # button to update the DB via sudo updatedb self.UpdateDB = KPushButton("Update Database", self.dialog, clicked=lambda: self.update_db()) self.UpdateDB.setToolTip("Database is Updated every Reboot and Daily!") self.Histor = KPushButton("Delete my History", self.dialog, clicked=delete_my_history) self.Histor.setToolTip("History is Deleted every Reboot !") # list of banned words separated by spaces self.banned = KTextEdit(self.dialog) self.banned.setPlainText(self.configurations.readEntry( "Banned", "sex p**n drugs suicide decapitate religion").toString()) # set the colors cg = KConfig("kdeglobals") color = cg.group("Colors:View").readEntry( "BackgroundAlternate").split(",") self.bcolor = QColor(int(color[0]), int(color[1]), int(color[2])) self.BColorButton.setColor(self.bcolor) self.history_file_path_field = KLineEdit(HISTORY_FILE_PATH) self.history_file_path_field.setDisabled(True) self.python_file_path_field = KLineEdit(__file__) self.python_file_path_field.setDisabled(True) self.kill_baloo = QCheckBox("Disable Baloo") self.kill_baloo.setToolTip("Enable/Disable Desktop Search Indexing") self.kill_baloo.stateChanged.connect(lambda: call( DISABLE_BALOO_CMD.format(str( not self.kill_baloo.isChecked()).lower()), shell=True)) self.kill_baloo.stateChanged.connect(lambda: QMessageBox.information( self.dialog, __doc__, """ <b>Indexing Disabled, Baloo is Dead ! """ if self.kill_baloo.isChecked() else """ <b>Indexing Enabled, Baloo is Running !""")) self.updatez = KPushButton("Check for Updates", self.dialog, clicked=lambda: self.check_for_updates()) self.updatez.setToolTip("Check for Pylou updates from the internet") self.home_sweet_home = QCheckBox("Only Search Home") self.home_sweet_home.setToolTip("Only Search on my Home folders") self.home_sweet_home.setChecked( bool(self.configurations.readEntry("Home", True))) # pack all widgets self.layBox.addWidget(self.title, 0, 1) self.layBox.addWidget(QLabel("Font"), 1, 0) self.layBox.addWidget(self.FontButton, 1, 1) self.layBox.addWidget(QLabel("Text Color"), 2, 0) self.layBox.addWidget(self.ColorButton, 2, 1) self.layBox.addWidget(QLabel("Alternate Color"), 3, 0) self.layBox.addWidget(self.BColorButton, 3, 1) self.layBox.addWidget(QLabel(), 4, 0) self.layBox.addWidget(QLabel("Mainteniance"), 5, 0) self.layBox.addWidget(self.UpdateDB, 5, 1) self.layBox.addWidget(QLabel("Privacy"), 6, 0) self.layBox.addWidget(self.Histor, 6, 1) self.layBox.addWidget(QLabel("History file"), 7, 0) self.layBox.addWidget(self.history_file_path_field, 7, 1) self.layBox.addWidget(QLabel(__package__ + "file"), 8, 0) self.layBox.addWidget(self.python_file_path_field, 8, 1) self.layBox.addWidget(QLabel("Banned Words"), 9, 0) self.layBox.addWidget(self.banned, 9, 1) self.layBox.addWidget(QLabel("SelfUpdating"), 10, 0) self.layBox.addWidget(self.updatez, 10, 1) self.layBox.addWidget(QLabel("<b>Disable Indexing"), 12, 0) self.layBox.addWidget(self.kill_baloo, 12, 1) self.layBox.addWidget(QLabel("Search Paths"), 13, 0) self.layBox.addWidget(self.home_sweet_home, 13, 1) # button box on the bottom self.dialog.setButtons(KDialog.ButtonCodes( KDialog.ButtonCode(KDialog.Ok | KDialog.Cancel | KDialog.Apply))) # connect self.dialog.applyClicked.connect(self.configAccepted) self.dialog.okClicked.connect(self.configAccepted) @pyqtSignature("configAccepted()") def configAccepted(self): """Save configuration settings.""" self.tcolor = self.ColorButton.color() self.bcolor = self.BColorButton.color() self._widget.treeview.nativeWidget().setFont(self.tfont) self._widget.treeview.nativeWidget().setStyleSheet( "color:{};alternate-background-color:{}".format( self.tcolor.name(), self.bcolor.name())) self.configurations.writeEntry("TextColor", self.tcolor.name()) self.configurations.writeEntry("AlternateBColor", self.bcolor.name()) self.configurations.writeEntry("TextFont", QVariant(self.tfont)) self.configurations.writeEntry("Banned", self.banned.toPlainText()) self.configurations.writeEntry("Home", self.home_sweet_home.isChecked()) def showConfigurationInterface(self): """Show configuration dialog.""" self.dialog.show() self.dialog.raise_() def check_for_updates(self): """Method to check for updates from Git repo versus this version.""" this_version = str(open(__file__).read()) last_version = str(urlopen(__source__).read()) if this_version != last_version: m = "Theres new Version available!<br>Download update from the web" else: m = "No new updates!<br>You have the lastest version of this app!." return QMessageBox.information(None, __doc__.title(), "<b>" + m)
class TreeNode(object): """store data for a class and manage hierarchy""" def __init__(self, classid,name,rect=None,color=None,pos=None,accu = 1.0,parent=None): super(TreeNode, self).__init__() self.classid = classid self.name = name self.parent = parent self.accu = accu self.rect = QRectF(*rect) if rect else rect self.color = QColor(color) if color else color self.pos = QPointF(*pos) if pos else pos self.children = [] if parent: parent.children.append(self) # def __init__(self,jsonobj): # self.__init__(jsonobj['id'],jsonobj['name'],jsonobj['rect'],jsonobj['color'],jsonobj['pos']) # for child in jsonobj['children']: # childItem = TreeNode(child) # self.children.append(childItem) # childItem.parent = self def isLeaf(self): if self.children: return False else: return True def isRoot(self): if self.parent: return False else: return True def toJSON(self): jsonObj = {} jsonObj['id']= self.classid jsonObj['name'] = self.name jsonObj['rect'] = [self.rect.left(),self.rect.top(),self.rect.width(),self.rect.height()] if self.rect else self.rect jsonObj['color'] = str(self.color.name()) if self.color else self.color jsonObj['pos'] = [self.pos.x(),self.pos.y()] if isinstance(self.pos,QPointF) else self.pos jsonObj['accu'] = self.accu jsonObj['children'] = [] for child in self.children: jsonObj['children'].append(child.toJSON()) return jsonObj def __str__(self): tempstr = "%s %s\n" % (self.classid,self.name) for child in self.children: tempstr+= ' '+str(child) return tempstr def findNode(self,id): if self.classid == id: return self for child in self.children: result = child.findNode(id) if result: return result return None def toplogicalDistance(self,id1,id2): if id1==id2: return 0 else: node1 = self.findNode(id1) node2 = self.findNode(id2) if node1 and node2: if node1.parent == node2.parent: return 1 else: return 2 return 0 def matrixDistance(self,id1,id2): if id1==id2: return 0 else: node1 = self.findNode(id1) node2 = self.findNode(id2) if node1 and node2: pos1 = node1.pos + node1.parent.pos pos2 = node2.pos + node2.parent.pos return QLineF(pos1,pos2).length() return 2000.0 def transactionPossibility(self,id1,id2): node1 = self.findNode(id1) node2 = self.findNode(id2) if node1 and node2: return node1.accu * node2.accu else: return 1.0
class LedIndicator(QWidget): valueChanged = pyqtSignal(bool) def __init__(self, parent=None): QWidget.__init__(self, parent) self._value = False self._color = QColor(Qt.red) self._flashing = False @pyqtProperty(QColor) def color(self): return self._color @color.setter def color(self, color): self.setColor(color) def setColor(self, newColor): if (newColor == self._color): return oldKey = self._generateKey() QPixmapCache.remove(oldKey) self._color = QColor(newColor) self.update() def isOn(self): return bool(self._value) def value(self): return self._value def setValue(self, newValue): if self._value != newValue: self._value = newValue self.update() self.valueChanged.emit(self._value) @pyqtSlot(bool) def toggle(self): self.setValue(not self._value) @pyqtSlot() def turnOn(self): self.setValue(True) @pyqtSlot() def turnOff(self): self.setValue(False) def flashOnce(self, duration=0.1): self.turnOn() QTimer.singleShot(int(1E3 * duration), self.turnOff) def flashContinously(self, duration=0.1): if self._flashing: return self.turnOn() self._flashing = True QTimer.singleShot(int(1E3 * duration), self._endFlash) def _endFlash(self): self.turnOff() self._flashing = False def _generateKey(self): # Because of the centering code below, both w and h are characteristics for the pixmap. return "QlxLed:%s:%s:%s:%s" % (self._color.name(), self.width(), self.height(), self._value) def sizeHint(self): return QSize(24, 24) def minimumSizeHint(self): return QSize(12, 12) def heightForWidth(self, width): return width def paintEvent(self, event): w = self.width() h = self.height() s = min(w, h) key = self._generateKey() pixmap = QPixmapCache.find(key) if not pixmap: pixmap = QPixmap(w, h) pixmap.fill(self, QPoint(0, 0)) # Fill pixmap with widget background pixPainter = QPainter(pixmap) pixPainter.setRenderHint(QPainter.Antialiasing) # Offsets for centering ox = int(0.5 * (w - s)) oy = int(0.5 * (h - s)) insideColor = self._color if not self._value: insideColor = insideColor.darker(250) gradient = QRadialGradient(ox + 0.5 * s, oy + 0.5 * s, 0.5 * s) gradient.setColorAt(0.27, insideColor) gradient.setColorAt(0.6, insideColor.darker(120)) gradient.setColorAt(1.0, insideColor.darker(160)) pixPainter.setBrush(gradient) pixPainter.setPen(QPen(Qt.black, 2)) pixPainter.drawEllipse(1 + ox, 1 + oy, s - 2, s - 2) pixPainter.end() QPixmapCache.insert(key, pixmap) p = QPainter() p.begin(self) p.drawPixmap(QPoint(0, 0), pixmap) p.end()
def __init__(self, parent=None): " Initialize QWidget inside MyMainWindow " super(MyMainWindow, self).__init__(parent) QWidget.__init__(self) self.statusBar().showMessage(" {}".format(__doc__)) self.setStyleSheet("QStatusBar{color:grey;}") self.setWindowTitle(__doc__) self.setWindowIcon(QIcon.fromTheme("face-monkey")) self.setFont(QFont("Ubuntu Light", 10)) self.setMaximumSize(QDesktopWidget().screenGeometry().width(), QDesktopWidget().screenGeometry().height()) # directory auto completer self.completer = QCompleter(self) self.dirs = QDirModel(self) self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot) self.completer.setModel(self.dirs) self.completer.setCaseSensitivity(Qt.CaseInsensitive) self.completer.setCompletionMode(QCompleter.PopupCompletion) # Proxy support, by reading http_proxy os env variable proxy_url = QUrl(environ.get("http_proxy", "")) QNetworkProxy.setApplicationProxy( QNetworkProxy( QNetworkProxy.HttpProxy if str(proxy_url.scheme()).startswith("http") else QNetworkProxy.Socks5Proxy, proxy_url.host(), proxy_url.port(), proxy_url.userName(), proxy_url.password(), ) ) if "http_proxy" in environ else None print((" INFO: Proxy Auto-Config as " + str(proxy_url))) # basic widgets layouts and set up self.mainwidget = QTabWidget() self.mainwidget.setToolTip(__doc__) self.mainwidget.setContextMenuPolicy(Qt.CustomContextMenu) self.mainwidget.tabCloseRequested.connect(lambda: self.mainwidget.setTabPosition(randint(0, 3))) # if self.mainwidget.tabPosition() == 0 # else self.mainwidget.setTabPosition(0)) self.mainwidget.setStyleSheet("QTabBar{color:white;font-weight:bold;}") self.mainwidget.setTabBar(TabBar(self)) self.mainwidget.setMovable(True) self.mainwidget.setTabsClosable(True) self.mainwidget.setTabShape(QTabWidget.Triangular) self.setCentralWidget(self.mainwidget) self.dock1 = QDockWidget() self.dock2 = QDockWidget() self.dock3 = QDockWidget() for a in (self.dock1, self.dock2, self.dock3): a.setWindowModality(Qt.NonModal) a.setWindowOpacity(0.9) a.setWindowTitle(__doc__ if a.windowTitle() == "" else a.windowTitle()) a.setStyleSheet(" QDockWidget::title{text-align:center;}") self.mainwidget.addTab(a, QIcon.fromTheme("face-smile"), "Double Click Me") # Paleta de colores para pintar transparente self.palette().setBrush(QPalette.Base, Qt.transparent) self.setPalette(self.palette()) self.setAttribute(Qt.WA_OpaquePaintEvent, False) # toolbar and basic actions self.toolbar = QToolBar(self) self.toolbar.setIconSize(QSize(24, 24)) # spacer widget for left self.left_spacer = QWidget(self) self.left_spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) # spacer widget for right self.right_spacer = QWidget(self) self.right_spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) qaqq = QAction(QIcon.fromTheme("application-exit"), "Quit", self) qaqq.setShortcut("Ctrl+Q") qaqq.triggered.connect(exit) qamin = QAction(QIcon.fromTheme("go-down"), "Minimize", self) qamin.triggered.connect(lambda: self.showMinimized()) qamax = QAction(QIcon.fromTheme("go-up"), "Maximize", self) qanor = QAction(QIcon.fromTheme("view-fullscreen"), "AutoCenter AutoResize", self) qanor.triggered.connect(self.center) qatim = QAction(QIcon.fromTheme("mail-signed-verified"), "View Date and Time", self) qatim.triggered.connect(self.timedate) qabug = QAction(QIcon.fromTheme("help-about"), "Report a Problem", self) qabug.triggered.connect( lambda: qabug.setDisabled(True) if not call("xdg-open mailto:" + "*****@*****.**".decode("rot13"), shell=True) else " ERROR " ) qamax.triggered.connect(lambda: self.showMaximized()) qaqt = QAction(QIcon.fromTheme("help-about"), "About Qt", self) qaqt.triggered.connect(lambda: QMessageBox.aboutQt(self)) qakde = QAction(QIcon.fromTheme("help-about"), "About KDE", self) if KDE: qakde.triggered.connect(KHelpMenu(self, "", False).aboutKDE) qaslf = QAction(QIcon.fromTheme("help-about"), "About Self", self) if KDE: qaslf.triggered.connect(KAboutApplicationDialog(aboutData, self).exec_) else: qaslf.triggered.connect( lambda: QMessageBox.about( self.mainwidget, __doc__, "".join( ( __doc__, linesep, "version ", __version__, ", (", __license__, "), by ", __author__, ", ( ", __email__, " )", linesep, ) ), ) ) qafnt = QAction(QIcon.fromTheme("tools-check-spelling"), "Set GUI Font", self) if KDE: font = QFont() qafnt.triggered.connect( lambda: self.setStyleSheet( "".join(("*{font-family:", str(font.toString()), "}")) if KFontDialog.getFont(font)[0] == QDialog.Accepted else "" ) ) else: qafnt.triggered.connect( lambda: self.setStyleSheet("".join(("*{font-family:", str(QFontDialog.getFont()[0].toString()), "}"))) ) qasrc = QAction(QIcon.fromTheme("applications-development"), "View Source Code", self) qasrc.triggered.connect(lambda: call("xdg-open {}".format(__file__), 1)) qakb = QAction(QIcon.fromTheme("input-keyboard"), "Keyboard Shortcuts", self) qakb.triggered.connect( lambda: QMessageBox.information(self.mainwidget, "Keyboard Shortcuts", " Ctrl+Q = Quit ") ) qapic = QAction(QIcon.fromTheme("camera-photo"), "Take a Screenshot", self) qapic.triggered.connect( lambda: QPixmap.grabWindow(QApplication.desktop().winId()).save( QFileDialog.getSaveFileName( self.mainwidget, " Save Screenshot As ...", path.expanduser("~"), ";;(*.png) PNG", "png" ) ) ) qatb = QAction(QIcon.fromTheme("go-top"), "Toggle ToolBar", self) qatb.triggered.connect(lambda: self.toolbar.hide() if self.toolbar.isVisible() is True else self.toolbar.show()) qati = QAction(QIcon.fromTheme("help-browser"), "Switch ToolBar Icon Size", self) qati.triggered.connect( lambda: self.toolbar.setIconSize(self.toolbar.iconSize() * 4) if self.toolbar.iconSize().width() * 4 == 24 else self.toolbar.setIconSize(self.toolbar.iconSize() / 4) ) qasb = QAction(QIcon.fromTheme("zoom-in"), "Toggle Tabs Bar", self) qasb.triggered.connect( lambda: self.mainwidget.tabBar().hide() if self.mainwidget.tabBar().isVisible() is True else self.mainwidget.tabBar().show() ) qadoc = QAction(QIcon.fromTheme("help-browser"), "On-line Docs", self) qadoc.triggered.connect(lambda: open_new_tab(__url__)) qapy = QAction(QIcon.fromTheme("help-about"), "About Python", self) qapy.triggered.connect(lambda: open_new_tab("http://python.org/about")) qali = QAction(QIcon.fromTheme("help-browser"), "Read Licence", self) qali.triggered.connect(lambda: open_new_tab(__full_licence__)) qacol = QAction(QIcon.fromTheme("preferences-system"), "Set GUI Colors", self) if KDE: color = QColor() qacol.triggered.connect( lambda: self.setStyleSheet("".join(("* { background-color: ", str(color.name()), "}"))) if KColorDialog.getColor(color, self) else "" ) else: qacol.triggered.connect( lambda: self.setStyleSheet( "".join((" * { background-color: ", str(QColorDialog.getColor().name()), " } ")) ) ) qatit = QAction(QIcon.fromTheme("preferences-system"), "Set the App Window Title", self) qatit.triggered.connect(self.seTitle) self.toolbar.addWidget(self.left_spacer) self.toolbar.addSeparator() for b in ( qaqq, qamin, qanor, qamax, qasrc, qakb, qacol, qatim, qatb, qafnt, qati, qasb, qatit, qapic, qadoc, qali, qaslf, qaqt, qakde, qapy, qabug, ): self.toolbar.addAction(b) self.addToolBar(Qt.TopToolBarArea, self.toolbar) self.toolbar.addSeparator() self.toolbar.addWidget(self.right_spacer) # define the menu menu = self.menuBar() # File menu items menu.addMenu("&File").addActions((qaqq,)) menu.addMenu("&Window").addActions((qamax, qanor, qamin)) # Settings menu menu.addMenu("&Settings").addActions((qasrc, qacol, qafnt, qatim, qatb, qati, qasb, qapic)) # Help menu items menu.addMenu("&Help").addActions((qadoc, qakb, qabug, qali, qaqt, qakde, qapy, qaslf)) # Tray Icon tray = QSystemTrayIcon(QIcon.fromTheme("face-devilish"), self) tray.setToolTip(__doc__) traymenu = QMenu() traymenu.addActions((qamax, qanor, qamin, qaqq)) tray.setContextMenu(traymenu) tray.show() def contextMenuRequested(point): " quick and dirty custom context menu " menu = QMenu() menu.addActions( ( qaqq, qamin, qanor, qamax, qasrc, qakb, qacol, qafnt, qati, qasb, qatb, qatim, qatit, qapic, qadoc, qali, qaslf, qaqt, qakde, qapy, qabug, ) ) menu.exec_(self.mapToGlobal(point)) self.mainwidget.customContextMenuRequested.connect(contextMenuRequested) def must_be_checked(widget_list): " widget tuple passed as argument should be checked as ON " for each_widget in widget_list: try: each_widget.setChecked(True) except: pass def must_have_tooltip(widget_list): " widget tuple passed as argument should have tooltips " for each_widget in widget_list: try: each_widget.setToolTip(each_widget.text()) except: each_widget.setToolTip(each_widget.currentText()) finally: each_widget.setCursor(QCursor(Qt.PointingHandCursor)) def must_autofillbackground(widget_list): " widget tuple passed as argument should have filled background " for each_widget in widget_list: try: each_widget.setAutoFillBackground(True) except: pass def must_glow(widget_list): " apply an glow effect to the widget " for glow, each_widget in enumerate(widget_list): try: if each_widget.graphicsEffect() is None: glow = QGraphicsDropShadowEffect(self) glow.setOffset(0) glow.setBlurRadius(99) glow.setColor(QColor(99, 255, 255)) each_widget.setGraphicsEffect(glow) # glow.setEnabled(False) try: each_widget.clicked.connect( lambda: each_widget.graphicsEffect().setEnabled(True) if each_widget.graphicsEffect().isEnabled() is False else each_widget.graphicsEffect().setEnabled(False) ) except: each_widget.sliderPressed.connect( lambda: each_widget.graphicsEffect().setEnabled(True) if each_widget.graphicsEffect().isEnabled() is False else each_widget.graphicsEffect().setEnabled(False) ) except: pass ####################################################################### self.group1 = QGroupBox() self.group1.setTitle(__doc__) self.frmt = QComboBox(self.group1) self.frmt.addItems(["blah ", "blah blah", "blah blah blah"]) self.file1 = QLineEdit() self.file1.setPlaceholderText("/full/path/to/one_file.py") self.file1.setCompleter(self.completer) self.borig = QPushButton(QIcon.fromTheme("folder-open"), "Open") vboxg1 = QVBoxLayout(self.group1) for each_widget in ( QLabel('<b style="color:white;">some comment'), self.file1, self.borig, QLabel('<b style="color:white;">Lorem Impsum'), self.frmt, ): vboxg1.addWidget(each_widget) self.group2 = QGroupBox() self.group2.setTitle(__doc__) self.nwfl = QCheckBox("Be Awesome") self.smll = QCheckBox("Solve the Squaring of the Circle") self.lrgf = QCheckBox("Im just a QCheckBox") self.case = QCheckBox("Use Quantum Processing") vboxg2 = QVBoxLayout(self.group2) for each_widget in (self.nwfl, self.smll, self.lrgf, self.case): vboxg2.addWidget(each_widget) group3 = QGroupBox() group3.setTitle(__doc__) self.plai = QCheckBox("May the Force be with You") self.nocr = QCheckBox("Im just a Place Holder") self.ridt = QCheckBox("Lorem Impsum") self.nocm = QCheckBox("Divide by Zero") vboxg3 = QVBoxLayout(group3) for each_widget in (self.plai, self.nocr, self.ridt, self.nocm): vboxg3.addWidget(each_widget) container = QWidget() hbox = QHBoxLayout(container) for each_widget in (self.group2, self.group1, group3): hbox.addWidget(each_widget) self.dock1.setWidget(container) # dock 2 self.dock2.setWidget(QPlainTextEdit()) # dock 3 self.dock3.setWidget(QCalendarWidget()) # configure some widget settings must_be_checked((self.nwfl, self.smll, self.lrgf, self.plai)) must_have_tooltip((self.plai, self.nocr, self.ridt, self.nocm, self.nwfl, self.smll, self.lrgf, self.case)) must_autofillbackground( (self.plai, self.nocr, self.ridt, self.nocm, self.nwfl, self.smll, self.lrgf, self.case) ) must_glow((self.plai, self.nocr, self.ridt, self.nocm, self.nwfl))
class ConfigDialog(QDialog): def __init__(self, parent=None): QDialog.__init__(self, parent) self._layout = QVBoxLayout(self) self._tabdialog = QTabWidget(self) self._layout.addWidget(self._tabdialog) w = _config_dialog.Ui_config_dialog() w.setupUi(self._tabdialog) self.widgets = w self._buttonbox = QDialogButtonBox(QDialogButtonBox.Save|QDialogButtonBox.Cancel) self._buttonbox.setParent(self) signal_connect(self._buttonbox, SIGNAL("accepted()"), self.accept) signal_connect(self._buttonbox, SIGNAL("rejected()"), self.reject) self._layout.addWidget(self._buttonbox) self._layout.setContentsMargins(3,3,3,3) self.font = QFont() self.color = QColor() self.config = yobot_interfaces.component_registry.get_component("client-config") self.account_items = {} signal_connect(w.account_add, SIGNAL("clicked()"), lambda: self.add_modify_account(add=True)) signal_connect(w.account_edit, SIGNAL("clicked()"), lambda: self.add_modify_account(add=False)) signal_connect(w.account_del, SIGNAL("clicked()"), self.remove_account) signal_connect(w.select_color, SIGNAL("clicked()"), lambda: self.change_formatting(color=True)) signal_connect(w.select_font, SIGNAL("clicked()"), lambda: self.change_formatting(font=True)) signal_connect(w.agent_address, SIGNAL("editingFinished()"), self.change_agent) self.connect_global_bool(w.html_relsize, "appearance", "use_html_relsize") self.connect_global_bool(w.show_joinpart, "appearance", "show_joinpart") self.input_validated = True self.setWindowTitle("Yobot Configuration") def connect_global_bool(self, widget, dictname, optname, default=False): signal_connect(widget, SIGNAL("toggled(bool)"), lambda b: self.config.globals.setdefault(dictname, {}).__setitem__(optname, b)) def load_settings(self): w = self.widgets if not self.config: log_warn("config object not available! bailing") return #for font.. appearance = self.config.globals.setdefault("appearance", {}) family = appearance.get("font_family", None) size = appearance.get("font_size", None) color = appearance.get("font_color", None) if family: self.font.setFamily(family) if size: self.font.setPointSize(size) if color: self.color.setNamedColor(color) bold = appearance.get("font_bold", False) italic = appearance.get("font_italic", False) underline = appearance.get("font_underline", False) html_relsize = appearance.get("use_html_relsize", False) show_joinpart = appearance.get("show_joinpart", False) self.font.setBold(bold) self.font.setItalic(italic) self.font.setUnderline(underline) w.html_relsize.setChecked(html_relsize) w.show_joinpart.setChecked(show_joinpart) self.change_formatting() #for the agent... agent = self.config.globals.get("agent_address", None) if agent: w.agent_address.setText(agent) self.change_agent() #for accounts: for a in self.config.accounts: log_warn("got account", a) if a.get("name", None) and a.get("improto", None): #get name and icon name, icon = getProtoIconAndName(getattr(yobotproto, a["improto"], "")) log_debug(icon, name) i = QTreeWidgetItem((a["name"], name)) i.setIcon(1, icon) i.setData(0, ITEM_PLACEHOLDER_ROLE, a) self.account_items[i] = a self.widgets.accounts.addTopLevelItem(i) def remove_account(self): #get current item: w = self.widgets item = w.accounts.currentItem() #get the index (ugh.. this is tedious) itemindex = w.accounts.indexOfTopLevelItem(item) if itemindex == -1: log_err("couldn't get index!") return account = self.account_items[item] #remove the item from the widget: w.accounts.takeTopLevelItem(itemindex) #find the account in our global config list index = -1 for i in xrange(0, len(self.config.accounts)): a = self.config.accounts[i] if str(a["name"]) == str(account["name"]) and str(a["improto"]) == str(account["improto"]): index = i break else: pass if index >= 0: log_debug("index:", index) self.config.accounts.pop(index) #finally, remove it from the mapping self.account_items.pop(item) def add_modify_account(self, add=False): dlg = AccountSettingsDialog(self) if not add: item = self.widgets.accounts.currentItem() if not item: return account = self.account_items.get(item) if not account: return #account = item.data(0, ITEM_PLACEHOLDER_ROLE).toPyObject() dlg.fill_from(account) else: item = QTreeWidgetItem() result = dlg.exec_() if not result == QDialog.Accepted: return new_a = dlg.values item.setText(0, new_a["name"]) #get icon and name... name, icon = getProtoIconAndName(getattr(yobotproto, new_a["improto"], -1)) item.setText(1, name) item.setIcon(1, icon) if add: if self.account_exists(new_a): print "account already exists.. not adding" return item.setData(0, ITEM_PLACEHOLDER_ROLE, new_a) self.widgets.accounts.addTopLevelItem(item) self.config.accounts.append(new_a) else: account.update(new_a) def account_exists(self, d): for a in self.config.accounts: if d["name"] == a["name"] and d["improto"] == a["improto"]: return True return False def change_formatting(self, color=False, font=False): if color: _color = QColorDialog.getColor(self.color, self, "Select Color") if _color.isValid(): self.color = _color elif font: self.font, _ = QFontDialog.getFont(self.font, self, "Select Font") widgetformatter(self.widgets.sample_text, self.font, self.color, klass="QPlainTextEdit") #now, change the config objects.. fmt = self.config.globals["appearance"] fmt.update({ "font_family":str(self.font.family()), "font_size":int(self.font.pointSize()), "font_color":str(self.color.name()), "font_bold":bool(self.font.bold()), "font_italic":bool(self.font.italic()), "font_underline":bool(self.font.underline()) }) def change_agent(self): #bah.. the same boring thing as always s = str(self.widgets.agent_address.text()) if len(s.rsplit(":", 1)) == 2 and not str.isdigit(s.rsplit(":",1)[1]): self.input_validated = False self.widgets.agent_address.setStyleSheet("background-color:red;") else: self.widgets.agent_address.setStyleSheet("background-color:green") if s: self.config.globals["agent_address"] = str(s) self.input_validated = True def accept(self): #do some stuff first, like save if self.input_validated: self.config.save() QDialog.accept(self) else: QErrorMessage(self).showMessage("Bad input.. (somewhere?)")
class StarTrekFortunes(plasmascript.Applet): def __init__(self,parent,args=None): plasmascript.Applet.__init__(self,parent) def init(self): self._text = None self._quoteParser = QuoteParser(self.package().path()) # set configuration self.conf = self.config('startrekfortune-plasmoid') # parse or initialize configurations self._textColor = QColor(self.conf.readEntry("textColor", "#000000")) self._shadowColor = QColor(self.conf.readEntry("shadowColor", "#FFFFFF")) self._font = QFont(self.conf.readEntry("font", QFont("Sans-Serif", 12, QFont.Bold))) self._showBackground = self.conf.readEntry("showBackground", "False").toBool() self._showSVG = self.conf.readEntry("showSVG", "True").toBool() self._updateInterval = self.conf.readEntry("updateInterval", 5).toInt()[0] # set timer self._updateTimer = QTimer() self.setTimer() self.setPlasmaBackground() # set layout and initial size self.layout = QGraphicsLinearLayout(Qt.Horizontal, self.applet) self.setAspectRatioMode(Plasma.KeepAspectRatio) self.setHasConfigurationInterface(True) if self.conf.readEntry("size_initialized", "0").toString() == "0": self.resize(385, 277) self.conf.writeEntry("size_initialized", "1") def showConfigurationInterface(self): dialog = KPageDialog() dialog.setWindowTitle("Star Trek Fortune Settings") dialog.setFaceType(KPageDialog.List) dialog.setButtons(KDialog.ButtonCode(KDialog.Ok | KDialog.Cancel)) # Appearance Settings defaultConfig = {"textColor":self._textColor,"shadowColor":self._shadowColor, "font":self._font,"hideBackground":self._showBackground, "hideSVG":self._showSVG, "updateInterval":self._updateInterval} self._configDialog = STFConfig(self, defaultConfig) appearancePage = dialog.addPage(self._configDialog,i18n("Appearance")) appearancePage.setIcon(KIcon("preferences-desktop-color")) self.connect(dialog, SIGNAL("okClicked()"), self.configAccepted) self.connect(dialog, SIGNAL("cancelClicked()"), self.configDenied) dialog.resize(540,330) dialog.exec_() def configAccepted(self): # apply new settings self._textColor = self._configDialog.getTextColor() self._shadowColor = self._configDialog.getShadowColor() self._font = self._configDialog.getFont() self._showBackground = self._configDialog.getShowBackground() self._showSVG = self._configDialog.getShowSVG() self._updateInterval = self._configDialog.getUpdateInterval() # save new configuration self.conf.writeEntry("textColor", self._textColor.name()) self.conf.writeEntry("shadowColor", self._shadowColor.name()) self.conf.writeEntry("font", self._font.toString()) self.conf.writeEntry("showBackground", str(self._showBackground)) self.conf.writeEntry("showSVG", str(self._showSVG)) self.conf.writeEntry("updateInterval", str(self._updateInterval)) self.setTimer() self.setPlasmaBackground() self.update() def configDenied(self): pass def setPlasmaBackground(self): # show plasma background if preference is set if self._showBackground: self.setBackgroundHints(Plasma.Applet.DefaultBackground) else: self.setBackgroundHints(Plasma.Applet.NoBackground) def paintInterface(self, painter, option, rect): painter.save() # show UFP logo if preference is set if self._showSVG: svg_current = Plasma.Svg() svg_current.setImagePath(self.package().path() + "contents/icons/ufp.svg") svg_current.resize(QSizeF(rect.size())) svg_current.paint(painter, QPointF(rect.topLeft())) if self._text is None: self._text = self.getFortune() # first paint text for dropshadow and then paint the text painter.setPen(self._shadowColor) rect.moveTo(rect.left() + 1, rect.top() + 1) painter.setFont(self._font) painter.drawText(rect,Qt.TextWordWrap | Qt.AlignCenter, self._text) rect.moveTo(rect.left() - 1, rect.top() - 1) painter.setPen(self._textColor) painter.setFont(self._font) painter.drawText(rect, Qt.TextWordWrap | Qt.AlignCenter, self._text) painter.restore() def getFortune(self): return self._quoteParser.getRandomQuote() def updateFortune(self): self._text = self.getFortune() self.update() def setTimer(self): if not self._updateInterval is 0: self._updateTimer.setInterval(self._updateInterval * 60 * 1000) self._updateTimer.setSingleShot(False) self.connect(self._updateTimer, SIGNAL("timeout()"), self.updateFortune) self._updateTimer.start() else: self._updateTimer.stop()
def color_of_pixel(self, x, y): """Returns the pixel color of the pixel at coordinates x, y.""" c = QColor(QPixmap.grabWindow(QApplication.desktop().winId()).toImage().pixel(x, y)) return to_upper(str(c.name()))
def color(h, s, v): c = QColor() c.setHsv(h, s, v) return c.name()
def __init__(self, AUTO): ' Initialize QWidget inside MyMainWindow ' super(MyMainWindow, self).__init__() QWidget.__init__(self) self.auto = AUTO self.statusBar().showMessage(' {}'.format(__doc__)) self.setStyleSheet('QStatusBar{color:grey;}') self.setWindowTitle(__doc__) self.setWindowIcon(QIcon.fromTheme("face-monkey")) self.setFont(QFont('Ubuntu Light', 10)) self.setMaximumSize(QDesktopWidget().screenGeometry().width(), QDesktopWidget().screenGeometry().height()) self.base = path.abspath(path.join(getcwd(), str(datetime.now().year))) # directory auto completer self.completer = QCompleter(self) self.dirs = QDirModel(self) self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot) self.completer.setModel(self.dirs) self.completer.setCaseSensitivity(Qt.CaseInsensitive) self.completer.setCompletionMode(QCompleter.PopupCompletion) # process self.process1 = None self.process2 = None self.cmd1 = 'nice -n {n} arecord{v} -f {f} -c {c} -r {b} -t raw' self.cmd2 = 'oggenc - -r -C {c} -R {b} -q {q} {d}{t}{a} -o {o}' self.process3 = QProcess(self) #self.process3.finished.connect(self.on_process3_finished) #self.process3.error.connect(self.on_process3_error) self.cmd3 = ('nice -n 20 ' + 'sox "{o}" -n spectrogram -x {x} -y {y} -z 99 -t "{o}" -o "{o}.png"') self.actual_file = '' # re starting timers, one stops, one starts self.timerFirst = QTimer(self) self.timerFirst.timeout.connect(self.end) self.timerSecond = QTimer(self) self.timerSecond.timeout.connect(self.run) # Proxy support, by reading http_proxy os env variable proxy_url = QUrl(environ.get('http_proxy', '')) QNetworkProxy.setApplicationProxy(QNetworkProxy(QNetworkProxy.HttpProxy if str(proxy_url.scheme()).startswith('http') else QNetworkProxy.Socks5Proxy, proxy_url.host(), proxy_url.port(), proxy_url.userName(), proxy_url.password())) \ if 'http_proxy' in environ else None print((' INFO: Proxy Auto-Config as ' + str(proxy_url))) # basic widgets layouts and set up self.mainwidget = QTabWidget() self.mainwidget.setToolTip(__doc__) self.mainwidget.setMovable(True) self.mainwidget.setTabShape(QTabWidget.Triangular) self.mainwidget.setContextMenuPolicy(Qt.CustomContextMenu) self.mainwidget.setStyleSheet('QTabBar{color:white;font-weight:bold;}') self.mainwidget.setTabBar(TabBar(self)) self.mainwidget.setTabsClosable(False) self.setCentralWidget(self.mainwidget) self.dock1 = QDockWidget() self.dock2 = QDockWidget() self.dock3 = QDockWidget() self.dock4 = QDockWidget() self.dock5 = QDockWidget() for a in (self.dock1, self.dock2, self.dock3, self.dock4, self.dock5): a.setWindowModality(Qt.NonModal) # a.setWindowOpacity(0.9) a.setWindowTitle(__doc__ if a.windowTitle() == '' else a.windowTitle()) a.setStyleSheet('QDockWidget::title{text-align:center;}') self.mainwidget.addTab(a, QIcon.fromTheme("face-smile"), 'Double Click Me') # Paleta de colores para pintar transparente self.palette().setBrush(QPalette.Base, Qt.transparent) self.setPalette(self.palette()) self.setAttribute(Qt.WA_OpaquePaintEvent, False) # toolbar and basic actions self.toolbar = QToolBar(self) self.toolbar.setIconSize(QSize(24, 24)) # spacer widget for left self.left_spacer = QWidget(self) self.left_spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) # spacer widget for right self.right_spacer = QWidget(self) self.right_spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) qaqq = QAction(QIcon.fromTheme("application-exit"), 'Quit', self) qaqq.setShortcut('Ctrl+Q') qaqq.triggered.connect(exit) qamin = QAction(QIcon.fromTheme("go-down"), 'Minimize', self) qamin.triggered.connect(lambda: self.showMinimized()) qamax = QAction(QIcon.fromTheme("go-up"), 'Maximize', self) qanor = QAction(QIcon.fromTheme("view-fullscreen"), 'AutoCenter AutoResize', self) qanor.triggered.connect(self.center) qatim = QAction(QIcon.fromTheme("mail-signed-verified"), 'View Date and Time', self) qatim.triggered.connect(self.timedate) qabug = QAction(QIcon.fromTheme("help-about"), 'Report a Problem', self) qabug.triggered.connect(lambda: qabug.setDisabled(True) if not call( 'xdg-open mailto:' + '*****@*****.**'.decode('rot13'), shell=True) else ' ERROR ') qamax.triggered.connect(lambda: self.showMaximized()) qaqt = QAction(QIcon.fromTheme("help-about"), 'About Qt', self) qaqt.triggered.connect(lambda: QMessageBox.aboutQt(self)) qakde = QAction(QIcon.fromTheme("help-about"), 'About KDE', self) if KDE: qakde.triggered.connect(KHelpMenu(self, "", False).aboutKDE) qaslf = QAction(QIcon.fromTheme("help-about"), 'About Self', self) if KDE: qaslf.triggered.connect( KAboutApplicationDialog(aboutData, self).exec_) else: qaslf.triggered.connect(lambda: QMessageBox.about(self.mainwidget, __doc__, ''.join((__doc__, linesep, 'version ', __version__, ', (', __license__, '), by ', __author__, ', ( ', __email__, ' )', linesep )))) qafnt = QAction(QIcon.fromTheme("tools-check-spelling"), 'Set GUI Font', self) if KDE: font = QFont() qafnt.triggered.connect(lambda: self.setStyleSheet(''.join(( '*{font-family:', str(font.toString()), '}')) if KFontDialog.getFont(font)[0] == QDialog.Accepted else '')) else: qafnt.triggered.connect(lambda: self.setStyleSheet(''.join(('*{font-family:', str(QFontDialog.getFont()[0].toString()), '}')))) qasrc = QAction(QIcon.fromTheme("applications-development"), 'View Source Code', self) qasrc.triggered.connect(lambda: call('xdg-open {}'.format(__file__), shell=True)) qakb = QAction(QIcon.fromTheme("input-keyboard"), 'Keyboard Shortcuts', self) qakb.triggered.connect(lambda: QMessageBox.information(self.mainwidget, 'Keyboard Shortcuts', ' Ctrl+Q = Quit ')) qapic = QAction(QIcon.fromTheme("camera-photo"), 'Take a Screenshot', self) qapic.triggered.connect(lambda: QPixmap.grabWindow( QApplication.desktop().winId()).save(QFileDialog.getSaveFileName( self.mainwidget, " Save Screenshot As ...", path.expanduser("~"), ';;(*.png) PNG', 'png'))) qatb = QAction(QIcon.fromTheme("go-top"), 'Toggle ToolBar', self) qatb.triggered.connect(lambda: self.toolbar.hide() if self.toolbar.isVisible() is True else self.toolbar.show()) qati = QAction(QIcon.fromTheme("zoom-in"), 'Switch ToolBar Icon Size', self) qati.triggered.connect(lambda: self.toolbar.setIconSize(self.toolbar.iconSize() * 4) if self.toolbar.iconSize().width() * 4 == 24 else self.toolbar.setIconSize(self.toolbar.iconSize() / 4)) qasb = QAction(QIcon.fromTheme("preferences-other"), 'Toggle Tabs Bar', self) qasb.triggered.connect(lambda: self.mainwidget.tabBar().hide() if self.mainwidget.tabBar().isVisible() is True else self.mainwidget.tabBar().show()) qadoc = QAction(QIcon.fromTheme("help-browser"), 'On-line Docs', self) qadoc.triggered.connect(lambda: open_new_tab(str(__url__).strip())) qapy = QAction(QIcon.fromTheme("help-about"), 'About Python', self) qapy.triggered.connect(lambda: open_new_tab('http://python.org/about')) qali = QAction(QIcon.fromTheme("help-browser"), 'Read Licence', self) qali.triggered.connect(lambda: open_new_tab(__full_licence__)) qacol = QAction(QIcon.fromTheme("preferences-system"), 'Set GUI Colors', self) if KDE: color = QColor() qacol.triggered.connect(lambda: self.setStyleSheet(''.join(('* { background-color: ', str(color.name()), '}'))) if KColorDialog.getColor(color, self) else '') else: qacol.triggered.connect(lambda: self.setStyleSheet(''.join(( ' * { background-color: ', str(QColorDialog.getColor().name()), ' } ')))) qatit = QAction(QIcon.fromTheme("preferences-system"), 'Set the App Window Title', self) qatit.triggered.connect(self.seTitle) self.toolbar.addWidget(self.left_spacer) self.toolbar.addSeparator() self.toolbar.addActions((qaqq, qamin, qanor, qamax, qasrc, qakb, qacol, qatim, qatb, qafnt, qati, qasb, qatit, qapic, qadoc, qali, qaslf, qaqt, qakde, qapy, qabug)) self.addToolBar(Qt.TopToolBarArea, self.toolbar) self.toolbar.addSeparator() self.toolbar.addWidget(self.right_spacer) # define the menu menu = self.menuBar() # File menu items menu.addMenu('&File').addActions((qaqq, )) menu.addMenu('&Window').addActions((qamax, qanor, qamin)) # Settings menu menu.addMenu('&Settings').addActions((qasrc, qacol, qafnt, qatim, qatb, qati, qasb, qapic)) # Help menu items menu.addMenu('&Help').addActions((qadoc, qakb, qabug, qali, qaqt, qakde, qapy, qaslf)) # Tray Icon tray = QSystemTrayIcon(QIcon.fromTheme("face-devilish"), self) tray.setToolTip(__doc__) traymenu = QMenu() traymenu.addActions((qamax, qanor, qamin, qaqq)) tray.setContextMenu(traymenu) tray.show() def contextMenuRequested(point): ' quick and dirty custom context menu ' menu = QMenu() menu.addActions((qaqq, qamin, qanor, qamax, qasrc, qakb, qacol, qafnt, qati, qasb, qatb, qatim, qatit, qapic, qadoc, qali, qaslf, qaqt, qakde, qapy, qabug)) menu.exec_(self.mapToGlobal(point)) self.mainwidget.customContextMenuRequested.connect(contextMenuRequested) def must_be_checked(widget_list): ' widget tuple passed as argument should be checked as ON ' for each_widget in widget_list: try: each_widget.setChecked(True) except: pass def must_have_tooltip(widget_list): ' widget tuple passed as argument should have tooltips ' for each_widget in widget_list: try: each_widget.setToolTip(each_widget.text()) except: each_widget.setToolTip(each_widget.currentText()) finally: each_widget.setCursor(QCursor(Qt.PointingHandCursor)) def must_autofillbackground(widget_list): ' widget tuple passed as argument should have filled background ' for each_widget in widget_list: try: each_widget.setAutoFillBackground(True) except: pass def must_glow(widget_list): ' apply an glow effect to the widget ' for glow, each_widget in enumerate(widget_list): try: if each_widget.graphicsEffect() is None: glow = QGraphicsDropShadowEffect(self) glow.setOffset(0) glow.setBlurRadius(99) glow.setColor(QColor(99, 255, 255)) each_widget.setGraphicsEffect(glow) # glow.setEnabled(False) try: each_widget.clicked.connect(lambda: each_widget.graphicsEffect().setEnabled(True) if each_widget.graphicsEffect().isEnabled() is False else each_widget.graphicsEffect().setEnabled(False)) except: each_widget.sliderPressed.connect(lambda: each_widget.graphicsEffect().setEnabled(True) if each_widget.graphicsEffect().isEnabled() is False else each_widget.graphicsEffect().setEnabled(False)) except: pass ####################################################################### # dock 1 QLabel('<h1 style="color:white;"> Record !</h1>', self.dock1).resize( self.dock3.size().width() / 4, 25) self.group1 = QGroupBox() self.group1.setTitle(__doc__) self.spec = QPushButton(self) self.spec.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.spec.setMinimumSize(self.spec.size().width(), 250) self.spec.setFlat(True) self.spec.clicked.connect(self.spectro) self.clock = QLCDNumber() self.clock.setSegmentStyle(QLCDNumber.Flat) self.clock.setMinimumSize(self.clock.size().width(), 50) self.clock.setNumDigits(25) self.timer1 = QTimer(self) self.timer1.timeout.connect(lambda: self.clock.display( datetime.now().strftime("%d-%m-%Y %H:%M:%S %p"))) self.timer1.start(1000) self.clock.setToolTip(datetime.now().strftime("%c %x")) self.clock.setCursor(QCursor(Qt.CrossCursor)) self.diskBar = QProgressBar() self.diskBar.setMinimum(0) self.diskBar.setMaximum(statvfs(HOME).f_blocks * statvfs(HOME).f_frsize / 1024 / 1024 / 1024) self.diskBar.setValue(statvfs(HOME).f_bfree * statvfs(HOME).f_frsize / 1024 / 1024 / 1024) self.diskBar.setToolTip(str(statvfs(HOME).f_bfree * statvfs(HOME).f_frsize / 1024 / 1024 / 1024) + ' Gigabytes free') self.feedback = QPlainTextEdit(''.join(('<center><h3>', __doc__, ', version', __version__, __license__, ' <br> by ', __author__, ' <i>(Dev)</i>, Radio Comunitaria FM Reconquista <i>(Q.A.)</i><br>', 'FMReconquista.org.ar & GitHub.com/JuanCarlosPaco/Cinta-Testigo'))) self.rec = QPushButton(QIcon.fromTheme("media-record"), 'Record') self.rec.setMinimumSize(self.rec.size().width(), 50) self.rec.clicked.connect(self.go) # self.run self.stop = QPushButton(QIcon.fromTheme("media-playback-stop"), 'Stop') self.stop.clicked.connect(self.end) self.kill = QPushButton(QIcon.fromTheme("process-stop"), 'Kill') self.kill.clicked.connect(self.killer) vboxg1 = QVBoxLayout(self.group1) for each_widget in ( QLabel('<b style="color:white;"> Spectro'), self.spec, QLabel('<b style="color:white;"> Time '), self.clock, QLabel('<b style="color:white;"> Disk '), self.diskBar, QLabel('<b style="color:white;"> STDOUT + STDIN '), self.feedback, QLabel('<b style="color:white;"> Record '), self.rec, self.stop, self.kill): vboxg1.addWidget(each_widget) self.group2 = QGroupBox() self.group2.setTitle(__doc__) self.slider = QSlider(self) self.slid_l = QLabel(self.slider) self.slider.setCursor(QCursor(Qt.OpenHandCursor)) self.slider.sliderPressed.connect(lambda: self.slider.setCursor(QCursor(Qt.ClosedHandCursor))) self.slider.sliderReleased.connect(lambda: self.slider.setCursor(QCursor(Qt.OpenHandCursor))) self.slider.valueChanged.connect(lambda: self.slider.setToolTip(str(self.slider.value()))) self.slider.valueChanged.connect(lambda: self.slid_l.setText( '<h2 style="color:white;">{}'.format(self.slider.value()))) self.slider.setMinimum(10) self.slider.setMaximum(99) self.slider.setValue(30) self.slider.setOrientation(Qt.Vertical) self.slider.setTickPosition(QSlider.TicksBothSides) self.slider.setTickInterval(2) self.slider.setSingleStep(10) self.slider.setPageStep(10) vboxg2 = QVBoxLayout(self.group2) for each_widget in ( QLabel('<b style="color:white;">MINUTES of recording'), self.slider, QLabel('<b style="color:white;"> Default: 30 Min')): vboxg2.addWidget(each_widget) group3 = QGroupBox() group3.setTitle(__doc__) try: self.label2 = QLabel(getoutput('sox --version', shell=True)) self.label4 = QLabel(getoutput('arecord --version', shell=1)[:25]) self.label6 = QLabel(str(getoutput('oggenc --version', shell=True))) except: print(''' ERROR: No SOX, OGGenc avaliable ! ( sudo apt-get install vorbis-tools sox alsa-utils ) ''') exit() self.button5 = QPushButton(QIcon.fromTheme("audio-x-generic"), 'OGG --> ZIP') self.button5.clicked.connect(lambda: make_archive( str(QFileDialog.getSaveFileName(self, "Save OGG to ZIP file As...", getcwd(), ';;(*.zip)', 'zip')).replace('.zip', ''), "zip", path.abspath(path.join(getcwd(), str(datetime.now().year))))) self.button1 = QPushButton(QIcon.fromTheme("folder-open"), 'Files') self.button1.clicked.connect(lambda: call('xdg-open ' + getcwd(), shell=True)) self.button0 = QPushButton( QIcon.fromTheme("preferences-desktop-screensaver"), 'LCD OFF') self.button0.clicked.connect(lambda: call('sleep 3 ; xset dpms force off', shell=True)) vboxg3 = QVBoxLayout(group3) for each_widget in ( QLabel('<b style="color:white;"> OGG Output Codec '), self.label6, QLabel('<b style="color:white;"> Raw Record Backend '), self.label4, QLabel('<b style="color:white;"> Helper Libs '), self.label2, QLabel('<b style="color:white;"> OGG ZIP '), self.button5, QLabel('<b style="color:white;"> Files '), self.button1, QLabel('<b style="color:white;"> LCD '), self.button0): vboxg3.addWidget(each_widget) container = QWidget() hbox = QHBoxLayout(container) for each_widget in (self.group2, self.group1, group3): hbox.addWidget(each_widget) self.dock1.setWidget(container) # dock 2 QLabel('<h1 style="color:white;"> Hardware !</h1>', self.dock2).resize( self.dock2.size().width() / 4, 25) try: audioDriverStr = {Solid.AudioInterface.Alsa: "ALSA", Solid.AudioInterface.OpenSoundSystem: "Open Sound", Solid.AudioInterface.UnknownAudioDriver: "Unknown?"} audioInterfaceTypeStr = { Solid.AudioInterface.AudioControl: "Control", Solid.AudioInterface.UnknownAudioInterfaceType: "Unknown?", Solid.AudioInterface.AudioInput: "In", Solid.AudioInterface.AudioOutput: "Out"} soundcardTypeStr = { Solid.AudioInterface.InternalSoundcard: "Internal", Solid.AudioInterface.UsbSoundcard: "USB3", Solid.AudioInterface.FirewireSoundcard: "FireWire", Solid.AudioInterface.Headset: "Headsets", Solid.AudioInterface.Modem: "Modem"} display = QTreeWidget() display.setAlternatingRowColors(True) display.setHeaderLabels(["Items", "ID", "Drivers", "I / O", "Type"]) display.setColumnWidth(0, 350) display.setColumnWidth(1, 350) display.setColumnWidth(3, 75) # retrieve a list of Solid.Device for this machine deviceList = Solid.Device.allDevices() # filter the list of all devices and display matching results # note that we never create a Solid.AudioInterface object, but # receive one from the 'asDeviceInterface' call for device in deviceList: if device.isDeviceInterface( Solid.DeviceInterface.AudioInterface): audio = device.asDeviceInterface( Solid.DeviceInterface.AudioInterface) devtype = audio.deviceType() devstr = [] for key in audioInterfaceTypeStr: flag = key & devtype if flag: devstr.append(audioInterfaceTypeStr[key]) QTreeWidgetItem(display, [device.product(), audio.name(), audioDriverStr[audio.driver()], "/".join(devstr), soundcardTypeStr[audio.soundcardType()]]) self.dock2.setWidget(display) except: self.dock2.setWidget(QLabel(""" <center style='color:white;'> <h1>:(<br>ERROR: Please, install PyKDE !</h1><br> <br><i> (Sorry, can not use non-Qt Libs). Thanks </i><center>""")) ## dock 3 QLabel('<h1 style="color:white;"> Previews !</h1>', self.dock3).resize( self.dock3.size().width() / 4, 25) self.fileView = QColumnView() self.fileView.updatePreviewWidget.connect(self.play) self.fileView.setToolTip(' Browse and Preview Files ') self.media = None self.model = QDirModel() self.fileView.setModel(self.model) self.dock3.setWidget(self.fileView) # dock4 QLabel('<h1 style="color:white;"> Setup !</h1>', self.dock4).resize( self.dock4.size().width() / 4, 25) self.group4 = QGroupBox() self.group4.setTitle(__doc__) self.combo0 = QComboBox() self.combo0.addItems(['S16_LE', 'S32_LE', 'S16_BE', 'U16_LE', 'U16_BE', 'S24_LE', 'S24_BE', 'U24_LE', 'U24_BE', 'S32_BE', 'U32_LE', 'U32_BE']) self.combo1 = QComboBox() self.combo1.addItems(['1', '-1', '0', '2', '3', '4', '5', '6', '7', '8', '9', '10']) self.combo2 = QComboBox() self.combo2.addItems(['128', '256', '512', '1024', '64', '32', '16']) self.combo3 = QComboBox(self) self.combo3.addItems(['MONO', 'STEREO', 'Surround']) self.combo4 = QComboBox() self.combo4.addItems(['44100', '96000', '48000', '32000', '22050', '16000', '11025', '8000']) self.combo5 = QComboBox(self) self.combo5.addItems(['20', '19', '18', '17', '16', '15', '14', '13', '12', '10', '9', '8', '7', '6', '5', '4', '3', '2', '1', '0']) self.nepochoose = QCheckBox('Auto-Tag Files using Nepomuk Semantic') self.chckbx0 = QCheckBox('Disable Software based Volume Control') self.chckbx1 = QCheckBox('Output Sound Stereo-to-Mono Downmix') self.chckbx2 = QCheckBox('Add Date and Time MetaData to Sound files') self.chckbx3 = QCheckBox('Add Yourself as the Author Artist of Sound') vboxg4 = QVBoxLayout(self.group4) for each_widget in ( QLabel('<b style="color:white;"> Sound OGG Quality'), self.combo1, QLabel('<b style="color:white;"> Sound Record Format'), self.combo0, QLabel('<b style="color:white;"> Sound KBps '), self.combo2, QLabel('<b style="color:white;"> Sound Channels '), self.combo3, QLabel('<b style="color:white;"> Sound Sample Rate '), self.combo4, QLabel('<b style="color:white;"> Sound Volume'), self.chckbx0, QLabel('<b style="color:white;"> Sound Mix'), self.chckbx1, QLabel('<b style="color:white;"> Sound Meta'), self.chckbx2, QLabel('<b style="color:white;"> Sound Authorship'), self.chckbx3, QLabel('<b style="color:white;"> CPUs Priority'), self.combo5, QLabel('<b style="color:white;">Nepomuk Semantic User Experience'), self.nepochoose): vboxg4.addWidget(each_widget) self.dock4.setWidget(self.group4) # dock 5 QLabel('<h1 style="color:white;"> Voice Changer ! </h1>', self.dock5 ).resize(self.dock5.size().width() / 3, 25) self.group5 = QGroupBox() self.group5.setTitle(__doc__) self.dial = QDial() self.dial.setCursor(QCursor(Qt.OpenHandCursor)) self.di_l = QLabel(self.dial) self.di_l.resize(self.dial.size() / 8) self.dial.sliderPressed.connect(lambda: self.dial.setCursor(QCursor(Qt.ClosedHandCursor))) self.dial.sliderReleased.connect(lambda: self.dial.setCursor(QCursor(Qt.OpenHandCursor))) self.dial.valueChanged.connect(lambda: self.dial.setToolTip(str(self.dial.value()))) self.dial.valueChanged.connect(lambda: self.di_l.setText( '<h1 style="color:white;">{}'.format(self.dial.value()))) self.dial.setValue(0) self.dial.setMinimum(-999) self.dial.setMaximum(999) self.dial.setSingleStep(100) self.dial.setPageStep(100) self.dial.setWrapping(False) self.dial.setNotchesVisible(True) self.defo = QPushButton(QIcon.fromTheme("media-playback-start"), 'Run') self.defo.setMinimumSize(self.defo.size().width(), 50) self.defo.clicked.connect(lambda: self.process3.start( 'play -q -V0 "|rec -q -V0 -n -d -R riaa pitch {} "' .format(self.dial.value()) if int(self.dial.value()) != 0 else 'play -q -V0 "|rec -q -V0 --multi-threaded -n -d -R bend {} "' .format(' 3,2500,3 3,-2500,3 ' * 999))) self.qq = QPushButton(QIcon.fromTheme("media-playback-stop"), 'Stop') self.qq.clicked.connect(self.process3.kill) self.die = QPushButton(QIcon.fromTheme("process-stop"), 'Kill') self.die.clicked.connect(lambda: call('killall rec', shell=True)) vboxg5 = QVBoxLayout(self.group5) for each_widget in (self.dial, self.defo, self.qq, self.die): vboxg5.addWidget(each_widget) self.dock5.setWidget(self.group5) # configure some widget settings must_be_checked((self.nepochoose, self.chckbx1, self.chckbx2, self.chckbx3)) must_have_tooltip((self.label2, self.label4, self.label6, self.combo0, self.nepochoose, self.combo1, self.combo2, self.combo3, self.combo4, self.combo5, self.chckbx0, self.chckbx1, self.chckbx2, self.chckbx3, self.rec, self.stop, self.defo, self.qq, self.die, self.kill, self.button0, self.button1, self.button5)) must_autofillbackground((self.clock, self.label2, self.label4, self.label6, self.nepochoose, self.chckbx0, self.chckbx1, self.chckbx2, self.chckbx3)) must_glow((self.rec, self.dial, self.combo1)) self.nepomuk_get('testigo') if self.auto is True: self.go()