def add_slider(self, label, description, minimum, maximum, value, slider_moved_func, parent, tick_interval=1, single_step=1, slider_scale_factor=1, int_values=False): # make layout to hold slider and textbox control_layout = QHBoxLayout() slider_label = label + "_slider" textbox_label = label + "_textbox" # make slider & add to layout slider = QSlider(Qt.Horizontal) slider.setObjectName(label) slider.setFocusPolicy(Qt.StrongFocus) slider.setTickPosition(QSlider.TicksBothSides) slider.setTickInterval(tick_interval) slider.setSingleStep(single_step) slider.setMinimum(minimum) slider.setMaximum(maximum) slider.setValue(value) control_layout.addWidget(slider) # make textbox & add to layout textbox = QLineEdit() textbox.setObjectName(label) textbox.setFixedWidth(40) textbox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) textbox.returnPressed.connect( self.controller.update_crop_params_from_gui) self.update_textbox_from_slider(slider, textbox, slider_scale_factor, int_values) control_layout.addWidget(textbox) # connect slider to set textbox text & update params slider.sliderMoved.connect(lambda: self.update_textbox_from_slider( slider, textbox, slider_scale_factor, int_values)) slider.sliderMoved.connect(slider_moved_func) slider.sliderPressed.connect(lambda: self.slider_pressed(slider)) slider.sliderReleased.connect(lambda: self.slider_released(slider)) # connect textbox to textbox.editingFinished.connect( lambda: self.update_slider_from_textbox(slider, textbox, slider_scale_factor)) textbox.editingFinished.connect(slider_moved_func) # add row to form layout parent.addRow(description, control_layout) # add to list of controls self.crop_param_controls[-1][slider_label] = slider self.crop_param_controls[-1][textbox_label] = textbox
class MainForm(QDialog): def __init__(self, parent=None): # Create our main`layout for picking duration and such super(MainForm, self).__init__(parent) self.setWindowTitle("SelfRestraint") # Create widgets such as buttons and slider self.editButton = QPushButton("Edit Blocklist") self.startButton = QPushButton("Start") self.timeSlider = QSlider(Qt.Horizontal) self.timeLabel = QLabel('Disabled') # Disable start button self.startButton.setEnabled(False) # Mess with the slider self.timeSlider.setTickPosition(QSlider.TicksBelow) self.timeSlider.setTickInterval(1) # Edit button widths self.startButton.setFixedWidth(90) self.editButton.setFixedWidth(120) self.setFixedSize(600,150) # Create another layout to hold bottom contents bottomRow = QHBoxLayout() layout = QVBoxLayout() # Add to the layout layout.addWidget(self.startButton,0,Qt.AlignHCenter) layout.addWidget(self.timeSlider) bottomRow.addWidget(self.timeLabel) bottomRow.addWidget(self.editButton,0,Qt.AlignRight) layout.addLayout(bottomRow) # Set layout self.setLayout(layout) # Link functions to button and slider self.startButton.clicked.connect(backend.startBlock) self.timeSlider.valueChanged.connect(self.change) self.editButton.clicked.connect(self.openList) def openList(self): """docstring for openList""" list.show() # Displays the block time on the label def change(self): """docstring for change""" if self.timeSlider.value() == 0: self.timeLabel.setText("Disabled") self.startButton.setEnabled(False) return self.startButton.setEnabled(True) loc = self.timeSlider.value()* 15 if ((loc-loc%60)/60) == 1: hours = str((loc-loc%60)/60)+" hour, " elif ((loc-loc%60)/60) == 0: hours = "" else: hours = str((loc-loc%60)/60)+" hours, " self.timeLabel.setText(hours+str(loc%60) +" minutes")
class MainForm(QDialog): def __init__(self, parent=None): # Create our main layout for picking duration and such super(MainForm, self).__init__(parent) self.setWindowTitle("SelfRestraint") # Create widgets such as buttons and slider self.editButton = QPushButton("Edit Blocklist") self.startButton = QPushButton("Start") self.timeSlider = QSlider(Qt.Horizontal) self.timeLabel = QLabel('Disabled') # Disable start button self.startButton.setEnabled(False) # Mess with the slider self.timeSlider.setTickPosition(QSlider.TicksBelow) self.timeSlider.setTickInterval(1) # Edit button widths self.startButton.setFixedWidth(90) self.editButton.setFixedWidth(120) self.setFixedSize(600, 150) # Create another layout to hold bottom contents bottomRow = QHBoxLayout() layout = QVBoxLayout() # Add to the layout layout.addWidget(self.startButton, 0, Qt.AlignHCenter) layout.addWidget(self.timeSlider) bottomRow.addWidget(self.timeLabel) bottomRow.addWidget(self.editButton, 0, Qt.AlignRight) layout.addLayout(bottomRow) # Set layout self.setLayout(layout) # Link functions to button and slider self.startButton.clicked.connect(backend.startBlock) self.timeSlider.valueChanged.connect(self.change) self.editButton.clicked.connect(self.openList) def openList(self): """docstring for openList""" list.show() def change(self): """Displays the block time on the label""" if self.timeSlider.value() == 0: self.timeLabel.setText("Disabled") self.startButton.setEnabled(False) return self.startButton.setEnabled(True) loc = self.timeSlider.value() * 15 if ((loc - loc % 60) / 60) == 1: hours = str((loc - loc % 60) / 60) + " hour, " elif ((loc - loc % 60) / 60) == 0: hours = "" hours = "" else: hours = str((loc - loc % 60) / 60) + " hours, " self.timeLabel.setText(hours + str(loc % 60) + " minutes")
def getSlider(self, parent): sld = QSlider(parent) sld.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum) sld.setMinimum(0) sld.setMaximum(99) sld.setPageStep(10) sld.setPageStep(10) sld.setMinimumHeight(50) sld.setTickInterval(25) sld.setTickPosition(QSlider.TicksBothSides) return sld
class QCustomSlider(QWidget): def __init__(self, sliderOrientation=None): super(QCustomSlider, self).__init__() self._slider = QSlider(sliderOrientation) self.setLayout(QVBoxLayout()) self._labelTicksWidget = QWidget(self) self._labelTicksWidget.setLayout(QHBoxLayout()) self._labelTicksWidget.layout().setContentsMargins(0, 0, 0, 0) self.layout().addWidget(self._slider) self.layout().addWidget(self._labelTicksWidget) def setTickLabels(self, listWithLabels): lengthOfList = len(listWithLabels) for index, label in enumerate(listWithLabels): label = QLabel(str(label)) label.setContentsMargins(0, 0, 0, 0) if index > lengthOfList/3: label.setAlignment(QtCore.Qt.AlignCenter) if index > 2*lengthOfList/3: label.setAlignment(QtCore.Qt.AlignRight) self._labelTicksWidget.layout().addWidget(label) def setRange(self, mini, maxi): self._slider.setRange(mini, maxi) def setPageStep(self, value): self._slider.setPageStep(value) def setTickInterval(self, value): self._slider.setTickInterval(value) def setTickPosition(self, position): self._slider.setTickPosition(position) def setValue(self, value): self._slider.setValue(value) def onValueChangedCall(self, function): self._slider.valueChanged.connect(function)
class QtSlider(QtControl, ProxySlider): """ A Qt implementation of an Enaml ProxySlider. """ #: A reference to the widget created by the proxy. widget = Typed(QSlider) #: Cyclic notification guard flags. _guard = Int(0) #-------------------------------------------------------------------------- # Initialization API #-------------------------------------------------------------------------- def create_widget(self): """ Create the underlying QSlider widget. """ self.widget = QSlider(self.parent_widget()) def init_widget(self): """ Initialize the underlying widget. """ super(QtSlider, self).init_widget() d = self.declaration self.set_minimum(d.minimum) self.set_maximum(d.maximum) self.set_value(d.value) self.set_orientation(d.orientation) self.set_page_step(d.page_step) self.set_single_step(d.single_step) self.set_tick_interval(d.tick_interval) self.set_tick_position(d.tick_position) self.set_tracking(d.tracking) self.widget.valueChanged.connect(self.on_value_changed) #-------------------------------------------------------------------------- # Signal Handlers #-------------------------------------------------------------------------- def on_value_changed(self): """ Send the 'value_changed' action to the Enaml widget when the slider value has changed. """ if not self._guard & VALUE_FLAG: self._guard |= VALUE_FLAG try: self.declaration.value = self.widget.value() finally: self._guard &= ~VALUE_FLAG #-------------------------------------------------------------------------- # ProxySlider API #-------------------------------------------------------------------------- def set_maximum(self, maximum): """ Set the maximum value of the underlying widget. """ self.widget.setMaximum(maximum) def set_minimum(self, minimum): """ Set the minimum value of the underlying widget. """ self.widget.setMinimum(minimum) def set_value(self, value): """ Set the value of the underlying widget. """ if not self._guard & VALUE_FLAG: self._guard |= VALUE_FLAG try: self.widget.setValue(value) finally: self._guard &= ~VALUE_FLAG def set_page_step(self, page_step): """ Set the page step of the underlying widget. """ self.widget.setPageStep(page_step) def set_single_step(self, single_step): """ Set the single step of the underlying widget. """ self.widget.setSingleStep(single_step) def set_tick_interval(self, interval): """ Set the tick interval of the underlying widget. """ self.widget.setTickInterval(interval) def set_tick_position(self, tick_position): """ Set the tick position of the underlying widget. """ self.widget.setTickPosition(TICK_POSITION[tick_position]) def set_orientation(self, orientation): """ Set the orientation of the underlying widget. """ self.widget.setOrientation(ORIENTATION[orientation]) def set_tracking(self, tracking): """ Set the tracking of the underlying widget. """ self.widget.setTracking(tracking)
class MainWindow(QWidget): def __init__(self): QWidget.__init__(self, None) # initiate timer self.timer = QTimer() self.timer.timeout.connect(self.reload) # layout id gridbox-like self.box = QGridLayout() self.resize(800, 800) self.setLayout(self.box) # Create two labels and a button self.vertLabel = QLabel("Radolan Data Window", self) self.timeLabel = QLabel("Time", self) self.sliderLabel = QLabel("00:00", self) # File Dialog self.dlg = QFileDialog() self.dlg.setFileMode(QFileDialog.Directory) self.dlg.setOption(QFileDialog.ShowDirsOnly, True) # Canvas self.canvas = None self.cbar = CBarCanvas() # Sliders self.slider = QSlider(Qt.Horizontal) self.slider.setMinimum(1) self.slider.setMaximum(100) self.slider.setTickInterval(1) self.slider.setSingleStep(1) self.slider.valueChanged.connect(self.slider_moved) self.cHighSlider = QSlider(Qt.Horizontal) self.cHighSlider.setMinimum(0) self.cHighSlider.setMaximum(4096) self.cHighSlider.setTickInterval(1) self.cHighSlider.setSingleStep(1) self.cHighSlider.setValue(4096) self.cHighSlider.valueChanged.connect(self.cHighSlider_moved) self.cHighLabel = QLabel("Upper Limit:") self.cHighValue = QLabel("4096") # Load Button self.loadButton = QPushButton("Open Directory") self.loadButton.clicked.connect(self.button_clicked) # Text Output Widget self.attrWidget = TextWidget() self.attrWidget.setVisible(False) self.createButtons() # grid parameters self.c1 = 0 self.c2 = 10 # add Widgets to Layout self.box.addWidget(self.loadButton, 0, self.c1, 1, 11) self.box.addWidget(self.dlg, 1, self.c1, 3, 11) self.box.addWidget(self.attrWidget, 1, self.c1, 3, -1) self.box.addWidget(self.vertLabel, 6, self.c1, 1, 10) self.box.addWidget(self.cbar.native, 5, self.c2, 10, 1) self.box.addWidget(self.timeLabel, 4, self.c1, 1, 10) self.box.addWidget(self.playPauseButton, 4, self.c1 + 1, 1, 1) self.box.addWidget(self.cHighLabel, 4, self.c1 + 4, 1, 1) self.box.addWidget(self.cHighValue, 4, self.c1 + 5, 1, 1) self.box.addWidget(self.cHighSlider, 4, self.c1 + 6, 1, 4) self.box.addWidget(self.sliderLabel, 5, self.c1, 1, 1) self.box.addWidget(self.slider, 5, self.c1 + 1, 1, 9) self.show() # connect Filedialog self.dlg.fileSelected.connect(self.folder_selected) def folder_selected(self, folder): if not self.canvas: self.canvas = Canvas() self.box.addWidget(self.canvas.native, 7, self.c1, -1, 10) inname = "/raa*" self.canvas.flist = sorted(glob.glob(str(folder) + inname)) self.canvas.frames = len(self.canvas.flist) self.slider.setMaximum(self.canvas.frames) self.attrWidget.setVisible(True) self.slider.setValue(1) self.slider_moved(1) def button_clicked(self): self.attrWidget.setVisible(False) self.dlg.setVisible(True) # loop continuously through data def reload(self): if self.slider.value() == self.slider.maximum(): self.slider.setValue(1) else: self.slider.setValue(self.slider.value() + 1) # changing upper limit def cHighSlider_moved(self, position): clow, chigh = self.canvas.image.clim self.canvas.image.clim = (clow, position) self.cHighValue.setText(str(position)) # slide through data def slider_moved(self, position): self.canvas.actualFrame = position - 1 self.canvas.data, self.canvas.attrs = read_RADOLAN_composite(self.canvas.flist[self.canvas.actualFrame], missing=0) # adapt color limits if self.canvas.data.dtype == 'uint8': self.cHighSlider.setMaximum(255) else: self.cHighSlider.setMaximum(4096) # change and update self.canvas.update() self.sliderLabel.setText(self.canvas.attrs['datetime'].strftime("%H:%M")) self.attrWidget.radolanVersion.setText(self.canvas.attrs['radolanversion']) self.attrWidget.dateTime.setText(self.canvas.attrs['datetime'].strftime("%Y-%m-%d")) self.attrWidget.productType.setText(self.canvas.attrs['producttype'].upper()) # start/stop capability def playpause(self): if self.playPauseButton.toolTip() == 'Play': self.playPauseButton.setToolTip("Pause") self.timer.start() self.playPauseButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPause)) else: self.playPauseButton.setToolTip("Play") self.timer.stop() self.playPauseButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) # create play/pause Button def createButtons(self): iconSize = QSize(18, 18) self.playPauseButton = QToolButton() self.playPauseButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay)) self.playPauseButton.setIconSize(iconSize) self.playPauseButton.setToolTip("Play") self.playPauseButton.clicked.connect(self.playpause)
class LogDialog(QDialogWithDpi): """LogDialog for the Freeseer project. It is the dialog window for the log. There is an instance for every FreeseerApp. It has a LogHandler which calls LogDialog's message() method when a new log message is received. The call to message() causes a call to add_entry() which adds the information to a new row in the table. """ def __init__(self, parent=None): super(LogDialog, self).__init__(parent) self.resize(800, 500) self.app = QApplication.instance() icon = QIcon() icon.addPixmap(QPixmap(_fromUtf8(":/freeseer/logo.png")), QIcon.Normal, QIcon.Off) self.setWindowIcon(icon) layout = QVBoxLayout() self.setLayout(layout) self.level = 0 self.handler = LogHandler() self.table_model = QStandardItemModel(0, 5) header_names = ["Date", "Level", "Module", "Message", "LevelNo"] date_column = header_names.index("Date") level_column = header_names.index("Level") module_column = header_names.index("Module") self.level_num_column = header_names.index("LevelNo") self.table_model.setHorizontalHeaderLabels(header_names) self.table_view = QTableView() self.table_view.setModel(self.table_model) self.table_view.horizontalHeader().setStretchLastSection(True) self.table_view.setColumnWidth(date_column, self.set_width_with_dpi(125)) self.table_view.setColumnWidth(level_column, self.set_width_with_dpi(60)) self.table_view.setColumnWidth(module_column, self.set_width_with_dpi(250)) self.table_view.setColumnHidden(self.level_num_column, True) self.table_view.setShowGrid(False) self.table_view.horizontalHeader().setClickable(False) self.table_view.verticalHeader().hide() self.table_view.setStyleSheet("""Qtable_view::item { border-bottom: 1px solid lightgrey; selection-background-color: white; selection-color: black; }""") top_panel = QHBoxLayout() self.log_levels = ["Debug", "Info", "Warning", "Error"] self.level_colors = ["#3E4C85", "#269629", "#B0AB21", "#B32020"] self.levels_label = QLabel("Filter Level: ") self.levels_label.setStyleSheet("QLabel { font-weight: bold }") self.current_level_label = QLabel(self.log_levels[0]) self.current_level_label.setStyleSheet("QLabel {{ color: {} }}".format( self.level_colors[0])) self.clear_button = QPushButton("Clear Log") self.levels_slider = QSlider(Qt.Horizontal) self.levels_slider.setStyleSheet(""" QSlider::handle:horizontal { background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #FFFFFF, stop:1 #E3E3E3); border: 1px solid #707070; width: 10px; margin-top: -4px; margin-bottom: -4px; border-radius: 4px; } QSlider::handle:horizontal:hover { background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #DEDEDE, stop:1 #C9C9C9); border: 1px solid #4F4F4F; border-radius: 4px; } QSlider::sub-page:horizontal { background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #BFBFBF, stop: 1 #9E9E9E); background: qlineargradient(x1: 0, y1: 0.2, x2: 1, y2: 1, stop: 0 #9E9E9E, stop: 1 #858585); border: 1px solid #777; height: 10px; border-radius: 4px; } QSlider::add-page:horizontal { background: #fff; border: 1px solid #707070; height: 10px; border-radius: 4px; }""") self.levels_slider.setRange(0, len(self.log_levels) - 1) self.levels_slider.setTickPosition(QSlider.TicksBelow) self.levels_slider.setTickInterval(1) top_panel.addSpacerItem(self.qspacer_item_with_dpi(10, 0)) top_panel.addWidget(self.levels_label, 3) top_panel.addWidget(self.current_level_label, 2) top_panel.addWidget(self.levels_slider, 8) top_panel.addSpacerItem(self.qspacer_item_with_dpi(25, 0)) top_panel.addWidget(self.clear_button, 10) layout.addLayout(top_panel) layout.addWidget(self.table_view) self.connect(self.clear_button, SIGNAL('clicked()'), functools.partial(self.table_model.setRowCount, 0)) self.connect(self.levels_slider, SIGNAL('valueChanged(int)'), self.slider_set_level) self.setWindowTitle("Log") self.handler.add_listener(self) def __del__(self): self.handler.remove_listener(self) def retranslate(self): self.setWindowTitle(self.app.translate("LogDialog", "Log")) self.clear_button.setText(self.app.translate("LogDialog", "Clear Log")) self.levels_label.setText("{}: ".format( self.app.translate("LogDialog", "Filter Level"))) def message(self, message): """Passes the log fields to add_entry() It is called by LogHandler when a log message is received""" self.add_entry(message["time"], message["level"], message["full_module_name"], message["message"], str(message["levelno"])) def add_entry(self, date, level, module, message, levelno): """Adds the given fields to a new row in the log table It is called by message() when a log message is received""" items = [ QStandardItem(date), QStandardItem(level), QStandardItem(module), QStandardItem(message), QStandardItem(levelno) ] for item in items: item.setEditable(False) self.table_model.appendRow(items) def slider_set_level(self, level): self.current_level_label.setText(self.log_levels[level]) self.current_level_label.setStyleSheet("QLabel {{ color: {} }}".format( self.level_colors[level])) self.set_level(level + 1) def set_level(self, level): """Sets the current level of the LogDialog. Level is based on the selection made in the levels_combo_box. It hides all messages with a lower level.""" self.level = level * 10 for i in range(self.table_model.rowCount()): if int(str(self.table_model.item( i, self.level_num_column).text())) < self.level: self.table_view.setRowHidden(i, True) else: self.table_view.setRowHidden(i, False)
class options(QWidget): def __init__(self, parent): QWidget.__init__(self) self.init(parent) self.initShape() def init(self, parent): self.heditor = parent def initShape(self): self.vbox = QVBoxLayout() self.optab = QTabWidget() self.fill = QWidget() self.createHexOptions() # self.createPageOptions() self.createPixelOptions() self.vbox.addWidget(self.optab) self.createButtons() self.vbox.addWidget(self.fill) self.setLayout(self.vbox) def createPageOptions(self): self.pagegrid = QGridLayout() self.pagegroup = QWidget() pagelabel = QLabel("Page size : ") self.sizeEdit = QFFSpinBox(self) self.sizeEdit.setMaximum(self.heditor.filesize) self.sizeEdit.setValue(self.heditor.pageSize) # psize = QString("%.2d" % self.heditor.pageSize) # self.sizeEdit.insert(psize) headerlabel = QLabel("Header size : ") self.headEdit = QFFSpinBox(self) self.headEdit.setMaximum(self.heditor.filesize) self.headEdit.setValue(self.heditor.pageHead) # phead = QString("%.2d" % self.heditor.pageHead) # self.headEdit.insert(phead) sparelabel = QLabel("Spare size : ") self.spareEdit = QFFSpinBox(self) self.spareEdit.setMaximum(self.heditor.filesize) self.spareEdit.setValue(self.heditor.pageSpare) # pspare = QString("%.2d" % self.heditor.pageSpare) # self.spareEdit.insert(pspare) ppb = QLabel("Pages per block:") self.pagesperblock = QComboBox() self.pagesperblock.addItem("8") self.pagesperblock.addItem("16") self.pagesperblock.addItem("32") self.pagesperblock.addItem("64") self.pagesperblock.addItem("128") self.pagesperblock.addItem("256") self.pagesperblock.addItem("512") self.pagesperblock.setCurrentIndex(2) lview = QLabel("Left indication: ") self.indic = QComboBox() self.indic.addItem("Offset") self.indic.addItem("Block") # self.pagesperlineEdit = QLineEdit() # ppl = QString("%.2d" % self.heditor.pagesPerBlock) # self.pagesperlineEdit.insert(ppl) self.pagegrid.addWidget(pagelabel, 0, 0) self.pagegrid.addWidget(self.sizeEdit, 0, 1) self.pagegrid.addWidget(headerlabel, 1, 0) self.pagegrid.addWidget(self.headEdit, 1, 1) self.pagegrid.addWidget(sparelabel, 2, 0) self.pagegrid.addWidget(self.spareEdit, 2, 1) self.pagegrid.addWidget(ppb, 3, 0) self.pagegrid.addWidget(self.pagesperblock, 3, 1) self.pagegrid.addWidget(lview, 4, 0) self.pagegrid.addWidget(self.indic, 4, 1) self.pagegrid.addWidget(self.fill, 5, 0) self.pagegrid.setRowStretch(5, 1) # self.pagegrid.addWidget(self.fill, 6, 0) # self.pagegrid.addWidget(pagesperline, 6, 0) # self.pagegrid.addWidget(self.pagesperlineEdit, 7, 0) self.pagegroup.setLayout(self.pagegrid) self.vvbox.addWidget(self.pagegroup) # self.optab.insertTab(1, self.pagegroup, "Pages" ) # self.vbox.addWidget(self.pagegroup) def createHexOptions(self): self.vvbox = QVBoxLayout() self.vcontainer = QWidget() self.hexgroup = QWidget() self.hexgrid = QGridLayout() groupebylabel = QLabel("Groupe by:") self.groupeby = QComboBox() self.groupeby.addItem("1") self.groupeby.addItem("2") self.groupeby.addItem("4") offsetlabel = QLabel("Offset as") self.offsetas = QComboBox() self.offsetas.addItem("Hexadecimal") self.offsetas.addItem("Decimal") # self.hexgrid.addWidget(groupebylabel, 0, 0) # self.hexgrid.addWidget(self.groupeby, 1, 0) self.hexgrid.addWidget(offsetlabel, 0, 0) self.hexgrid.addWidget(self.offsetas, 0, 1) # self.hexgrid.addWidget(self.fill, 2, 0) # self.hexgrid.setRowStretch(2, 1) self.hexgroup.setLayout(self.hexgrid) self.vvbox.addWidget(self.hexgroup) self.createPageOptions() self.vcontainer.setLayout(self.vvbox) self.optab.insertTab(0, self.vcontainer, "General") # self.vbox.addWidget(self.hexgroup) #Offset as decimal / hexadecimal def createPixelOptions(self): self.pixgroup = QWidget() self.pixgrid = QGridLayout() formatlabel = QLabel("Format :") self.format = QComboBox() self.format.addItem("RGB") self.format.addItem("Alpha RGB") self.format.addItem("Indexed 8bit") self.format.addItem("Mono") self.connect(self.format, SIGNAL("currentIndexChanged(const QString)"), self.formatChanged) colorlabel = QLabel("Indexed Color :") self.icolor = QComboBox() self.icolor.addItem("Green") self.icolor.addItem("Red") self.icolor.addItem("Blue") self.icolor.addItem("Ascii") self.icolor.addItem("256") self.icolor.setEnabled(False) slidelabel = QLabel("Resolution : ") self.sliderspin = QSpinBox(self) self.sliderspin.setMinimum(64) self.sliderspin.setMaximum(1024) self.sliderspin.setValue(self.heditor.wpixel.view.w) self.connect(self.sliderspin, SIGNAL("valueChanged(int)"), self.slidermoved) self.slider = QSlider(Qt.Horizontal) self.slider.setMinimum(64) self.slider.setMaximum(1024) self.slider.setValue(self.heditor.wpixel.view.w) self.slider.setSingleStep(1) self.zoomlabel = QLabel("Scale factor : 1") self.zoom = QSlider(Qt.Horizontal) self.zoom.setMinimum(1) self.zoom.setMaximum(5) self.zoom.setValue(1) self.zoom.setSingleStep(1) self.zoom.setTickInterval(1) self.zoom.setTickPosition(QSlider.TicksBelow) self.connect(self.slider, SIGNAL("sliderMoved(int)"), self.slidermoved) self.connect(self.zoom, SIGNAL("sliderMoved(int)"), self.scale) self.pixgrid.addWidget(formatlabel, 0, 0) self.pixgrid.addWidget(self.format, 0, 1) self.pixgrid.addWidget(colorlabel, 1, 0) self.pixgrid.addWidget(self.icolor, 1, 1) self.pixgrid.addWidget(slidelabel, 2, 0) self.pixgrid.addWidget(self.sliderspin, 2, 1, Qt.AlignLeft) self.pixgrid.addWidget(self.slider, 3, 0) self.pixgrid.addWidget(self.zoomlabel, 4, 0, Qt.AlignLeft) self.pixgrid.addWidget(self.zoom, 5, 0) self.pixgrid.addWidget(self.fill, 6, 0) self.pixgrid.setRowStretch(6, 1) self.pixgroup.setLayout(self.pixgrid) self.optab.insertTab(1, self.pixgroup, "Pixel") def setSliderLabel(self, value): cvalue = QString() cvalue = "%2.d" % value self.sliderlabel.setText(cvalue) def setZoomLabel(self, value): zvalue = QString("Scale factor : ") zvalue += "%2.d" % value self.zoomlabel.setText(zvalue) def createButtons(self): self.applyB = QPushButton("Apply") self.connect(self.applyB, SIGNAL('clicked()'), self.apply) self.vbox.addWidget(self.applyB) def checkValue(self, value): try: n = int(value) return n except ValueError: return -1 def apply(self): #PAGE CHECK pagesize = self.sizeEdit.value() headsize = self.headEdit.value() sparesize = self.spareEdit.value() pagesperblock = self.checkValue(self.pagesperblock.currentText()) if (pagesize < 0) or (headsize < 0) or (sparesize < 0) or (pagesperblock < 0): print "Wrong values" else: offas = self.offsetas.currentText() if offas == "Decimal": self.heditor.decimalview = True elif offas == "Hexadecimal": self.heditor.decimalview = False #Hexview refresh self.heditor.readOffset(self.heditor.currentOffset) #Pageview refresh if self.indic.currentText() == "Offset": self.heditor.pageOffView = True else: self.heditor.pageOffView = False self.heditor.refreshPageValues(headsize, pagesize, sparesize, pagesperblock) if self.heditor.wpage.scroll: self.heditor.wpage.scroll.refreshValues( self.heditor.pagesPerBlock, self.heditor.pageSize) self.heditor.wpage.view.refreshAllContent() #PageView scrollbar refres #Pixel View refresh format = self.format.currentText() if format == "Indexed 8bit": self.heditor.wpixel.view.format = 0 elif format == "Mono": self.heditor.wpixel.view.format = 1 elif format == "RGB": self.heditor.wpixel.view.format = 2 elif format == "Alpha RGB": self.heditor.wpixel.view.format = 3 if self.heditor.wpixel.scroll: self.heditor.wpixel.scroll.refreshValues() #Color icolor = self.icolor.currentText() if icolor == "Red": self.heditor.wpixel.view.icolor = 0 elif icolor == "Green": self.heditor.wpixel.view.icolor = 1 elif icolor == "Blue": self.heditor.wpixel.view.icolor = 2 elif icolor == "Ascii": self.heditor.wpixel.view.icolor = 3 elif icolor == "256": self.heditor.wpixel.view.icolor = 4 pixoffset = self.heditor.wpixel.view.currentOffset self.heditor.wpixel.view.read_image(pixoffset) def slidermoved(self, value): pixoffset = self.heditor.wpixel.view.currentOffset self.heditor.wpixel.view.w = value self.sliderspin.setValue(value) # self.setSliderLabel(value) self.heditor.wpixel.view.read_image(pixoffset) if self.heditor.wpixel.scroll: self.heditor.wpixel.scroll.refreshValues() # print value def scale(self, value): self.setZoomLabel(value) self.heditor.wpixel.view.scale = value pixoffset = self.heditor.wpixel.view.currentOffset self.heditor.wpixel.view.read_image(pixoffset) def formatChanged(self, format): if format == "Indexed 8bit": self.icolor.setEnabled(True) else: self.icolor.setEnabled(False) def keyPressEvent(self, kEvent): key = kEvent.key() if key == Qt.Key_Return or key == Qt.Key_Enter: self.apply()
class PreviewWindow(QMainWindow): """ QMainWindow subclass used to show frames & tracking. """ def __init__(self, controller): QMainWindow.__init__(self) # set controller self.controller = controller # set title self.setWindowTitle("Preview") # get parameter window position & size param_window_x = self.controller.param_window.x() param_window_y = self.controller.param_window.y() param_window_width = self.controller.param_window.width() # set position & size to be next to the parameter window self.setGeometry(param_window_x + param_window_width, param_window_y, 10, 10) # create main widget self.main_widget = QWidget(self) self.main_widget.setMinimumSize(QSize(500, 500)) # create main layout self.main_layout = QGridLayout(self.main_widget) self.main_layout.setContentsMargins(0, 0, 0, 0) self.main_layout.setSpacing(0) # create label that shows frames self.image_widget = QWidget(self) self.image_layout = QVBoxLayout(self.image_widget) self.image_layout.setContentsMargins(0, 0, 0, 0) self.image_label = PreviewQLabel(self) self.image_label.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) self.image_label.setAlignment(Qt.AlignTop | Qt.AlignLeft) self.image_label.hide() self.image_layout.addWidget(self.image_label) self.main_layout.addWidget(self.image_widget, 0, 0) # self.image_label.setStyleSheet("border: 1px solid rgba(122, 127, 130, 0.5)") self.bottom_widget = QWidget(self) self.bottom_layout = QVBoxLayout(self.bottom_widget) self.bottom_layout.setContentsMargins(8, 0, 8, 8) self.bottom_widget.setMaximumHeight(40) self.main_layout.addWidget(self.bottom_widget, 1, 0) # create label that shows crop instructions self.instructions_label = QLabel("") self.instructions_label.setStyleSheet("font-size: 11px;") self.instructions_label.setAlignment(Qt.AlignCenter) self.bottom_layout.addWidget(self.instructions_label) # create image slider self.image_slider = QSlider(Qt.Horizontal) self.image_slider.setFocusPolicy(Qt.StrongFocus) self.image_slider.setTickPosition(QSlider.NoTicks) self.image_slider.setTickInterval(1) self.image_slider.setSingleStep(1) self.image_slider.setValue(0) self.image_slider.valueChanged.connect(self.controller.show_frame) self.image_slider.hide() self.bottom_layout.addWidget(self.image_slider) self.zoom = 1 self.offset = [0, 0] self.center_y = 0 self.center_x = 0 # initialize variables self.image = None # image to show self.tracking_data = None # list of tracking data self.selecting_crop = False # whether user is selecting a crop self.changing_heading_angle = False # whether the user is changing the heading angle self.body_crop = None self.final_image = None # set main widget self.setCentralWidget(self.main_widget) # set window buttons if pyqt_version == 5: self.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowMinimizeButtonHint | Qt.WindowMaximizeButtonHint | Qt.WindowFullscreenButtonHint) else: self.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowMinimizeButtonHint | Qt.WindowMaximizeButtonHint) self.show() def wheelEvent(self, event): old_zoom = self.zoom self.zoom = max(1, self.zoom + event.pixelDelta().y() / 100) self.zoom = int(self.zoom * 100) / 100.0 self.update_image_label(self.final_image, zooming=True) def start_selecting_crop(self): # start selecting crop self.selecting_crop = True # add instruction text self.instructions_label.setText("Click & drag to select crop area.") def plot_image(self, image, params, crop_params, tracking_results, new_load=False, new_frame=False, show_slider=True, crop_around_body=False): if image is None: self.update_image_label(None) self.image_slider.hide() self.image_label.hide() else: if new_load: self.image_label.show() self.remove_tail_start() if show_slider: if not self.image_slider.isVisible(): self.image_slider.setValue(0) self.image_slider.setMaximum(self.controller.n_frames - 1) self.image_slider.show() else: self.image_slider.hide() max_inititial_size = 500 if image.shape[0] > max_inititial_size: min_height = max_inititial_size min_width = max_inititial_size * image.shape[ 1] / image.shape[0] elif image.shape[1] > max_inititial_size: min_width = max_inititial_size min_height = max_inititial_size * image.shape[ 0] / image.shape[1] else: min_height = image.shape[0] min_width = image.shape[1] self.main_widget.setMinimumSize( QSize(min_width, min_height + self.bottom_widget.height())) # convert to RGB if len(image.shape) == 2: image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB) # update image self.image = image.copy() try: body_crop = params['body_crop'] except: body_crop = None try: tail_start_coords = params['tail_start_coords'] # add tail start point to image cv2.circle(image, (int( round(tail_start_coords[1] - crop_params['offset'][1])), int( round(tail_start_coords[0] - crop_params['offset'][0]))), 1, (180, 180, 50), -1) except (KeyError, TypeError) as error: tail_start_coords = None if tracking_results is not None: body_position = tracking_results['body_position'] heading_angle = tracking_results['heading_angle'] # add tracking to image image = tracking.add_tracking_to_frame(image, tracking_results, cropped=True) if body_crop is not None and body_position is not None: if not crop_around_body: # copy image overlay = image.copy() # draw tail crop overlay cv2.rectangle(overlay, (int(body_position[1] - body_crop[1]), int(body_position[0] - body_crop[0])), (int(body_position[1] + body_crop[1]), int(body_position[0] + body_crop[0])), (242, 242, 65), -1) # overlay with the original image cv2.addWeighted(overlay, 0.2, image, 0.8, 0, image) self.body_crop = None else: self.body_crop = body_crop if crop_around_body: _, image = tracking.crop_frame_around_body( image, body_position, params['body_crop']) self.final_image = image # update image label self.update_image_label( self.final_image, zoom=(not (crop_around_body and body_position is not None)), new_load=new_load) def draw_crop_selection(self, start_crop_coords, end_crop_coords): if self.selecting_crop and self.image is not None: # convert image to rgb if len(self.image.shape) < 3: image = np.repeat(self.image[:, :, np.newaxis], 3, axis=2) else: image = self.image.copy() # copy image overlay = image.copy() # draw crop selection overlay cv2.rectangle(overlay, (start_crop_coords[1], start_crop_coords[0]), (end_crop_coords[1], end_crop_coords[0]), (255, 51, 0), -1) # overlay with the original image cv2.addWeighted(overlay, 0.5, image, 0.5, 0, image) # update image label self.update_image_label(image) def change_offset(self, prev_coords, new_coords): self.offset[0] -= new_coords[0] - prev_coords[0] self.offset[1] -= new_coords[1] - prev_coords[1] self.update_image_label(self.final_image) def draw_tail_start(self, rel_tail_start_coords): if self.controller.params['type'] == "headfixed": # send new tail start coordinates to controller self.controller.update_tail_start_coords(rel_tail_start_coords) # clear instructions text self.instructions_label.setText("") if self.image is not None: image = self.image.copy() cv2.circle(image, (int(round(rel_tail_start_coords[1])), int(round(rel_tail_start_coords[0]))), 1, (180, 180, 50), -1) # update image label self.update_image_label(image) def remove_tail_start(self): self.update_image_label(self.image) def add_angle_overlay(self, angle): image = self.image.copy() image_height = self.image.shape[0] image_width = self.image.shape[1] center_y = image_height / 2 center_x = image_width / 2 cv2.arrowedLine( image, (int(center_x - 0.3 * image_height * np.sin((angle + 90) * np.pi / 180)), int(center_y - 0.3 * image_width * np.cos((angle + 90) * np.pi / 180))), (int(center_x + 0.3 * image_height * np.sin((angle + 90) * np.pi / 180)), int(center_y + 0.3 * image_width * np.cos((angle + 90) * np.pi / 180))), (50, 255, 50), 2) self.update_image_label(image) def remove_angle_overlay(self): self.update_image_label(self.image) def update_image_label(self, image, zoom=True, new_load=False, zooming=False): if image is not None and self.zoom != 1 and zoom: if zooming: self.offset[0] = min( max( 0, self.offset[0] + int( (self.image_label.image.shape[0]) / 2.0) - int(round((image.shape[0] / self.zoom) / 2.0))), image.shape[0] - int(round(image.shape[0] / self.zoom))) self.offset[1] = min( max( 0, self.offset[1] + int( (self.image_label.image.shape[1]) / 2.0) - int(round((image.shape[1] / self.zoom) / 2.0))), image.shape[1] - int(round(image.shape[1] / self.zoom))) else: self.offset[0] = min( max(0, self.offset[0]), image.shape[0] - int(round(image.shape[0] / self.zoom))) self.offset[1] = min( max(0, self.offset[1]), image.shape[1] - int(round(image.shape[1] / self.zoom))) if self.center_y is None: self.center_y = int(round(image.shape[0] / 2.0)) if self.center_x is None: self.center_x = int(round(image.shape[1] / 2.0)) image = image[ self.offset[0]:int(round(image.shape[0] / self.zoom)) + self.offset[0], self.offset[1]:int(round(image.shape[1] / self.zoom)) + self.offset[1], :].copy() if image is not None: if zoom: self.setWindowTitle("Preview - Zoom: {:.1f}x".format( self.zoom)) else: self.setWindowTitle("Preview - Zoom: 1x") else: self.setWindowTitle("Preview") self.image_label.update_pixmap(image, new_load=new_load) def crop_selection(self, start_crop_coord, end_crop_coord): if self.selecting_crop: # stop selecting the crop self.selecting_crop = False # clear instruction text self.instructions_label.setText("") # update crop parameters from the selection self.controller.update_crop_from_selection(start_crop_coord, end_crop_coord) def closeEvent(self, ce): if not self.controller.closing: ce.ignore() else: ce.accept()
class MyMainWindow(QMainWindow): ' Main Window ' 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() def play(self, index): ' play with delay ' if not self.media: self.media = Phonon.MediaObject(self) audioOutput = Phonon.AudioOutput(Phonon.MusicCategory, self) Phonon.createPath(self.media, audioOutput) self.media.setCurrentSource(Phonon.MediaSource( self.model.filePath(index))) self.media.play() def end(self): ' kill it with fire ' print((' INFO: Stoping Processes at {}'.format(str(datetime.now())))) self.process1.terminate() self.process2.terminate() self.feedback.setText(''' <h5>Errors for RECORDER QProcess 1:</h5>{}<hr> <h5>Errors for ENCODER QProcess 2:</h5>{}<hr> <h5>Output for RECORDER QProcess 1:</h5>{}<hr> <h5>Output for ENCODER QProcess 2:</h5>{}<hr> '''.format(self.process1.readAllStandardError(), self.process2.readAllStandardError(), self.process1.readAllStandardOutput(), self.process2.readAllStandardOutput(), )) def killer(self): ' kill -9 ' QMessageBox.information(self.mainwidget, __doc__, ' KILL -9 was sent to the multi-process backend ! ') self.process1.kill() self.process2.kill() def go(self): ' run timeout re-starting timers ' self.timerFirst.start(int(self.slider.value()) * 60 * 1000 + 2000) self.timerSecond.start(int(self.slider.value()) * 60 * 1000 + 2010) self.run() def run(self): ' run forest run ' print((' INFO: Working at {}'.format(str(datetime.now())))) chnl = 1 if self.combo3.currentText() == 'MONO' else 2 print((' INFO: Using {} Channels . . . '.format(chnl))) btrt = int(self.combo4.currentText()) print((' INFO: Using {} Hz per Second . . . '.format(btrt))) threshold = int(self.dial.value()) print((' INFO: Using Thresold of {} . . . '.format(threshold))) print((' INFO: Using Recording time of {}'.format(self.slider.value()))) frmt = str(self.combo0.currentText()).strip() print((' INFO: Using Recording quality of {} ...'.format(frmt))) qlt = str(self.combo1.currentText()).strip() print((' INFO: Using Recording quality of {} ...'.format(qlt))) prio = str(self.combo5.currentText()).strip() print((' INFO: Using CPU Priority of {} ...'.format(prio))) downmix = '--downmix ' if self.chckbx1.isChecked() is True else '' print((' INFO: Using Downmix is {} ...'.format(downmix))) aut = '-a ' + getuser() if self.chckbx3.isChecked() is True else '' print((' INFO: The Author Artist of this sound is: {}'.format(aut))) T = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") tim = '--date {} '.format(T) if self.chckbx2.isChecked() is True else '' print((' INFO: The Date and Time of this sound is: {}'.format(tim))) vol = ' --disable-softvol' if self.chckbx0.isChecked() is True else '' print((' INFO: Software based Volume Control is: {}'.format(vol))) # make base directory try: mkdir(self.base) print((' INFO: Base Directory path created {}'.format(self.base))) except OSError: print((' INFO: Base Directory already exist {}'.format(self.base))) except: print((' ERROR: Can not create Directory ?, {}'.format(self.base))) # make directory tree try: for dr in range(1, 13): mkdir(path.abspath(path.join(self.base, str(dr)))) print((' INFO:Directory created {}/{}'.format(self.base, dr))) except OSError: print((' INFO: Directory already exist {}/1,12'.format(self.base))) except: print((' ERROR: Cant create Directory?, {}/1,12'.format(self.base))) # make new filename flnm = path.abspath(path.join(self.base, str(datetime.now().month), datetime.now().strftime("%Y-%m-%d_%H:%M:%S.ogg"))) self.actual_file = flnm print((' INFO: Recording on the file {}'.format(flnm))) # make custom commands cmd1 = self.cmd1.format(n=prio, f=frmt, c=chnl, b=btrt, v=vol) cmd2 = self.cmd2.format(c=chnl, b=btrt, q=qlt, d=downmix, o=flnm, a=aut, t=tim) print((cmd1, cmd2)) # multiprocess recording loop pipe self.process1 = QProcess(self) self.process2 = QProcess(self) self.process1.setStandardOutputProcess(self.process2) self.process1.start(cmd1) if not self.process1.waitForStarted(): print((" ERROR: RECORDER QProcess 1 Failed: \n {} ".format(cmd1))) self.process2.start(cmd2) if not self.process2.waitForStarted(): print((" ERROR: ENCODER QProcess 2 Failed: \n {} ".format(cmd2))) self.nepomuk_set(flnm, 'testigo', 'testigo', 'AutoTag by Cinta-Testigo') def spectro(self): ' spectrometer ' wid = self.spec.size().width() hei = self.spec.size().height() command = self.cmd3.format(o=self.actual_file, x=wid, y=hei) print(' INFO: Spectrometer is deleting OLD .ogg.png Files on target ') call('rm --verbose --force {}/*/*.ogg.png'.format(self.base), shell=1) print(' INFO: Spectrometer finished Deleting Files, Starting Render ') call(command, shell=True) print((''' INFO: Spectrometer finished Rendering Sound using: {}{} OutPut: {}'''.format(command, linesep, self.actual_file))) self.spec.setIcon(QIcon('{o}.png'.format(o=self.actual_file))) self.spec.setIconSize(QSize(wid, hei)) self.spec.resize(wid, hei) ########################################################################### def paintEvent(self, event): 'Paint semi-transparent background, animated pattern, background text' QWidget.paintEvent(self, event) # make a painter p = QPainter(self) p.setRenderHint(QPainter.TextAntialiasing) p.setRenderHint(QPainter.HighQualityAntialiasing) # fill a rectangle with transparent painting p.fillRect(event.rect(), Qt.transparent) # animated random dots background pattern for i in range(4096): x = randint(9, self.size().width() - 9) y = randint(9, self.size().height() - 9) p.setPen(QPen(QColor(randint(200, 255), randint(200, 255), 255), 1)) p.drawPoint(x, y) # set pen to use white color p.setPen(QPen(QColor(randint(9, 255), randint(9, 255), 255), 1)) # Rotate painter 45 Degree p.rotate(35) # Set painter Font for text p.setFont(QFont('Ubuntu', 300)) # draw the background text, with antialiasing p.drawText(99, 199, "Radio") # Rotate -45 the QPen back ! p.rotate(-35) # set the pen to no pen p.setPen(Qt.NoPen) # Background Color p.setBrush(QColor(0, 0, 0)) # Background Opacity p.setOpacity(0.75) # Background Rounded Borders p.drawRoundedRect(self.rect(), 50, 50) # finalize the painter p.end() def seTitle(self): ' set the title of the main window ' dialog = QDialog(self) textEditInput = QLineEdit(' Type Title Here ') ok = QPushButton(' O K ') ok.clicked.connect(lambda: self.setWindowTitle(textEditInput.text())) ly = QVBoxLayout() [ly.addWidget(wdgt) for wdgt in (QLabel('Title:'), textEditInput, ok)] dialog.setLayout(ly) dialog.exec_() def timedate(self): ' get the time and date ' dialog = QDialog(self) clock = QLCDNumber() clock.setNumDigits(24) timer = QTimer() timer.timeout.connect(lambda: clock.display( datetime.now().strftime("%d-%m-%Y %H:%M:%S %p"))) timer.start(1000) clock.setToolTip(datetime.now().strftime("%c %x")) ok = QPushButton(' O K ') ok.clicked.connect(dialog.close) ly = QVBoxLayout() [ly.addWidget(wdgt) for wdgt in (QCalendarWidget(), clock, ok)] dialog.setLayout(ly) dialog.exec_() def closeEvent(self, event): ' Ask to Quit ' if QMessageBox.question(self, ' Close ', ' Quit ? ', QMessageBox.Yes | QMessageBox.No, QMessageBox.No) == QMessageBox.Yes: event.accept() else: event.ignore() def center(self): ' Center and resize the window ' self.showNormal() self.resize(QDesktopWidget().screenGeometry().width() // 1.25, QDesktopWidget().screenGeometry().height() // 1.25) qr = self.frameGeometry() qr.moveCenter(QDesktopWidget().availableGeometry().center()) self.move(qr.topLeft()) def nepomuk_set(self, file_tag=None, __tag='', _label='', _description=''): ' Quick and Easy Nepomuk Taggify for Files ' print((''' INFO: Semantic Desktop Experience is Tagging Files : {}, {}, {}, {})'''.format(file_tag, __tag, _label, _description))) if Nepomuk.ResourceManager.instance().init() is 0: fle = Nepomuk.Resource(KUrl(QFileInfo(file_tag).absoluteFilePath())) _tag = Nepomuk.Tag(__tag) _tag.setLabel(_label) fle.addTag(_tag) fle.setDescription(_description) print(([str(a.label()) for a in fle.tags()], fle.description())) return ([str(a.label()) for a in fle.tags()], fle.description()) else: print(" ERROR: FAIL: Nepomuk is not running ! ") def nepomuk_get(self, query_to_search): ' Quick and Easy Nepomuk Query for Files ' print((''' INFO: Semantic Desktop Experience is Quering Files : {} '''.format(query_to_search))) results = [] nepo = Nepomuk.Query.QueryServiceClient() nepo.desktopQuery("hasTag:{}".format(query_to_search)) def _query(data): ''' ('filename.ext', 'file description', ['list', 'of', 'tags']) ''' results.append(([str(a.resource().genericLabel()) for a in data][0], [str(a.resource().description()) for a in data][0], [str(a.label()) for a in iter([a.resource().tags() for a in data][0] )])) nepo.newEntries.connect(_query) def _end(): ''' [ ('filename.ext', 'file description', ['list', 'of', 'tags']), ('filename.ext', 'file description', ['list', 'of', 'tags']), ('filename.ext', 'file description', ['list', 'of', 'tags']) ] ''' nepo.newEntries.disconnect print(results) return results nepo.finishedListing.connect(_end)
class Simulator(QMainWindow): def __init__(self, network): super(Simulator, self).__init__() x, y, w, h = 100, 100, 800, 500 self.setGeometry(x, y, w, h) # Network self.network = network # Canvas self.canvas = Canvas() #Controls self.slider = QSlider(Qt.Horizontal, self) self.slider.setMaximum(self.network.count_snapshots()-1) self.slider.setTickPosition(QSlider.TicksBelow) self.slider.setTickInterval(1) self.connect(self.slider, SIGNAL("valueChanged(int)"), self.draw_network) self.prevButton = QPushButton(u"\u25C0") self.connect(self.prevButton, SIGNAL("clicked()"), self.onClickPrev) self.nextButton = QPushButton(u"\u25B6") self.connect(self.nextButton, SIGNAL("clicked()"), self.onClickNext) controls = QHBoxLayout() controls.addWidget(self.prevButton) controls.addWidget(self.slider) controls.addWidget(self.nextButton) #Main Layout mainLayout = QVBoxLayout() mainLayout.addWidget(self.canvas) mainLayout.addLayout(controls) self.widget = QtGui.QWidget() self.widget.setLayout(mainLayout) self.setCentralWidget(self.widget) self.setWindowTitle('DATK Simulator') #Reset Network and draw in starting state self.draw_network(0) def draw_network(self, value): self.network.restore_snapshot(value) self.canvas.draw(self.network) def onClickPrev(self): v = self.slider.value() if v > 0: self.slider.setValue(v-1) def onClickNext(self): v = self.slider.value() if v < self.slider.maximum(): self.slider.setValue(v+1) def closeEvent(self, event): self.network.restore_snapshot(-1) self.deleteLater()
class EditGeometryProperties(QDialog): force = True allow_update = True def __init__(self, data, win_parent=None): """ +------------------+ | Edit Actor Props | +------------------+------+ | Name1 | | Name2 | | Name3 | | Name4 | | | | Active_Name main | | Color box | | Line_Width 2 | | Point_Size 2 | | Bar_Scale 2 | | Opacity 0.5 | | Show/Hide | | | | Apply OK Cancel | +-------------------------+ """ QDialog.__init__(self, win_parent) self.setWindowTitle('Edit Geometry Properties') #default self.win_parent = win_parent self.out_data = data self.keys = sorted(data.keys()) self.keys = data.keys() keys = self.keys nrows = len(keys) self.active_key = 'main'#keys[0] items = keys header_labels = ['Groups'] table_model = Model(items, header_labels, self) view = CustomQTableView(self) #Call your custom QTableView here view.setModel(table_model) if qt_version == 4: view.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch) self.table = view actor_obj = data[self.active_key] name = actor_obj.name line_width = actor_obj.line_width point_size = actor_obj.point_size bar_scale = actor_obj.bar_scale opacity = actor_obj.opacity color = actor_obj.color show = actor_obj.is_visible self.representation = actor_obj.representation # table header = self.table.horizontalHeader() header.setStretchLastSection(True) self._default_is_apply = False self.name = QLabel("Name:") self.name_edit = QLineEdit(str(name)) self.name_edit.setDisabled(True) self.color = QLabel("Color:") self.color_edit = QPushButton() #self.color_edit.setFlat(True) color = self.out_data[self.active_key].color qcolor = QtGui.QColor() qcolor.setRgb(*color) #print('color =%s' % str(color)) palette = QtGui.QPalette(self.color_edit.palette()) # make a copy of the palette #palette.setColor(QtGui.QPalette.Active, QtGui.QPalette.Base, \ #qcolor) palette.setColor(QtGui.QPalette.Background, QtGui.QColor('blue')) # ButtonText self.color_edit.setPalette(palette) self.color_edit.setStyleSheet("QPushButton {" "background-color: rgb(%s, %s, %s);" % tuple(color) + #"border:1px solid rgb(255, 170, 255); " "}") self.use_slider = True self.is_opacity_edit_active = False self.is_opacity_edit_slider_active = False self.is_line_width_edit_active = False self.is_line_width_edit_slider_active = False self.is_point_size_edit_active = False self.is_point_size_edit_slider_active = False self.is_bar_scale_edit_active = False self.is_bar_scale_edit_slider_active = False self.opacity = QLabel("Opacity:") self.opacity_edit = QDoubleSpinBox(self) self.opacity_edit.setRange(0.1, 1.0) self.opacity_edit.setDecimals(1) self.opacity_edit.setSingleStep(0.1) self.opacity_edit.setValue(opacity) if self.use_slider: self.opacity_slider_edit = QSlider(QtCore.Qt.Horizontal) self.opacity_slider_edit.setRange(1, 10) self.opacity_slider_edit.setValue(opacity * 10) self.opacity_slider_edit.setTickInterval(1) self.opacity_slider_edit.setTickPosition(QSlider.TicksBelow) self.line_width = QLabel("Line Width:") self.line_width_edit = QSpinBox(self) self.line_width_edit.setRange(1, 15) self.line_width_edit.setSingleStep(1) self.line_width_edit.setValue(line_width) if self.use_slider: self.line_width_slider_edit = QSlider(QtCore.Qt.Horizontal) self.line_width_slider_edit.setRange(1, 15) self.line_width_slider_edit.setValue(line_width) self.line_width_slider_edit.setTickInterval(1) self.line_width_slider_edit.setTickPosition(QSlider.TicksBelow) if self.representation in ['point', 'surface']: self.line_width.setEnabled(False) self.line_width_edit.setEnabled(False) self.line_width_slider_edit.setEnabled(False) self.point_size = QLabel("Point Size:") self.point_size_edit = QSpinBox(self) self.point_size_edit.setRange(1, 15) self.point_size_edit.setSingleStep(1) self.point_size_edit.setValue(point_size) self.point_size.setVisible(False) self.point_size_edit.setVisible(False) if self.use_slider: self.point_size_slider_edit = QSlider(QtCore.Qt.Horizontal) self.point_size_slider_edit.setRange(1, 15) self.point_size_slider_edit.setValue(point_size) self.point_size_slider_edit.setTickInterval(1) self.point_size_slider_edit.setTickPosition(QSlider.TicksBelow) self.point_size_slider_edit.setVisible(False) if self.representation in ['wire', 'surface']: self.point_size.setEnabled(False) self.point_size_edit.setEnabled(False) if self.use_slider: self.point_size_slider_edit.setEnabled(False) self.bar_scale = QLabel("Bar Scale:") self.bar_scale_edit = QDoubleSpinBox(self) #self.bar_scale_edit.setRange(0.01, 1.0) # was 0.1 #self.bar_scale_edit.setRange(0.05, 5.0) self.bar_scale_edit.setDecimals(1) #self.bar_scale_edit.setSingleStep(bar_scale / 10.) self.bar_scale_edit.setSingleStep(0.1) self.bar_scale_edit.setValue(bar_scale) #if self.use_slider: #self.bar_scale_slider_edit = QSlider(QtCore.Qt.Horizontal) #self.bar_scale_slider_edit.setRange(1, 100) # 1/0.05 = 100/5.0 #self.bar_scale_slider_edit.setValue(opacity * 0.05) #self.bar_scale_slider_edit.setTickInterval(10) #self.bar_scale_slider_edit.setTickPosition(QSlider.TicksBelow) if self.representation != 'bar': self.bar_scale.setEnabled(False) self.bar_scale_edit.setEnabled(False) self.bar_scale.setVisible(False) self.bar_scale_edit.setVisible(False) #self.bar_scale_slider_edit.setVisible(False) #self.bar_scale_slider_edit.setEnabled(False) # show/hide self.checkbox_show = QCheckBox("Show") self.checkbox_hide = QCheckBox("Hide") self.checkbox_show.setChecked(show) self.checkbox_hide.setChecked(not show) if name == 'main': self.color.setEnabled(False) self.color_edit.setEnabled(False) self.point_size.setEnabled(False) self.point_size_edit.setEnabled(False) if self.use_slider: self.point_size_slider_edit.setEnabled(False) # closing # self.apply_button = QPushButton("Apply") #if self._default_is_apply: #self.apply_button.setDisabled(True) # self.ok_button = QPushButton("OK") self.cancel_button = QPushButton("Close") self.create_layout() self.set_connections() def on_update_geometry_properties_window(self, data): """Not Implemented""" return new_keys = sorted(data.keys()) if self.active_key in new_keys: i = new_keys.index(self.active_key) else: i = 0 self.table.update_data(new_keys) self.out_data = data self.update_active_key(i) def update_active_key(self, index): """ Parameters ---------- index : PyQt4.QtCore.QModelIndex the index of the list Internal Parameters ------------------- name : str the name of obj obj : CoordProperties, AltGeometry the storage object for things like line_width, point_size, etc. """ old_obj = self.out_data[self.active_key] old_obj.line_width = self.line_width_edit.value() old_obj.point_size = self.point_size_edit.value() old_obj.bar_scale = self.bar_scale_edit.value() old_obj.opacity = self.opacity_edit.value() old_obj.is_visible = self.checkbox_show.isChecked() if qt_version == 4: name = str(index.data().toString()) else: name = str(index.data()) print('name = %r' % name) #i = self.keys.index(self.active_key) self.active_key = name self.name_edit.setText(name) obj = self.out_data[name] if isinstance(obj, CoordProperties): opacity = 1.0 representation = 'coord' is_visible = obj.is_visible elif isinstance(obj, AltGeometry): line_width = obj.line_width point_size = obj.point_size bar_scale = obj.bar_scale opacity = obj.opacity representation = obj.representation is_visible = obj.is_visible self.color_edit.setStyleSheet("QPushButton {" "background-color: rgb(%s, %s, %s);" % tuple(obj.color) + #"border:1px solid rgb(255, 170, 255); " "}") self.allow_update = False self.force = False self.line_width_edit.setValue(line_width) self.point_size_edit.setValue(point_size) self.bar_scale_edit.setValue(bar_scale) self.force = True self.allow_update = True else: raise NotImplementedError(obj) allowed_representations = [ 'main', 'surface', 'coord', 'toggle', 'wire', 'point', 'bar'] if self.representation != representation: self.representation = representation if representation not in allowed_representations: msg = 'name=%r; representation=%r is invalid\nrepresentations=%r' % ( name, representation, allowed_representations) if self.representation == 'coord': self.color.setVisible(False) self.color_edit.setVisible(False) self.line_width.setVisible(False) self.line_width_edit.setVisible(False) self.point_size.setVisible(False) self.point_size_edit.setVisible(False) self.bar_scale.setVisible(False) self.bar_scale_edit.setVisible(False) self.opacity.setVisible(False) self.opacity_edit.setVisible(False) if self.use_slider: self.opacity_slider_edit.setVisible(False) self.point_size_slider_edit.setVisible(False) self.line_width_slider_edit.setVisible(False) #self.bar_scale_slider_edit.setVisible(False) else: self.color.setVisible(True) self.color_edit.setVisible(True) self.line_width.setVisible(True) self.line_width_edit.setVisible(True) self.point_size.setVisible(True) self.point_size_edit.setVisible(True) self.bar_scale.setVisible(True) #self.bar_scale_edit.setVisible(True) self.opacity.setVisible(True) self.opacity_edit.setVisible(True) if self.use_slider: self.opacity_slider_edit.setVisible(True) self.line_width_slider_edit.setVisible(True) self.point_size_slider_edit.setVisible(True) #self.bar_scale_slider_edit.setVisible(True) if name == 'main': self.color.setEnabled(False) self.color_edit.setEnabled(False) self.point_size.setEnabled(False) self.point_size_edit.setEnabled(False) self.line_width.setEnabled(True) self.line_width_edit.setEnabled(True) self.bar_scale.setEnabled(False) self.bar_scale_edit.setEnabled(False) show_points = False show_line_width = True show_bar_scale = False if self.use_slider: self.line_width_slider_edit.setEnabled(True) #self.bar_scale_slider_edit.setVisible(False) else: self.color.setEnabled(True) self.color_edit.setEnabled(True) show_points = False if self.representation in ['point', 'wire+point']: show_points = True show_line_width = False if self.representation in ['wire', 'wire+point', 'bar']: show_line_width = True if representation == 'bar': show_bar_scale = True else: show_bar_scale = False #self.bar_scale_button.setVisible(show_bar_scale) #self.bar_scale_edit.setSingleStep(bar_scale / 10.) #if self.use_slider: #self.bar_scale_slider_edit.setEnabled(False) self.point_size.setEnabled(show_points) self.point_size_edit.setEnabled(show_points) self.point_size.setVisible(show_points) self.point_size_edit.setVisible(show_points) self.line_width.setEnabled(show_line_width) self.line_width_edit.setEnabled(show_line_width) self.bar_scale.setEnabled(show_bar_scale) self.bar_scale_edit.setEnabled(show_bar_scale) self.bar_scale.setVisible(show_bar_scale) self.bar_scale_edit.setVisible(show_bar_scale) if self.use_slider: self.point_size_slider_edit.setEnabled(show_points) self.point_size_slider_edit.setVisible(show_points) self.line_width_slider_edit.setEnabled(show_line_width) #if self.representation in ['wire', 'surface']: self.opacity_edit.setValue(opacity) #if self.use_slider: #self.opacity_slider_edit.setValue(opacity*10) self.checkbox_show.setChecked(is_visible) self.checkbox_hide.setChecked(not is_visible) passed = self.on_validate() #self.on_apply(force=True) # TODO: was turned on...do I want this??? #self.allow_update = True #def on_name_select(self): #print('on_name_select') #return def create_layout(self): ok_cancel_box = QHBoxLayout() # ok_cancel_box.addWidget(self.apply_button) # ok_cancel_box.addWidget(self.ok_button) ok_cancel_box.addWidget(self.cancel_button) grid = QGridLayout() irow = 0 grid.addWidget(self.name, irow, 0) grid.addWidget(self.name_edit, irow, 1) irow += 1 grid.addWidget(self.color, irow, 0) grid.addWidget(self.color_edit, irow, 1) irow += 1 grid.addWidget(self.opacity, irow, 0) if self.use_slider: grid.addWidget(self.opacity_edit, irow, 2) grid.addWidget(self.opacity_slider_edit, irow, 1) else: grid.addWidget(self.opacity_edit, irow, 1) irow += 1 grid.addWidget(self.line_width, irow, 0) if self.use_slider: grid.addWidget(self.line_width_edit, irow, 2) grid.addWidget(self.line_width_slider_edit, irow, 1) else: grid.addWidget(self.line_width_edit, irow, 1) irow += 1 grid.addWidget(self.point_size, irow, 0) if self.use_slider: grid.addWidget(self.point_size_edit, irow, 2) grid.addWidget(self.point_size_slider_edit, irow, 1) else: grid.addWidget(self.point_size_edit, irow, 1) irow += 1 grid.addWidget(self.bar_scale, irow, 0) if self.use_slider and 0: grid.addWidget(self.bar_scale_edit, irow, 2) grid.addWidget(self.bar_scale_slider_edit, irow, 1) else: grid.addWidget(self.bar_scale_edit, irow, 1) irow += 1 checkboxs = QButtonGroup(self) checkboxs.addButton(self.checkbox_show) checkboxs.addButton(self.checkbox_hide) vbox = QVBoxLayout() vbox.addWidget(self.table) vbox.addLayout(grid) if 0: vbox.addWidget(self.checkbox_show) vbox.addWidget(self.checkbox_hide) else: vbox1 = QVBoxLayout() vbox1.addWidget(self.checkbox_show) vbox1.addWidget(self.checkbox_hide) vbox.addLayout(vbox1) vbox.addStretch() #vbox.addWidget(self.check_apply) vbox.addLayout(ok_cancel_box) self.setLayout(vbox) def set_connections(self): # self.opacity_edit.connect(arg0, QObject, arg1) if qt_version == 4: self.connect(self.opacity_edit, QtCore.SIGNAL('valueChanged(double)'), self.on_opacity) #self.connect(self.opacity_slider_edit, QtCore.SIGNAL('valueChanged(double)'), self.on_opacity) #grid.addWidget(self.opacity_slider_edit, irow, 1) # self.connect(self.line_width, QtCore.SIGNAL('valueChanged(int)'), self.on_line_width) # self.connect(self.point_size, QtCore.SIGNAL('valueChanged(int)'), self.on_point_size) # self.connect(self.line_width, QtCore.SIGNAL('valueChanged(const QString&)'), self.on_line_width) # self.connect(self.point_size, QtCore.SIGNAL('valueChanged(const QString&)'), self.on_point_size) self.connect(self.line_width_edit, QtCore.SIGNAL('valueChanged(int)'), self.on_line_width) self.connect(self.point_size_edit, QtCore.SIGNAL('valueChanged(int)'), self.on_point_size) self.connect(self.bar_scale_edit, QtCore.SIGNAL('valueChanged(double)'), self.on_bar_scale) else: self.opacity_edit.valueChanged.connect(self.on_opacity) self.line_width_edit.valueChanged.connect(self.on_line_width) self.point_size_edit.valueChanged.connect(self.on_point_size) self.bar_scale_edit.valueChanged.connect(self.on_bar_scale) if self.use_slider: self.opacity_slider_edit.valueChanged.connect(self.on_opacity_slider) self.line_width_slider_edit.valueChanged.connect(self.on_line_width_slider) self.point_size_slider_edit.valueChanged.connect(self.on_point_size_slider) #self.bar_scale_slider_edit.valueChanged.connect(self.on_bar_scale_slider) # self.connect(self.opacity_edit, QtCore.SIGNAL('clicked()'), self.on_opacity) # self.connect(self.line_width, QtCore.SIGNAL('clicked()'), self.on_line_width) # self.connect(self.point_size, QtCore.SIGNAL('clicked()'), self.on_point_size) if qt_version == 4: self.connect(self.color_edit, QtCore.SIGNAL('clicked()'), self.on_color) self.connect(self.checkbox_show, QtCore.SIGNAL('clicked()'), self.on_show) self.connect(self.checkbox_hide, QtCore.SIGNAL('clicked()'), self.on_hide) #self.connect(self.check_apply, QtCore.SIGNAL('clicked()'), self.on_check_apply) # self.connect(self.apply_button, QtCore.SIGNAL('clicked()'), self.on_apply) # self.connect(self.ok_button, QtCore.SIGNAL('clicked()'), self.on_ok) self.connect(self.cancel_button, QtCore.SIGNAL('clicked()'), self.on_cancel) self.connect(self, QtCore.SIGNAL('triggered()'), self.closeEvent) else: self.color_edit.clicked.connect(self.on_color) self.checkbox_show.clicked.connect(self.on_show) self.checkbox_hide.clicked.connect(self.on_hide) self.cancel_button.clicked.connect(self.on_cancel) # closeEvent def keyPressEvent(self, event): if event.key() == QtCore.Qt.Key_Escape: self.close() def closeEvent(self, event): self.on_cancel() def on_color(self): name = self.active_key obj = self.out_data[name] rgb_color_ints = obj.color msg = name col = QtGui.QColorDialog.getColor(QtGui.QColor(*rgb_color_ints), self, "Choose a %s color" % msg) if col.isValid(): color = col.getRgbF()[:3] obj.color = color #print('new_color =', color) self.color_edit.setStyleSheet("QPushButton {" "background-color: rgb(%s, %s, %s);" % tuple(obj.color) + #"border:1px solid rgb(255, 170, 255); " "}") self.on_apply(force=self.force) def on_show(self): name = self.active_key is_checked = self.checkbox_show.isChecked() self.out_data[name].is_visible = is_checked self.on_apply(force=self.force) def on_hide(self): name = self.active_key is_checked = self.checkbox_hide.isChecked() self.out_data[name].is_visible = not is_checked self.on_apply(force=self.force) def on_line_width(self): self.is_line_width_edit_active = True name = self.active_key line_width = self.line_width_edit.value() self.out_data[name].line_width = line_width if not self.is_line_width_edit_slider_active: if self.use_slider: self.line_width_slider_edit.setValue(line_width) self.is_line_width_edit_active = False self.on_apply(force=self.force) self.is_line_width_edit_active = False def on_line_width_slider(self): self.is_line_width_edit_slider_active = True name = self.active_key line_width = self.line_width_slider_edit.value() if not self.is_line_width_edit_active: self.line_width_edit.setValue(line_width) self.is_line_width_edit_slider_active = False def on_point_size(self): self.is_point_size_edit_active = True name = self.active_key point_size = self.point_size_edit.value() self.out_data[name].point_size = point_size if not self.is_point_size_edit_slider_active: if self.use_slider: self.point_size_slider_edit.setValue(point_size) self.is_point_size_edit_active = False self.on_apply(force=self.force) self.is_point_size_edit_active = False def on_point_size_slider(self): self.is_point_size_edit_slider_active = True name = self.active_key point_size = self.point_size_slider_edit.value() if not self.is_point_size_edit_active: self.point_size_edit.setValue(point_size) self.is_point_size_edit_slider_active = False def on_bar_scale(self): self.is_bar_scale_edit_active = True name = self.active_key float_bar_scale = self.bar_scale_edit.value() self.out_data[name].bar_scale = float_bar_scale if not self.is_bar_scale_edit_slider_active: int_bar_scale = int(round(float_bar_scale * 20, 0)) #if self.use_slider: #self.bar_scale_slider_edit.setValue(int_bar_scale) self.is_bar_scale_edit_active = False self.on_apply(force=self.force) self.is_bar_scale_edit_active = False def on_bar_scale_slider(self): self.is_bar_scale_edit_slider_active = True name = self.active_key int_bar_scale = self.bar_scale_slider_edit.value() if not self.is_bar_scale_edit_active: float_bar_scale = int_bar_scale / 20. self.bar_scale_edit.setValue(float_bar_scale) self.is_bar_scale_edit_slider_active = False def on_opacity(self): self.is_opacity_edit_active = True name = self.active_key float_opacity = self.opacity_edit.value() self.out_data[name].opacity = float_opacity if not self.is_opacity_edit_slider_active: int_opacity = int(round(float_opacity * 10, 0)) if self.use_slider: self.opacity_slider_edit.setValue(int_opacity) self.is_opacity_edit_active = False self.on_apply(force=self.force) self.is_opacity_edit_active = False def on_opacity_slider(self): self.is_opacity_edit_slider_active = True name = self.active_key int_opacity = self.opacity_slider_edit.value() if not self.is_opacity_edit_active: float_opacity = int_opacity / 10. self.opacity_edit.setValue(float_opacity) self.is_opacity_edit_slider_active = False #def on_axis(self, text): ##print(self.combo_axis.itemText()) #self._axis = str(text) #self.plane.setText('Point on %s? Plane:' % self._axis) #self.point_a.setText('Point on %s Axis:' % self._axis) #self.point_b.setText('Point on %s%s Plane:' % (self._axis, self._plane)) #def on_plane(self, text): #self._plane = str(text) #self.point_b.setText('Point on %s%s Plane:' % (self._axis, self._plane)) def on_check_apply(self): is_checked = self.check_apply.isChecked() self.apply_button.setDisabled(is_checked) def _on_float(self, field): try: eval_float_from_string(field.text()) field.setStyleSheet("QLineEdit{background: white;}") except ValueError: field.setStyleSheet("QLineEdit{background: red;}") #def on_default_name(self): #self.name_edit.setText(str(self._default_name)) #self.name_edit.setStyleSheet("QLineEdit{background: white;}") #def check_float(self, cell): #text = cell.text() #try: #value = eval_float_from_string(text) #cell.setStyleSheet("QLineEdit{background: white;}") #return value, True #except ValueError: #cell.setStyleSheet("QLineEdit{background: red;}") #return None, False #def check_name(self, cell): #text = str(cell.text()).strip() #if len(text): #cell.setStyleSheet("QLineEdit{background: white;}") #return text, True #else: #cell.setStyleSheet("QLineEdit{background: red;}") #return None, False def on_validate(self): self.out_data['clicked_ok'] = True self.out_data['clicked_cancel'] = False old_obj = self.out_data[self.active_key] old_obj.line_width = self.line_width_edit.value() old_obj.point_size = self.point_size_edit.value() old_obj.bar_scale = self.bar_scale_edit.value() old_obj.opacity = self.opacity_edit.value() old_obj.is_visible = self.checkbox_show.isChecked() return True #name_value, flag0 = self.check_name(self.name_edit) #ox_value, flag1 = self.check_float(self.transparency_edit) #if flag0 and flag1: #self.out_data['clicked_ok'] = True #return True #return False def on_apply(self, force=False): passed = self.on_validate() if (passed or force) and self.allow_update: self.win_parent.on_update_geometry_properties(self.out_data) return passed def on_cancel(self): passed = self.on_apply(force=True) if passed: self.close()
class LogDialog(QDialog): """LogDialog for the Freeseer project. It is the dialog window for the log. There is an instance for every FreeseerApp. It has a LogHandler which calls LogDialog's message() method when a new log message is received. The call to message() causes a call to add_entry() which adds the information to a new row in the table. """ def __init__(self, parent=None): super(LogDialog, self).__init__(parent) self.resize(800, 500) self.app = QApplication.instance() icon = QIcon() icon.addPixmap(QPixmap(_fromUtf8(":/freeseer/logo.png")), QIcon.Normal, QIcon.Off) self.setWindowIcon(icon) layout = QVBoxLayout() self.setLayout(layout) self.level = 0 self.handler = LogHandler() self.table_model = QStandardItemModel(0, 5) header_names = ["Date", "Level", "Module", "Message", "LevelNo"] date_column = header_names.index("Date") level_column = header_names.index("Level") module_column = header_names.index("Module") self.level_num_column = header_names.index("LevelNo") self.table_model.setHorizontalHeaderLabels(header_names) self.table_view = QTableView() self.table_view.setModel(self.table_model) self.table_view.horizontalHeader().setStretchLastSection(True) self.table_view.setColumnWidth(date_column, 125) self.table_view.setColumnWidth(level_column, 60) self.table_view.setColumnWidth(module_column, 250) self.table_view.setColumnHidden(self.level_num_column, True) self.table_view.setShowGrid(False) self.table_view.horizontalHeader().setClickable(False) self.table_view.verticalHeader().hide() self.table_view.setStyleSheet("""Qtable_view::item { border-bottom: 1px solid lightgrey; selection-background-color: white; selection-color: black; }""") top_panel = QHBoxLayout() self.log_levels = ["Debug", "Info", "Warning", "Error"] self.level_colors = ["#3E4C85", "#269629", "#B0AB21", "#B32020"] self.levels_label = QLabel("Filter Level: ") self.levels_label.setStyleSheet("QLabel { font-weight: bold }") self.current_level_label = QLabel(self.log_levels[0]) self.current_level_label.setStyleSheet("QLabel {{ color: {} }}".format(self.level_colors[0])) self.clear_button = QPushButton("Clear Log") self.levels_slider = QSlider(Qt.Horizontal) self.levels_slider.setStyleSheet(""" QSlider::handle:horizontal { background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #FFFFFF, stop:1 #E3E3E3); border: 1px solid #707070; width: 10px; margin-top: -4px; margin-bottom: -4px; border-radius: 4px; } QSlider::handle:horizontal:hover { background: qlineargradient(x1:0, y1:0, x2:1, y2:1, stop:0 #DEDEDE, stop:1 #C9C9C9); border: 1px solid #4F4F4F; border-radius: 4px; } QSlider::sub-page:horizontal { background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #BFBFBF, stop: 1 #9E9E9E); background: qlineargradient(x1: 0, y1: 0.2, x2: 1, y2: 1, stop: 0 #9E9E9E, stop: 1 #858585); border: 1px solid #777; height: 10px; border-radius: 4px; } QSlider::add-page:horizontal { background: #fff; border: 1px solid #707070; height: 10px; border-radius: 4px; }""") self.levels_slider.setRange(0, len(self.log_levels) - 1) self.levels_slider.setTickPosition(QSlider.TicksBelow) self.levels_slider.setTickInterval(1) top_panel.addSpacerItem(QSpacerItem(10, 0)) top_panel.addWidget(self.levels_label, 3) top_panel.addWidget(self.current_level_label, 2) top_panel.addWidget(self.levels_slider, 8) top_panel.addSpacerItem(QSpacerItem(25, 0)) top_panel.addWidget(self.clear_button, 10) layout.addLayout(top_panel) layout.addWidget(self.table_view) self.connect(self.clear_button, SIGNAL('clicked()'), functools.partial(self.table_model.setRowCount, 0)) self.connect(self.levels_slider, SIGNAL('valueChanged(int)'), self.slider_set_level) self.setWindowTitle("Log") self.handler.add_listener(self) def __del__(self): self.handler.remove_listener(self) def retranslate(self): self.setWindowTitle(self.app.translate("LogDialog", "Log")) self.clear_button.setText(self.app.translate("LogDialog", "Clear Log")) self.levels_label.setText("{}: ".format(self.app.translate("LogDialog", "Filter Level"))) def message(self, message): """Passes the log fields to add_entry() It is called by LogHandler when a log message is received""" self.add_entry(message["time"], message["level"], message["full_module_name"], message["message"], str(message["levelno"])) def add_entry(self, date, level, module, message, levelno): """Adds the given fields to a new row in the log table It is called by message() when a log message is received""" items = [QStandardItem(date), QStandardItem(level), QStandardItem(module), QStandardItem(message), QStandardItem(levelno)] for item in items: item.setEditable(False) self.table_model.appendRow(items) def slider_set_level(self, level): self.current_level_label.setText(self.log_levels[level]) self.current_level_label.setStyleSheet("QLabel {{ color: {} }}".format(self.level_colors[level])) self.set_level(level + 1) def set_level(self, level): """Sets the current level of the LogDialog. Level is based on the selection made in the levels_combo_box. It hides all messages with a lower level.""" self.level = level * 10 for i in range(self.table_model.rowCount()): if int(str(self.table_model.item(i, self.level_num_column).text())) < self.level: self.table_view.setRowHidden(i, True) else: self.table_view.setRowHidden(i, False)
class MyMainWindow(QMainWindow): ' Main Window ' def __init__(self, parent=None): super(MyMainWindow, self).__init__(parent) self.statusBar().showMessage(__doc__) self.setWindowTitle(__doc__) self.setMinimumSize(250, 280) self.setMaximumSize(300, 300) self.resize(250, 290) self.setWindowIcon(QIcon.fromTheme("face-monkey")) self.setStyleSheet('''QWidget { color: rgba( 0, 255, 255, 255 ); background-color: #323232; font-family: 'Ubuntu Light'; font-size: 14px; } QToolTip { border: 1px solid black; background-color: #ffa02f; background-image: None; padding: 1px; border-radius: 3px; opacity: 100; } QWidget:item:hover { background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffa02f, stop: 1 #ca0619 ); color: #000000; } QWidget:item:selected { background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffa02f, stop: 1 #d7801a ); } QWidget:disabled { color: #404040; background-color: #323232; } QWidget:focus { background-image: None; border: 2px solid QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffa02f, stop: 1 #d7801a ); } QPushButton { background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #565656, stop: 0.1 #525252, stop: 0.5 #4e4e4e, stop: 0.9 #4a4a4a, stop: 1 #464646 ); border-width: 1px; border-color: #1e1e1e; border-style: solid; border-radius: 6; padding: 3px; font-size: 12px; padding-left: 5px; padding-right: 5px; background-image: None; } QPushButton:pressed { background-image: None; background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #2d2d2d, stop: 0.1 #2b2b2b, stop: 0.5 #292929, stop: 0.9 #282828, stop: 1 #252525 ); } QComboBox { background-image: None; selection-background-color: #ffaa00; background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #565656, stop: 0.1 #525252, stop: 0.5 #4e4e4e, stop: 0.9 #4a4a4a, stop: 1 #464646 ); border-style: solid; border: 1px solid #1e1e1e; border-radius: 5; } QComboBox:hover, QPushButton:hover { background-image: url(.bg.png); border: 2px solid QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffa02f, stop: 1 #d7801a ); } QComboBox:on { padding-top: 3px; padding-left: 4px; background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #2d2d2d, stop: 0.1 #2b2b2b, stop: 0.5 #292929, stop: 0.9 #282828, stop: 1 #252525 ); selection-background-color: #ffaa00; background-image: None; } QComboBox QAbstractItemView { background-image: None; border: 2px solid darkgray; selection-background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #ffa02f, stop: 1 #d7801a ); } QComboBox::drop-down { subcontrol-origin: padding; subcontrol-position: top right; width: 15px; border-left-width: 0px; border-left-color: darkgray; border-left-style: solid; border-top-right-radius: 3px; border-bottom-right-radius: 3px; background-image: None; } QComboBox::down-arrow { background-image: None; } QSlider { border-width: 2px; border-color: #1e1e1e; border-style: solid; padding: 3px; font-size: 8px; padding-left: 5px; padding-right: 5px; width: 25px; border-radius: 5px; } QSlider::sub-page:vertical { background: red; border: none; width: 25px; } QSlider::add-page:vertical { background: green; border: none; width: 25px; } QSlider::handle:vertical { background-color: QLinearGradient(spread:pad, x1:0, y1:0, x2:1, y2:0.273, stop:0 rgba(0, 0, 0, 255), stop:1 rgba(150, 255, 255, 255) ); width: 10px; height: 25px; border: 1px solid grey; text-align: center; border-top-left-radius: 2px; border-bottom-left-radius: 2px; border-top-right-radius: 2px; border-bottom-right-radius 2px; margin-left: 2px; margin-right: 2px; } QSlider::handle:vertical:hover { border: 2px solid #ffaa00; margin-left: 2px; margin-right: 2px; } QSlider::sub-page:vertical:disabled { background: #bbb; border-color: #999; } QSlider::add-page:vertical:disabled { background: #eee; border-color: #999; } QSlider::handle:vertical:disabled { background: #eee; border: 1px solid #aaa; border-radius: 4px; } ''') self.label1 = QLabel(self) self.label1.setText('Use Debug') self.label1.setGeometry(QtCore.QRect(25, 25, 125, 25)) self.slider1 = QSlider(self) self.slider1.setGeometry(QtCore.QRect(150, 25, 25, 25)) self.slider1.setTickInterval(1) self.slider1.setCursor(QCursor(QtCore.Qt.OpenHandCursor)) self.slider1.TickPosition(QSlider.TicksBothSides) self.slider1.setRange(0, 1) self.slider1.setValue(1) self.sli1lbl = QLabel(str(self.slider1.value()), self.slider1) self.sli1lbl.move(9, 5) self.sli1lbl.setAutoFillBackground(False) self.slider1.valueChanged.connect( lambda: self.sli1lbl.setText(str(self.slider1.value()))) self.slider1.sliderPressed.connect( lambda: self.slider1.setCursor(QCursor(QtCore.Qt.ClosedHandCursor))) self.slider1.sliderReleased.connect( lambda: self.slider1.setCursor(QCursor(QtCore.Qt.OpenHandCursor))) self.label2 = QLabel(self) self.label2.setText('Make Executable') self.label2.setGeometry(QtCore.QRect(25, 75, 125, 25)) self.slider2 = QSlider(self) self.slider2.setGeometry(QtCore.QRect(150, 75, 25, 25)) self.slider2.setTickInterval(1) self.slider2.setCursor(QCursor(QtCore.Qt.OpenHandCursor)) self.slider2.TickPosition(QSlider.TicksBothSides) self.slider2.setRange(0, 1) self.slider2.setValue(1) self.sli2lbl = QLabel(str(self.slider2.value()), self.slider2) self.sli2lbl.move(9, 5) self.sli2lbl.setAutoFillBackground(False) self.slider2.valueChanged.connect( lambda: self.sli2lbl.setText(str(self.slider2.value()))) self.slider2.sliderPressed.connect( lambda: self.slider2.setCursor(QCursor(QtCore.Qt.ClosedHandCursor))) self.slider2.sliderReleased.connect( lambda: self.slider2.setCursor(QCursor(QtCore.Qt.OpenHandCursor))) self.label3 = QLabel(self) self.label3.setText('Relative Imports') self.label3.setGeometry(QtCore.QRect(25, 125, 125, 25)) self.slider3 = QSlider(self) self.slider3.setGeometry(QtCore.QRect(150, 125, 25, 25)) self.slider3.setTickInterval(1) self.slider3.setCursor(QCursor(QtCore.Qt.OpenHandCursor)) self.slider3.TickPosition(QSlider.TicksBothSides) self.slider3.setRange(0, 1) self.slider3.setValue(0) self.sli3lbl = QLabel(str(self.slider3.value()), self.slider3) self.sli3lbl.move(9, 5) self.sli3lbl.setAutoFillBackground(False) self.slider3.valueChanged.connect( lambda: self.sli3lbl.setText(str(self.slider3.value()))) self.slider3.sliderPressed.connect( lambda: self.slider3.setCursor(QCursor(QtCore.Qt.ClosedHandCursor))) self.slider3.sliderReleased.connect( lambda: self.slider3.setCursor(QCursor(QtCore.Qt.OpenHandCursor))) self.label4 = QLabel(self) self.label4.setText('Indent Spaces') self.label4.setGeometry(QtCore.QRect(25, 175, 125, 25)) self.combo1 = QComboBox(self) self.combo1.setCursor(QCursor(QtCore.Qt.PointingHandCursor)) self.combo1.addItems(['4', '0', '2', '6', '8']) self.combo1.setGeometry(QtCore.QRect(150, 175, 50, 25)) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setGeometry(QtCore.QRect(25, 225, 200, 32)) self.buttonBox.setOrientation(QtCore.Qt.Horizontal) self.buttonBox.setStandardButtons( QDialogButtonBox.Ok | QDialogButtonBox.Cancel | QDialogButtonBox.Close | QDialogButtonBox.Help) self.buttonBox.setCenterButtons(False) self.buttonBox.helpRequested.connect(lambda: QMessageBox.about( self, __doc__, str(__doc__ + ', ' + ',\nversion ' + __version__ + '(' + __license__ + '),\nby ' + __author__ + ', ' + __email__))) self.buttonBox.accepted.connect(self.run) self.buttonBox.rejected.connect(self.close) palette = self.palette() palette.setBrush(QPalette.Base, Qt.transparent) self.setPalette(palette) self.setAttribute(Qt.WA_OpaquePaintEvent, False) def run(self): 'Run the actual conversion.' # Ask the User for the source .ui file as input filein = str(QFileDialog.getOpenFileName( self, __doc__, path.expanduser("~"), 'UI(*.ui)')).strip() # Parse Value of Slider1 as the Debug flag parameter if self.slider1.value() == 0: arg1 = '' else: arg1 = '--debug ' # Parse Value of Slider2 as the Execute flag parameter if self.slider2.value() == 0: arg2 = '' else: arg2 = '--execute ' # Parse Value of Slider3 as the relative imports flag parameter if self.slider3.value() == 0: arg3 = '' else: arg3 = '--from-imports ' # debug #print(arg1, arg2, arg3, str(self.combo1.currentText())) # run the subprocesses subprocess.Popen( 'nice --adjustment=19 pyuic4 ' + arg1 + arg2 + arg3 + '--indent=' + str(self.combo1.currentText()) + ' --output=' + str(filein).lower().replace('.ui', '.py') + ' ' + filein + ' && chmod -v +x ' + str(filein).lower().replace('.ui', '.py'), shell=True) def paintEvent(self, event): ' Paint semi-transparent background ' painter = QPainter(self) painter.fillRect(event.rect(), Qt.transparent) painter.setPen(Qt.NoPen) painter.setBrush(QColor(0, 0, 0)) painter.setOpacity(0.75) painter.drawRoundedRect(self.rect(), 75, 50) painter.end()
class options(QWidget): def __init__(self, parent): QWidget.__init__(self) self.init(parent) self.initShape() def init(self, parent): self.heditor = parent def initShape(self): self.vbox = QVBoxLayout() self.optab = QTabWidget() self.fill = QWidget() self.createHexOptions() # self.createPageOptions() self.createPixelOptions() self.vbox.addWidget(self.optab) self.createButtons() self.vbox.addWidget(self.fill) self.setLayout(self.vbox) def createPageOptions(self): self.pagegrid = QGridLayout() self.pagegroup = QWidget() pagelabel = QLabel("Page size : ") self.sizeEdit = QFFSpinBox(self) self.sizeEdit.setMaximum(self.heditor.filesize) self.sizeEdit.setValue(self.heditor.pageSize) # psize = QString("%.2d" % self.heditor.pageSize) # self.sizeEdit.insert(psize) headerlabel = QLabel("Header size : ") self.headEdit = QFFSpinBox(self) self.headEdit.setMaximum(self.heditor.filesize) self.headEdit.setValue(self.heditor.pageHead) # phead = QString("%.2d" % self.heditor.pageHead) # self.headEdit.insert(phead) sparelabel = QLabel("Spare size : ") self.spareEdit = QFFSpinBox(self) self.spareEdit.setMaximum(self.heditor.filesize) self.spareEdit.setValue(self.heditor.pageSpare) # pspare = QString("%.2d" % self.heditor.pageSpare) # self.spareEdit.insert(pspare) ppb = QLabel("Pages per block:") self.pagesperblock = QComboBox() self.pagesperblock.addItem("8") self.pagesperblock.addItem("16") self.pagesperblock.addItem("32") self.pagesperblock.addItem("64") self.pagesperblock.addItem("128") self.pagesperblock.addItem("256") self.pagesperblock.addItem("512") self.pagesperblock.setCurrentIndex(2) lview = QLabel("Left indication: ") self.indic = QComboBox() self.indic.addItem("Offset") self.indic.addItem("Block") # self.pagesperlineEdit = QLineEdit() # ppl = QString("%.2d" % self.heditor.pagesPerBlock) # self.pagesperlineEdit.insert(ppl) self.pagegrid.addWidget(pagelabel, 0, 0) self.pagegrid.addWidget(self.sizeEdit, 0, 1) self.pagegrid.addWidget(headerlabel, 1, 0) self.pagegrid.addWidget(self.headEdit, 1, 1) self.pagegrid.addWidget(sparelabel, 2, 0) self.pagegrid.addWidget(self.spareEdit, 2, 1) self.pagegrid.addWidget(ppb, 3 ,0) self.pagegrid.addWidget(self.pagesperblock, 3, 1) self.pagegrid.addWidget(lview, 4, 0) self.pagegrid.addWidget(self.indic, 4, 1) self.pagegrid.addWidget(self.fill, 5, 0) self.pagegrid.setRowStretch(5, 1) # self.pagegrid.addWidget(self.fill, 6, 0) # self.pagegrid.addWidget(pagesperline, 6, 0) # self.pagegrid.addWidget(self.pagesperlineEdit, 7, 0) self.pagegroup.setLayout(self.pagegrid) self.vvbox.addWidget(self.pagegroup) # self.optab.insertTab(1, self.pagegroup, "Pages" ) # self.vbox.addWidget(self.pagegroup) def createHexOptions(self): self.vvbox = QVBoxLayout() self.vcontainer = QWidget() self.hexgroup = QWidget() self.hexgrid = QGridLayout() groupebylabel = QLabel("Groupe by:") self.groupeby = QComboBox() self.groupeby.addItem("1") self.groupeby.addItem("2") self.groupeby.addItem("4") offsetlabel = QLabel("Offset as") self.offsetas = QComboBox() self.offsetas.addItem("Hexadecimal") self.offsetas.addItem("Decimal") # self.hexgrid.addWidget(groupebylabel, 0, 0) # self.hexgrid.addWidget(self.groupeby, 1, 0) self.hexgrid.addWidget(offsetlabel, 0, 0) self.hexgrid.addWidget(self.offsetas, 0, 1) # self.hexgrid.addWidget(self.fill, 2, 0) # self.hexgrid.setRowStretch(2, 1) self.hexgroup.setLayout(self.hexgrid) self.vvbox.addWidget(self.hexgroup) self.createPageOptions() self.vcontainer.setLayout(self.vvbox) self.optab.insertTab(0, self.vcontainer, "General") # self.vbox.addWidget(self.hexgroup) #Offset as decimal / hexadecimal def createPixelOptions(self): self.pixgroup = QWidget() self.pixgrid = QGridLayout() formatlabel = QLabel("Format :") self.format = QComboBox() self.format.addItem("RGB") self.format.addItem("Alpha RGB") self.format.addItem("Indexed 8bit") self.format.addItem("Mono") self.connect(self.format, SIGNAL("currentIndexChanged(const QString)"), self.formatChanged) colorlabel = QLabel("Indexed Color :") self.icolor = QComboBox() self.icolor.addItem("Green") self.icolor.addItem("Red") self.icolor.addItem("Blue") self.icolor.addItem("Ascii") self.icolor.addItem("256") self.icolor.setEnabled(False) slidelabel = QLabel("Resolution : ") self.sliderspin = QSpinBox(self) self.sliderspin.setMinimum(64) self.sliderspin.setMaximum(1024) self.sliderspin.setValue(self.heditor.wpixel.view.w) self.connect(self.sliderspin, SIGNAL("valueChanged(int)"), self.slidermoved) self.slider = QSlider(Qt.Horizontal) self.slider.setMinimum(64) self.slider.setMaximum(1024) self.slider.setValue(self.heditor.wpixel.view.w) self.slider.setSingleStep(1) self.zoomlabel = QLabel("Scale factor : 1") self.zoom = QSlider(Qt.Horizontal) self.zoom.setMinimum(1) self.zoom.setMaximum(5) self.zoom.setValue(1) self.zoom.setSingleStep(1) self.zoom.setTickInterval(1) self.zoom.setTickPosition(QSlider.TicksBelow) self.connect(self.slider, SIGNAL("sliderMoved(int)"), self.slidermoved) self.connect(self.zoom, SIGNAL("sliderMoved(int)"), self.scale) self.pixgrid.addWidget(formatlabel, 0, 0) self.pixgrid.addWidget(self.format, 0, 1) self.pixgrid.addWidget(colorlabel, 1, 0) self.pixgrid.addWidget(self.icolor, 1, 1) self.pixgrid.addWidget(slidelabel, 2, 0) self.pixgrid.addWidget(self.sliderspin, 2, 1, Qt.AlignLeft) self.pixgrid.addWidget(self.slider, 3, 0) self.pixgrid.addWidget(self.zoomlabel, 4, 0, Qt.AlignLeft) self.pixgrid.addWidget(self.zoom, 5, 0) self.pixgrid.addWidget(self.fill, 6, 0) self.pixgrid.setRowStretch(6, 1) self.pixgroup.setLayout(self.pixgrid) self.optab.insertTab(1, self.pixgroup, "Pixel") def setSliderLabel(self, value): cvalue = QString() cvalue = "%2.d" % value self.sliderlabel.setText(cvalue) def setZoomLabel(self, value): zvalue = QString("Scale factor : ") zvalue += "%2.d" % value self.zoomlabel.setText(zvalue) def createButtons(self): self.applyB = QPushButton("Apply") self.connect(self.applyB, SIGNAL('clicked()'), self.apply) self.vbox.addWidget(self.applyB) def checkValue(self, value): try: n = int(value) return n except ValueError: return -1 def apply(self): #PAGE CHECK pagesize = self.sizeEdit.value() headsize = self.headEdit.value() sparesize = self.spareEdit.value() pagesperblock = self.checkValue(self.pagesperblock.currentText()) if (pagesize < 0) or (headsize < 0) or (sparesize < 0) or (pagesperblock < 0): print "Wrong values" else: offas = self.offsetas.currentText() if offas == "Decimal": self.heditor.decimalview = True elif offas == "Hexadecimal": self.heditor.decimalview = False #Hexview refresh self.heditor.readOffset(self.heditor.currentOffset) #Pageview refresh if self.indic.currentText() == "Offset": self.heditor.pageOffView = True else: self.heditor.pageOffView = False self.heditor.refreshPageValues(headsize, pagesize, sparesize, pagesperblock) if self.heditor.wpage.scroll: self.heditor.wpage.scroll.refreshValues(self.heditor.pagesPerBlock, self.heditor.pageSize) self.heditor.wpage.view.refreshAllContent() #PageView scrollbar refres #Pixel View refresh format = self.format.currentText() if format == "Indexed 8bit": self.heditor.wpixel.view.format = 0 elif format == "Mono": self.heditor.wpixel.view.format = 1 elif format == "RGB": self.heditor.wpixel.view.format = 2 elif format == "Alpha RGB": self.heditor.wpixel.view.format = 3 if self.heditor.wpixel.scroll: self.heditor.wpixel.scroll.refreshValues() #Color icolor = self.icolor.currentText() if icolor == "Red": self.heditor.wpixel.view.icolor = 0 elif icolor == "Green": self.heditor.wpixel.view.icolor = 1 elif icolor == "Blue": self.heditor.wpixel.view.icolor = 2 elif icolor == "Ascii": self.heditor.wpixel.view.icolor = 3 elif icolor == "256": self.heditor.wpixel.view.icolor = 4 pixoffset = self.heditor.wpixel.view.currentOffset self.heditor.wpixel.view.read_image(pixoffset) def slidermoved(self, value): pixoffset = self.heditor.wpixel.view.currentOffset self.heditor.wpixel.view.w = value self.sliderspin.setValue(value) # self.setSliderLabel(value) self.heditor.wpixel.view.read_image(pixoffset) if self.heditor.wpixel.scroll: self.heditor.wpixel.scroll.refreshValues() # print value def scale(self, value): self.setZoomLabel(value) self.heditor.wpixel.view.scale = value pixoffset = self.heditor.wpixel.view.currentOffset self.heditor.wpixel.view.read_image(pixoffset) def formatChanged(self, format): if format == "Indexed 8bit": self.icolor.setEnabled(True) else: self.icolor.setEnabled(False) def keyPressEvent(self, kEvent): key = kEvent.key() if key == Qt.Key_Return or key == Qt.Key_Enter: self.apply()
class EditGeometryProperties(PyDialog): force = True def __init__(self, data, win_parent=None): """ +------------------+ | Edit Actor Props | +------------------+------+ | Name1 | | Name2 | | Name3 | | Name4 | | | | Active_Name main | | Color box | | Line_Width 2 | | Point_Size 2 | | Bar_Scale 2 | | Opacity 0.5 | | Show/Hide | | | | Apply OK Cancel | +-------------------------+ """ PyDialog.__init__(self, data, win_parent) self.set_font_size(data['font_size']) del self.out_data['font_size'] self.setWindowTitle('Edit Geometry Properties') self.allow_update = True #default #self.win_parent = win_parent #self.out_data = data self.keys = sorted(data.keys()) self.keys = data.keys() keys = self.keys nrows = len(keys) self.active_key = 'main' #keys[0] items = keys header_labels = ['Groups'] table_model = Model(items, header_labels, self) view = CustomQTableView(self) #Call your custom QTableView here view.setModel(table_model) if qt_version == 4: view.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch) self.table = view actor_obj = data[self.active_key] name = actor_obj.name line_width = actor_obj.line_width point_size = actor_obj.point_size bar_scale = actor_obj.bar_scale opacity = actor_obj.opacity color = actor_obj.color show = actor_obj.is_visible self.representation = actor_obj.representation # table header = self.table.horizontalHeader() header.setStretchLastSection(True) self._default_is_apply = False self.name = QLabel("Name:") self.name_edit = QLineEdit(str(name)) self.name_edit.setDisabled(True) self.color = QLabel("Color:") self.color_edit = QPushButton() #self.color_edit.setFlat(True) color = self.out_data[self.active_key].color qcolor = QtGui.QColor() qcolor.setRgb(*color) #print('color =%s' % str(color)) palette = QtGui.QPalette( self.color_edit.palette()) # make a copy of the palette #palette.setColor(QtGui.QPalette.Active, QtGui.QPalette.Base, \ #qcolor) palette.setColor(QtGui.QPalette.Background, QtGui.QColor('blue')) # ButtonText self.color_edit.setPalette(palette) self.color_edit.setStyleSheet("QPushButton {" "background-color: rgb(%s, %s, %s);" % tuple(color) + #"border:1px solid rgb(255, 170, 255); " "}") self.use_slider = True self.is_opacity_edit_active = False self.is_opacity_edit_slider_active = False self.is_line_width_edit_active = False self.is_line_width_edit_slider_active = False self.is_point_size_edit_active = False self.is_point_size_edit_slider_active = False self.is_bar_scale_edit_active = False self.is_bar_scale_edit_slider_active = False self.opacity = QLabel("Opacity:") self.opacity_edit = QDoubleSpinBox(self) self.opacity_edit.setRange(0.1, 1.0) self.opacity_edit.setDecimals(1) self.opacity_edit.setSingleStep(0.1) self.opacity_edit.setValue(opacity) if self.use_slider: self.opacity_slider_edit = QSlider(QtCore.Qt.Horizontal) self.opacity_slider_edit.setRange(1, 10) self.opacity_slider_edit.setValue(opacity * 10) self.opacity_slider_edit.setTickInterval(1) self.opacity_slider_edit.setTickPosition(QSlider.TicksBelow) self.line_width = QLabel("Line Width:") self.line_width_edit = QSpinBox(self) self.line_width_edit.setRange(1, 15) self.line_width_edit.setSingleStep(1) self.line_width_edit.setValue(line_width) if self.use_slider: self.line_width_slider_edit = QSlider(QtCore.Qt.Horizontal) self.line_width_slider_edit.setRange(1, 15) self.line_width_slider_edit.setValue(line_width) self.line_width_slider_edit.setTickInterval(1) self.line_width_slider_edit.setTickPosition(QSlider.TicksBelow) if self.representation in ['point', 'surface']: self.line_width.setEnabled(False) self.line_width_edit.setEnabled(False) self.line_width_slider_edit.setEnabled(False) self.point_size = QLabel("Point Size:") self.point_size_edit = QSpinBox(self) self.point_size_edit.setRange(1, 15) self.point_size_edit.setSingleStep(1) self.point_size_edit.setValue(point_size) self.point_size.setVisible(False) self.point_size_edit.setVisible(False) if self.use_slider: self.point_size_slider_edit = QSlider(QtCore.Qt.Horizontal) self.point_size_slider_edit.setRange(1, 15) self.point_size_slider_edit.setValue(point_size) self.point_size_slider_edit.setTickInterval(1) self.point_size_slider_edit.setTickPosition(QSlider.TicksBelow) self.point_size_slider_edit.setVisible(False) if self.representation in ['wire', 'surface']: self.point_size.setEnabled(False) self.point_size_edit.setEnabled(False) if self.use_slider: self.point_size_slider_edit.setEnabled(False) self.bar_scale = QLabel("Bar Scale:") self.bar_scale_edit = QDoubleSpinBox(self) #self.bar_scale_edit.setRange(0.01, 1.0) # was 0.1 #self.bar_scale_edit.setRange(0.05, 5.0) self.bar_scale_edit.setDecimals(1) #self.bar_scale_edit.setSingleStep(bar_scale / 10.) self.bar_scale_edit.setSingleStep(0.1) self.bar_scale_edit.setValue(bar_scale) #if self.use_slider: #self.bar_scale_slider_edit = QSlider(QtCore.Qt.Horizontal) #self.bar_scale_slider_edit.setRange(1, 100) # 1/0.05 = 100/5.0 #self.bar_scale_slider_edit.setValue(opacity * 0.05) #self.bar_scale_slider_edit.setTickInterval(10) #self.bar_scale_slider_edit.setTickPosition(QSlider.TicksBelow) if self.representation != 'bar': self.bar_scale.setEnabled(False) self.bar_scale_edit.setEnabled(False) self.bar_scale.setVisible(False) self.bar_scale_edit.setVisible(False) #self.bar_scale_slider_edit.setVisible(False) #self.bar_scale_slider_edit.setEnabled(False) # show/hide self.checkbox_show = QCheckBox("Show") self.checkbox_hide = QCheckBox("Hide") self.checkbox_show.setChecked(show) self.checkbox_hide.setChecked(not show) if name == 'main': self.color.setEnabled(False) self.color_edit.setEnabled(False) self.point_size.setEnabled(False) self.point_size_edit.setEnabled(False) if self.use_slider: self.point_size_slider_edit.setEnabled(False) self.cancel_button = QPushButton("Close") self.create_layout() self.set_connections() def on_update_geometry_properties_window(self, data): """Not Implemented""" return #new_keys = sorted(data.keys()) #if self.active_key in new_keys: #i = new_keys.index(self.active_key) #else: #i = 0 #self.table.update_data(new_keys) #self.out_data = data #self.update_active_key(i) def update_active_key(self, index): """ Parameters ---------- index : PyQt4.QtCore.QModelIndex the index of the list Internal Parameters ------------------- name : str the name of obj obj : CoordProperties, AltGeometry the storage object for things like line_width, point_size, etc. """ if qt_version == 4: name = str(index.data().toString()) else: name = str(index.data()) print('name = %r' % name) #i = self.keys.index(self.active_key) self.active_key = name self.name_edit.setText(name) obj = self.out_data[name] if isinstance(obj, CoordProperties): opacity = 1.0 representation = 'coord' is_visible = obj.is_visible elif isinstance(obj, AltGeometry): line_width = obj.line_width point_size = obj.point_size bar_scale = obj.bar_scale opacity = obj.opacity representation = obj.representation is_visible = obj.is_visible self.color_edit.setStyleSheet( "QPushButton {" "background-color: rgb(%s, %s, %s);" % tuple(obj.color) + #"border:1px solid rgb(255, 170, 255); " "}") self.allow_update = False self.force = False self.line_width_edit.setValue(line_width) self.point_size_edit.setValue(point_size) self.bar_scale_edit.setValue(bar_scale) self.force = True self.allow_update = True else: raise NotImplementedError(obj) allowed_representations = [ 'main', 'surface', 'coord', 'toggle', 'wire', 'point', 'bar' ] if self.representation != representation: self.representation = representation if representation not in allowed_representations: msg = 'name=%r; representation=%r is invalid\nrepresentations=%r' % ( name, representation, allowed_representations) if self.representation == 'coord': self.color.setVisible(False) self.color_edit.setVisible(False) self.line_width.setVisible(False) self.line_width_edit.setVisible(False) self.point_size.setVisible(False) self.point_size_edit.setVisible(False) self.bar_scale.setVisible(False) self.bar_scale_edit.setVisible(False) self.opacity.setVisible(False) self.opacity_edit.setVisible(False) if self.use_slider: self.opacity_slider_edit.setVisible(False) self.point_size_slider_edit.setVisible(False) self.line_width_slider_edit.setVisible(False) #self.bar_scale_slider_edit.setVisible(False) else: self.color.setVisible(True) self.color_edit.setVisible(True) self.line_width.setVisible(True) self.line_width_edit.setVisible(True) self.point_size.setVisible(True) self.point_size_edit.setVisible(True) self.bar_scale.setVisible(True) #self.bar_scale_edit.setVisible(True) self.opacity.setVisible(True) self.opacity_edit.setVisible(True) if self.use_slider: self.opacity_slider_edit.setVisible(True) self.line_width_slider_edit.setVisible(True) self.point_size_slider_edit.setVisible(True) #self.bar_scale_slider_edit.setVisible(True) if name == 'main': self.color.setEnabled(False) self.color_edit.setEnabled(False) self.point_size.setEnabled(False) self.point_size_edit.setEnabled(False) self.line_width.setEnabled(True) self.line_width_edit.setEnabled(True) self.bar_scale.setEnabled(False) self.bar_scale_edit.setEnabled(False) show_points = False show_line_width = True show_bar_scale = False if self.use_slider: self.line_width_slider_edit.setEnabled(True) #self.bar_scale_slider_edit.setVisible(False) else: self.color.setEnabled(True) self.color_edit.setEnabled(True) show_points = False if self.representation in ['point', 'wire+point']: show_points = True show_line_width = False if self.representation in ['wire', 'wire+point', 'bar']: show_line_width = True if representation == 'bar': show_bar_scale = True else: show_bar_scale = False #self.bar_scale_button.setVisible(show_bar_scale) #self.bar_scale_edit.setSingleStep(bar_scale / 10.) #if self.use_slider: #self.bar_scale_slider_edit.setEnabled(False) self.point_size.setEnabled(show_points) self.point_size_edit.setEnabled(show_points) self.point_size.setVisible(show_points) self.point_size_edit.setVisible(show_points) self.line_width.setEnabled(show_line_width) self.line_width_edit.setEnabled(show_line_width) self.bar_scale.setEnabled(show_bar_scale) self.bar_scale_edit.setEnabled(show_bar_scale) self.bar_scale.setVisible(show_bar_scale) self.bar_scale_edit.setVisible(show_bar_scale) if self.use_slider: self.point_size_slider_edit.setEnabled(show_points) self.point_size_slider_edit.setVisible(show_points) self.line_width_slider_edit.setEnabled(show_line_width) #if self.representation in ['wire', 'surface']: self.opacity_edit.setValue(opacity) #if self.use_slider: #self.opacity_slider_edit.setValue(opacity*10) self.checkbox_show.setChecked(is_visible) self.checkbox_hide.setChecked(not is_visible) passed = self.on_validate() #self.on_apply(force=True) # TODO: was turned on...do I want this??? #self.allow_update = True #def on_name_select(self): #print('on_name_select') #return def create_layout(self): ok_cancel_box = QHBoxLayout() ok_cancel_box.addWidget(self.cancel_button) grid = QGridLayout() irow = 0 grid.addWidget(self.name, irow, 0) grid.addWidget(self.name_edit, irow, 1) irow += 1 grid.addWidget(self.color, irow, 0) grid.addWidget(self.color_edit, irow, 1) irow += 1 grid.addWidget(self.opacity, irow, 0) if self.use_slider: grid.addWidget(self.opacity_edit, irow, 2) grid.addWidget(self.opacity_slider_edit, irow, 1) else: grid.addWidget(self.opacity_edit, irow, 1) irow += 1 grid.addWidget(self.line_width, irow, 0) if self.use_slider: grid.addWidget(self.line_width_edit, irow, 2) grid.addWidget(self.line_width_slider_edit, irow, 1) else: grid.addWidget(self.line_width_edit, irow, 1) irow += 1 grid.addWidget(self.point_size, irow, 0) if self.use_slider: grid.addWidget(self.point_size_edit, irow, 2) grid.addWidget(self.point_size_slider_edit, irow, 1) else: grid.addWidget(self.point_size_edit, irow, 1) irow += 1 grid.addWidget(self.bar_scale, irow, 0) if self.use_slider and 0: grid.addWidget(self.bar_scale_edit, irow, 2) grid.addWidget(self.bar_scale_slider_edit, irow, 1) else: grid.addWidget(self.bar_scale_edit, irow, 1) irow += 1 checkboxs = QButtonGroup(self) checkboxs.addButton(self.checkbox_show) checkboxs.addButton(self.checkbox_hide) vbox = QVBoxLayout() vbox.addWidget(self.table) vbox.addLayout(grid) if 0: vbox.addWidget(self.checkbox_show) vbox.addWidget(self.checkbox_hide) else: vbox1 = QVBoxLayout() vbox1.addWidget(self.checkbox_show) vbox1.addWidget(self.checkbox_hide) vbox.addLayout(vbox1) vbox.addStretch() #vbox.addWidget(self.check_apply) vbox.addLayout(ok_cancel_box) self.setLayout(vbox) def set_connections(self): self.opacity_edit.valueChanged.connect(self.on_opacity) self.line_width_edit.valueChanged.connect(self.on_line_width) self.point_size_edit.valueChanged.connect(self.on_point_size) self.bar_scale_edit.valueChanged.connect(self.on_bar_scale) if self.use_slider: self.opacity_slider_edit.valueChanged.connect( self.on_opacity_slider) self.line_width_slider_edit.valueChanged.connect( self.on_line_width_slider) self.point_size_slider_edit.valueChanged.connect( self.on_point_size_slider) #self.bar_scale_slider_edit.valueChanged.connect(self.on_bar_scale_slider) # self.connect(self.opacity_edit, QtCore.SIGNAL('clicked()'), self.on_opacity) # self.connect(self.line_width, QtCore.SIGNAL('clicked()'), self.on_line_width) # self.connect(self.point_size, QtCore.SIGNAL('clicked()'), self.on_point_size) if qt_version == 4: self.connect(self, QtCore.SIGNAL('triggered()'), self.closeEvent) self.color_edit.clicked.connect(self.on_color) self.checkbox_show.clicked.connect(self.on_show) self.checkbox_hide.clicked.connect(self.on_hide) self.cancel_button.clicked.connect(self.on_cancel) # closeEvent def keyPressEvent(self, event): if event.key() == QtCore.Qt.Key_Escape: self.close() def closeEvent(self, event): self.on_cancel() def on_color(self): """called when the user clicks on the color box""" name = self.active_key obj = self.out_data[name] rgb_color_ints = obj.color msg = name col = QColorDialog.getColor(QtGui.QColor(*rgb_color_ints), self, "Choose a %s color" % msg) if col.isValid(): color_float = col.getRgbF()[:3] obj.color = color_float color_int = [int(colori * 255) for colori in color_float] self.color_edit.setStyleSheet( "QPushButton {" "background-color: rgb(%s, %s, %s);" % tuple(color_int) + #"border:1px solid rgb(255, 170, 255); " "}") self.on_apply(force=self.force) #print(self.allow_update) def on_show(self): """shows the actor""" name = self.active_key is_checked = self.checkbox_show.isChecked() self.out_data[name].is_visible = is_checked self.on_apply(force=self.force) def on_hide(self): """hides the actor""" name = self.active_key is_checked = self.checkbox_hide.isChecked() self.out_data[name].is_visible = not is_checked self.on_apply(force=self.force) def on_line_width(self): """increases/decreases the wireframe (for solid bodies) or the bar thickness""" self.is_line_width_edit_active = True name = self.active_key line_width = self.line_width_edit.value() self.out_data[name].line_width = line_width if not self.is_line_width_edit_slider_active: if self.use_slider: self.line_width_slider_edit.setValue(line_width) self.is_line_width_edit_active = False self.on_apply(force=self.force) self.is_line_width_edit_active = False def on_line_width_slider(self): """increases/decreases the wireframe (for solid bodies) or the bar thickness""" self.is_line_width_edit_slider_active = True #name = self.active_key line_width = self.line_width_slider_edit.value() if not self.is_line_width_edit_active: self.line_width_edit.setValue(line_width) self.is_line_width_edit_slider_active = False def on_point_size(self): """increases/decreases the point size""" self.is_point_size_edit_active = True name = self.active_key point_size = self.point_size_edit.value() self.out_data[name].point_size = point_size if not self.is_point_size_edit_slider_active: if self.use_slider: self.point_size_slider_edit.setValue(point_size) self.is_point_size_edit_active = False self.on_apply(force=self.force) self.is_point_size_edit_active = False def on_point_size_slider(self): """increases/decreases the point size""" self.is_point_size_edit_slider_active = True name = self.active_key point_size = self.point_size_slider_edit.value() if not self.is_point_size_edit_active: self.point_size_edit.setValue(point_size) self.is_point_size_edit_slider_active = False def on_bar_scale(self): """ Vectors start at some xyz coordinate and can increase in length. Increases/decreases the length scale factor. """ self.is_bar_scale_edit_active = True name = self.active_key float_bar_scale = self.bar_scale_edit.value() self.out_data[name].bar_scale = float_bar_scale if not self.is_bar_scale_edit_slider_active: int_bar_scale = int(round(float_bar_scale * 20, 0)) #if self.use_slider: #self.bar_scale_slider_edit.setValue(int_bar_scale) self.is_bar_scale_edit_active = False self.on_apply(force=self.force) self.is_bar_scale_edit_active = False def on_bar_scale_slider(self): """ Vectors start at some xyz coordinate and can increase in length. Increases/decreases the length scale factor. """ self.is_bar_scale_edit_slider_active = True name = self.active_key int_bar_scale = self.bar_scale_slider_edit.value() if not self.is_bar_scale_edit_active: float_bar_scale = int_bar_scale / 20. self.bar_scale_edit.setValue(float_bar_scale) self.is_bar_scale_edit_slider_active = False def on_opacity(self): """ opacity = 1.0 (solid/opaque) opacity = 0.0 (invisible) """ self.is_opacity_edit_active = True name = self.active_key float_opacity = self.opacity_edit.value() self.out_data[name].opacity = float_opacity if not self.is_opacity_edit_slider_active: int_opacity = int(round(float_opacity * 10, 0)) if self.use_slider: self.opacity_slider_edit.setValue(int_opacity) self.is_opacity_edit_active = False self.on_apply(force=self.force) self.is_opacity_edit_active = False def on_opacity_slider(self): """ opacity = 1.0 (solid/opaque) opacity = 0.0 (invisible) """ self.is_opacity_edit_slider_active = True name = self.active_key int_opacity = self.opacity_slider_edit.value() if not self.is_opacity_edit_active: float_opacity = int_opacity / 10. self.opacity_edit.setValue(float_opacity) self.is_opacity_edit_slider_active = False #def on_axis(self, text): ##print(self.combo_axis.itemText()) #self._axis = str(text) #self.plane.setText('Point on %s? Plane:' % self._axis) #self.point_a.setText('Point on %s Axis:' % self._axis) #self.point_b.setText('Point on %s%s Plane:' % (self._axis, self._plane)) #def on_plane(self, text): #self._plane = str(text) #self.point_b.setText('Point on %s%s Plane:' % (self._axis, self._plane)) #def _on_float(self, field): #try: #eval_float_from_string(field.text()) #field.setStyleSheet("QLineEdit{background: white;}") #except ValueError: #field.setStyleSheet("QLineEdit{background: red;}") #def on_default_name(self): #self.name_edit.setText(str(self._default_name)) #self.name_edit.setStyleSheet("QLineEdit{background: white;}") #def check_float(self, cell): #text = cell.text() #try: #value = eval_float_from_string(text) #cell.setStyleSheet("QLineEdit{background: white;}") #return value, True #except ValueError: #cell.setStyleSheet("QLineEdit{background: red;}") #return None, False #def check_name(self, cell): #text = str(cell.text()).strip() #if len(text): #cell.setStyleSheet("QLineEdit{background: white;}") #return text, True #else: #cell.setStyleSheet("QLineEdit{background: red;}") #return None, False def on_validate(self): self.out_data['clicked_ok'] = True self.out_data['clicked_cancel'] = False old_obj = self.out_data[self.active_key] old_obj.line_width = self.line_width_edit.value() old_obj.point_size = self.point_size_edit.value() old_obj.bar_scale = self.bar_scale_edit.value() old_obj.opacity = self.opacity_edit.value() #old_obj.color = self.color_edit old_obj.is_visible = self.checkbox_show.isChecked() return True #name_value, flag0 = self.check_name(self.name_edit) #ox_value, flag1 = self.check_float(self.transparency_edit) #if flag0 and flag1: #self.out_data['clicked_ok'] = True #return True #return False def on_apply(self, force=False): passed = self.on_validate() #print("passed=%s force=%s allow=%s" % (passed, force, self.allow_update)) if (passed or force) and self.allow_update and hasattr( self.win_parent, 'on_update_geometry_properties'): #print('obj = %s' % self.out_data[self.active_key]) self.win_parent.on_update_geometry_properties(self.out_data, name=self.active_key) return passed def on_cancel(self): passed = self.on_apply(force=True) if passed: self.close()
class OpencvCameraTestWidget(QWidget): available_resolutions = { "160x120": [160, 120], "176x144": [176, 144], "320x240": [320, 240], "352x288": [352, 288], "640x480": [640, 480], "960x720": [960, 720], "1280x960": [1280, 960] } def __init__(self, parent=None, capture=None, widget=None): super(OpencvCameraTestWidget, self).__init__(parent) self.main_layout = QVBoxLayout(self) self.main_layout.setSizeConstraint(QLayout.SetFixedSize) if capture is None: self.capture = cv2.VideoCapture(0) else: self.capture = capture if widget is None: self.camera_widget = QImageWidget() self.main_layout.addWidget(self.camera_widget) self.camera_ret = 0 self.raw_camera_image = None # cv2.namedWindow("image") self.camera_timer = QTimer() self.camera_timer.timeout.connect(self.grab_video) self.camera_timer.start(1000 / 24) self.brightness_layout = QHBoxLayout() self.brightness_label = QLabel("Brightness: ") self.brightness_layout.addWidget(self.brightness_label) self.brightness_value_label = QLabel("") self.brightness_value_label.setMinimumWidth(30) self.brightness_slider = QSlider(Qt.Horizontal) self.brightness_slider.setFocusPolicy(Qt.StrongFocus) self.brightness_slider.setTickPosition(QSlider.TicksBothSides) self.brightness_slider.setMinimum(-10) self.brightness_slider.setMaximum(110) self.brightness_slider.setValue(20) self.brightness_slider.setTickPosition(QSlider.TicksBelow) self.brightness_slider.setTickInterval(10) self.brightness_slider.valueChanged.connect(self.set_brightness) self.brightness_layout.addWidget(self.brightness_slider) self.brightness_layout.addWidget(self.brightness_value_label) self.main_layout.addLayout(self.brightness_layout) self.contrast_layout = QHBoxLayout() self.contrast_label = QLabel("Contrast: ") self.contrast_layout.addWidget(self.contrast_label) self.contrast_value_label = QLabel("") self.contrast_value_label.setMinimumWidth(30) self.contrast_slider = QSlider(Qt.Horizontal) self.contrast_slider.setFocusPolicy(Qt.StrongFocus) self.contrast_slider.setTickPosition(QSlider.TicksBothSides) self.contrast_slider.setMinimum(-10) self.contrast_slider.setMaximum(110) self.contrast_slider.setValue(20) self.contrast_slider.setTickPosition(QSlider.TicksBelow) self.contrast_slider.setTickInterval(10) self.contrast_slider.valueChanged.connect(self.set_contrast) self.contrast_layout.addWidget(self.contrast_slider) self.contrast_layout.addWidget(self.contrast_value_label) self.main_layout.addLayout(self.contrast_layout) self.exposure_layout = QHBoxLayout() self.exposure_label = QLabel("Exposure: ") self.exposure_layout.addWidget(self.exposure_label) self.exposure_value_label = QLabel("") self.exposure_value_label.setMinimumWidth(30) self.exposure_slider = QSlider(Qt.Horizontal) self.exposure_slider.setFocusPolicy(Qt.StrongFocus) self.exposure_slider.setTickPosition(QSlider.TicksBothSides) self.exposure_slider.setMinimum(-10) self.exposure_slider.setMaximum(110) self.exposure_slider.setValue(20) self.exposure_slider.setTickPosition(QSlider.TicksBelow) self.exposure_slider.setTickInterval(10) self.exposure_slider.valueChanged.connect(self.set_exposure) self.exposure_layout.addWidget(self.exposure_slider) self.exposure_layout.addWidget(self.exposure_value_label) self.main_layout.addLayout(self.exposure_layout) self.iso_layout = QHBoxLayout() self.iso_label = QLabel("ISO: ") self.iso_layout.addWidget(self.iso_label) self.iso_value_label = QLabel("") self.iso_value_label.setMinimumWidth(30) self.iso_slider = QSlider(Qt.Horizontal) self.iso_slider.setFocusPolicy(Qt.StrongFocus) self.iso_slider.setTickPosition(QSlider.TicksBothSides) self.iso_slider.setMinimum(-10) self.iso_slider.setMaximum(110) self.iso_slider.setValue(20) self.iso_slider.setTickPosition(QSlider.TicksBelow) self.iso_slider.setTickInterval(10) self.iso_slider.valueChanged.connect(self.set_iso) self.iso_layout.addWidget(self.iso_slider) self.iso_layout.addWidget(self.iso_value_label) self.main_layout.addLayout(self.iso_layout) self.auto_exposure_label = QLabel("AutoExposure: ") self.auto_exposure_checkbox = QCheckBox("AutoExposure: ") self.exposure_layout.addWidget(self.auto_exposure_checkbox) self.auto_exposure_checkbox.stateChanged.connect( self.set_auto_exposure) self.resolutions_combo = QComboBox() self.resolutions_combo.addItems(self.available_resolutions.keys()) self.main_layout.addWidget(self.resolutions_combo) self.resolutions_combo.currentIndexChanged[str].connect( self.set_resolution) def set_brightness(self, value): self.capture.set(cv2.CAP_PROP_BRIGHTNESS, value / 100.0) self.brightness_value_label.setText(str(value / 100.0)) def set_contrast(self, value): self.capture.set(cv2.CAP_PROP_CONTRAST, value / 100.0) self.contrast_value_label.setText(str(value / 100.0)) def set_exposure(self, value): self.capture.set(cv2.CAP_PROP_EXPOSURE, value / 100.0) self.exposure_value_label.setText(str(value / 100.0)) def set_iso(self, value): self.capture.set(cv2.CAP_PROP_ISO_SPEED, value / 100.0) self.exposure_value_label.setText(str(value / 100.0)) def set_auto_exposure(self, value): if value > 0: self.capture.set(cv2.CAP_PROP_AUTO_EXPOSURE, 1) else: self.capture.set(cv2.CAP_PROP_AUTO_EXPOSURE, 0.25) def set_resolution(self, string): if str(string) in self.available_resolutions: height = self.available_resolutions[str(string)][0] width = self.available_resolutions[str(string)][1] self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT, height) self.capture.set(cv2.CAP_PROP_FRAME_WIDTH, width) def grab_video(self): # print "grab video" self.camera_ret, self.raw_camera_image = self.capture.read() if self.camera_ret: self.raw_camera_image = cv2.cvtColor(self.raw_camera_image, cv2.COLOR_BGR2RGB) self.camera_widget.set_opencv_image(self.raw_camera_image)