diff options
author | Josh Morman <jmorman@gnuradio.org> | 2021-11-24 12:39:12 -0500 |
---|---|---|
committer | mormj <34754695+mormj@users.noreply.github.com> | 2021-11-24 14:41:53 -0500 |
commit | 29fd7c725d7e155e668351e0b4532145a6df3212 (patch) | |
tree | 16c0c24543c720ba3f495328356ec0540c368ab5 /gr-qtgui/python | |
parent | aa58bb7d9a37212f46af3cb52e39bfdd6e1bdaf6 (diff) |
qtgui: pep8 formatting
Signed-off-by: Josh Morman <jmorman@gnuradio.org>
Diffstat (limited to 'gr-qtgui/python')
-rw-r--r-- | gr-qtgui/python/qtgui/__init__.py | 11 | ||||
-rw-r--r-- | gr-qtgui/python/qtgui/auto_correlator_sink.py | 57 | ||||
-rw-r--r-- | gr-qtgui/python/qtgui/azelplot.py | 32 | ||||
-rw-r--r-- | gr-qtgui/python/qtgui/compass.py | 45 | ||||
-rw-r--r-- | gr-qtgui/python/qtgui/dialcontrol.py | 10 | ||||
-rw-r--r-- | gr-qtgui/python/qtgui/dialgauge.py | 38 | ||||
-rw-r--r-- | gr-qtgui/python/qtgui/digitalnumbercontrol.py | 59 | ||||
-rw-r--r-- | gr-qtgui/python/qtgui/distanceradar.py | 22 | ||||
-rw-r--r-- | gr-qtgui/python/qtgui/graphicitem.py | 39 | ||||
-rw-r--r-- | gr-qtgui/python/qtgui/graphicoverlay.py | 59 | ||||
-rw-r--r-- | gr-qtgui/python/qtgui/ledindicator.py | 31 | ||||
-rw-r--r-- | gr-qtgui/python/qtgui/levelgauge.py | 15 | ||||
-rw-r--r-- | gr-qtgui/python/qtgui/msgcheckbox.py | 38 | ||||
-rw-r--r-- | gr-qtgui/python/qtgui/msgpushbutton.py | 13 | ||||
-rwxr-xr-x | gr-qtgui/python/qtgui/range.py.cmakein | 81 | ||||
-rw-r--r-- | gr-qtgui/python/qtgui/togglebutton.py | 37 | ||||
-rw-r--r-- | gr-qtgui/python/qtgui/toggleswitch.py | 66 | ||||
-rw-r--r-- | gr-qtgui/python/qtgui/util.py.cmakein | 6 |
18 files changed, 385 insertions, 274 deletions
diff --git a/gr-qtgui/python/qtgui/__init__.py b/gr-qtgui/python/qtgui/__init__.py index 0522fed827..6edb8253f0 100644 --- a/gr-qtgui/python/qtgui/__init__.py +++ b/gr-qtgui/python/qtgui/__init__.py @@ -23,12 +23,12 @@ except ImportError: from .qtgui_python import * try: - import matplotlib.pyplot as plt - from .distanceradar import DistanceRadar - from .azelplot import AzElPlot + import matplotlib.pyplot as plt + from .distanceradar import DistanceRadar + from .azelplot import AzElPlot except ImportError: - from gnuradio import gr - gr.log.warn("Matplotlib is a required dependency to use DistanceRadar and AzElPlot." + from gnuradio import gr + gr.log.warn("Matplotlib is a required dependency to use DistanceRadar and AzElPlot." " Please install matplotlib to use these blocks (https://matplotlib.org/)") from .range import Range, RangeWidget @@ -49,4 +49,3 @@ from .graphicoverlay import GrGraphicOverlay from .auto_correlator_sink import AutoCorrelatorSink from .auto_correlator_sink import AutoCorrelator from .auto_correlator_sink import Normalize - diff --git a/gr-qtgui/python/qtgui/auto_correlator_sink.py b/gr-qtgui/python/qtgui/auto_correlator_sink.py index ed69395d1a..d1aa7728ad 100644 --- a/gr-qtgui/python/qtgui/auto_correlator_sink.py +++ b/gr-qtgui/python/qtgui/auto_correlator_sink.py @@ -19,12 +19,13 @@ from gnuradio import blocks, fft, filter from PyQt5 import QtGui from PyQt5.QtWidgets import QWidget + class Normalize(gr.hier_block2): def __init__(self, vecsize=1024): gr.hier_block2.__init__( self, "Normalize", - gr.io_signature(1, 1, gr.sizeof_float*vecsize), - gr.io_signature(1, 1, gr.sizeof_float*vecsize), + gr.io_signature(1, 1, gr.sizeof_float * vecsize), + gr.io_signature(1, 1, gr.sizeof_float * vecsize), ) ################################################## @@ -35,7 +36,8 @@ class Normalize(gr.hier_block2): ################################################## # Blocks ################################################## - self.blocks_stream_to_vector_0 = blocks.stream_to_vector(gr.sizeof_float, vecsize) + self.blocks_stream_to_vector_0 = blocks.stream_to_vector( + gr.sizeof_float, vecsize) self.blocks_repeat_0 = blocks.repeat(gr.sizeof_float, vecsize) self.blocks_max_xx_0 = blocks.max_ff(vecsize) self.blocks_divide_xx_0 = blocks.divide_ff(vecsize) @@ -44,19 +46,21 @@ class Normalize(gr.hier_block2): # Connections ################################################## self.connect((self.blocks_divide_xx_0, 0), (self, 0)) - self.connect((self.blocks_stream_to_vector_0, 0), (self.blocks_divide_xx_0, 1)) + self.connect((self.blocks_stream_to_vector_0, 0), + (self.blocks_divide_xx_0, 1)) self.connect((self, 0), (self.blocks_max_xx_0, 0)) - self.connect((self.blocks_repeat_0, 0), (self.blocks_stream_to_vector_0, 0)) + self.connect((self.blocks_repeat_0, 0), + (self.blocks_stream_to_vector_0, 0)) self.connect((self.blocks_max_xx_0, 0), (self.blocks_repeat_0, 0)) self.connect((self, 0), (self.blocks_divide_xx_0, 0)) - def get_vecsize(self): return self.vecsize def set_vecsize(self, vecsize): self.vecsize = vecsize + class AutoCorrelator(gr.hier_block2): """ This block uses the Wiener Khinchin theorem that the FFT of a signal's @@ -64,19 +68,24 @@ class AutoCorrelator(gr.hier_block2): FAC Size controls the FFT size and therefore the length of time (samp_rate/fac_size) the auto-correlation runs over. """ + def __init__(self, sample_rate, fac_size, fac_decimation, use_db): - gr.hier_block2.__init__(self,"AutoCorrelator", - gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input sig - gr.io_signature(1, 1, gr.sizeof_float*fac_size)) # Output sig + gr.hier_block2.__init__(self, "AutoCorrelator", + gr.io_signature( + 1, 1, gr.sizeof_gr_complex), # Input sig + gr.io_signature(1, 1, gr.sizeof_float * fac_size)) # Output sig self.fac_size = fac_size self.fac_decimation = fac_decimation self.sample_rate = sample_rate - streamToVec = blocks.stream_to_vector(gr.sizeof_gr_complex, self.fac_size) + streamToVec = blocks.stream_to_vector( + gr.sizeof_gr_complex, self.fac_size) # Make sure N is at least 1 - decimation = int(self.sample_rate/self.fac_size/self.fac_decimation) - self.one_in_n = blocks.keep_one_in_n(gr.sizeof_gr_complex * self.fac_size, max(1, decimation)) + decimation = int(self.sample_rate / + self.fac_size / self.fac_decimation) + self.one_in_n = blocks.keep_one_in_n( + gr.sizeof_gr_complex * self.fac_size, max(1, decimation)) # FFT Note: No windowing. fac = fft.fft_vcc(self.fac_size, True, ()) @@ -84,7 +93,7 @@ class AutoCorrelator(gr.hier_block2): complex2Mag = blocks.complex_to_mag(self.fac_size) self.avg = filter.single_pole_iir_filter_ff(1.0, self.fac_size) - fac_fac = fft.fft_vfc(self.fac_size, True, ()) + fac_fac = fft.fft_vfc(self.fac_size, True, ()) fac_c2mag = blocks.complex_to_mag(fac_size) # There's a note in Baz's block about needing to add 3 dB to each bin but the DC bin, however it was never implemented @@ -93,28 +102,35 @@ class AutoCorrelator(gr.hier_block2): log = blocks.nlog10_ff(n, self.fac_size, k) if use_db: - self.connect(self, streamToVec, self.one_in_n, fac, complex2Mag, fac_fac, fac_c2mag, self.avg, log, self) + self.connect(self, streamToVec, self.one_in_n, fac, + complex2Mag, fac_fac, fac_c2mag, self.avg, log, self) else: - self.connect(self, streamToVec, self.one_in_n, fac, complex2Mag, fac_fac, fac_c2mag, self.avg, self) + self.connect(self, streamToVec, self.one_in_n, fac, + complex2Mag, fac_fac, fac_c2mag, self.avg, self) + class AutoCorrelatorSink(gr.hier_block2): """ docstring for block AutoCorrelatorSink """ + def __init__(self, sample_rate, fac_size, fac_decimation, title, autoScale, grid, yMin, yMax, use_db): gr.hier_block2.__init__(self, - "AutoCorrelatorSink", - gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature - gr.io_signature(0, 0, 0)) # Output signature + "AutoCorrelatorSink", + # Input signature + gr.io_signature(1, 1, gr.sizeof_gr_complex), + gr.io_signature(0, 0, 0)) # Output signature self.fac_size = fac_size self.fac_decimation = fac_decimation self.sample_rate = sample_rate - autoCorr = AutoCorrelator(sample_rate, fac_size, fac_decimation, use_db) + autoCorr = AutoCorrelator( + sample_rate, fac_size, fac_decimation, use_db) vecToStream = blocks.vector_to_stream(gr.sizeof_float, self.fac_size) - self.timeSink = qtgui.time_sink_f(self.fac_size//2, sample_rate, title, 1, None) + self.timeSink = qtgui.time_sink_f( + self.fac_size // 2, sample_rate, title, 1, None) self.timeSink.enable_grid(grid) self.timeSink.set_y_axis(yMin, yMax) self.timeSink.enable_autoscale(autoScale) @@ -127,6 +143,5 @@ class AutoCorrelatorSink(gr.hier_block2): norm = Normalize(self.fac_size) self.connect(self, autoCorr, norm, vecToStream, self.timeSink) - def getWidget(self): return sip.wrapinstance(self.timeSink.qwidget(), QWidget) diff --git a/gr-qtgui/python/qtgui/azelplot.py b/gr-qtgui/python/qtgui/azelplot.py index d23d39234d..e091f7cc07 100644 --- a/gr-qtgui/python/qtgui/azelplot.py +++ b/gr-qtgui/python/qtgui/azelplot.py @@ -18,6 +18,7 @@ import math from gnuradio import gr import pmt + class AzElPlot(gr.sync_block, FigureCanvas): """ This block creates a polar plot with azimuth represented as the angle @@ -27,10 +28,11 @@ class AzElPlot(gr.sync_block, FigureCanvas): elevation < 0 is provided, the marker will turn to an open circle on the perimeter at the specified azimuth angle. """ + def __init__(self, lbl, backgroundColor, dotColor, Parent=None, width=4, height=4, dpi=90): - gr.sync_block.__init__(self, name = "MsgPushButton", in_sig = None, - out_sig = None) + gr.sync_block.__init__(self, name="MsgPushButton", in_sig=None, + out_sig=None) self.lbl = lbl @@ -46,15 +48,16 @@ class AzElPlot(gr.sync_block, FigureCanvas): self.fig = Figure(figsize=(width, height), dpi=dpi) self.fig.patch.set_facecolor(self.backgroundColor) - self.axes = self.fig.add_subplot(111, polar=True, facecolor=self.backgroundColor) + self.axes = self.fig.add_subplot( + 111, polar=True, facecolor=self.backgroundColor) # Create an "invisible" line at 90 to set the max for the plot - self.axes.plot(np.linspace(0, 2*np.pi, 90), np.ones(90)*90, color=self.scaleColor, + self.axes.plot(np.linspace(0, 2 * np.pi, 90), np.ones(90) * 90, color=self.scaleColor, linestyle='') # Plot line: Initialize out to 90 and blank radius = 90 - self.blackline = self.axes.plot(np.linspace(0, 2*np.pi, 90), np.ones(90)*radius, + self.blackline = self.axes.plot(np.linspace(0, 2 * np.pi, 90), np.ones(90) * radius, color=self.scaleColor, linestyle='-') self.reddot = None @@ -71,7 +74,8 @@ class AzElPlot(gr.sync_block, FigureCanvas): FigureCanvas.__init__(self, self.fig) self.setParent(Parent) - self.title = self.fig.suptitle(self.lbl, fontsize=8, fontweight='bold', color='black') + self.title = self.fig.suptitle( + self.lbl, fontsize=8, fontweight='bold', color='black') FigureCanvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, @@ -88,17 +92,20 @@ class AzElPlot(gr.sync_block, FigureCanvas): if new_val is not None: if type(new_val) == dict: if 'az' in new_val and 'el' in new_val: - self.updateData(float(new_val['az']), float(new_val['el'])) + self.updateData( + float(new_val['az']), float(new_val['el'])) else: - gr.log.error("az and el keys were not found in the dictionary.") + gr.log.error( + "az and el keys were not found in the dictionary.") else: gr.log.error("Value received was not a dictionary. Expecting a dictionary " "in the car message component with az and el keys.") else: gr.log.error("The CAR section of the inbound message was None. " - "This part should contain the dictionary with 'az' and 'el' float keys.") + "This part should contain the dictionary with 'az' and 'el' float keys.") except Exception as e: - gr.log.error("[AzElPlot] Error with message conversion: %s" % str(e)) + gr.log.error( + "[AzElPlot] Error with message conversion: %s" % str(e)) if new_val is not None: gr.log.error(str(new_val)) @@ -116,13 +123,12 @@ class AzElPlot(gr.sync_block, FigureCanvas): convertedElevation = 90.0 - elevation # Note: +azimuth for the plot is measured counter-clockwise, so need to reverse it. - self.reddot = self.axes.plot(-azimuth * math.pi/180.0, convertedElevation, self.dotColor, + self.reddot = self.axes.plot(-azimuth * math.pi / 180.0, convertedElevation, self.dotColor, markersize=8) else: # It's below the horizon. Show an open circle at the perimeter elevation = 0.0 - self.reddot = self.axes.plot(-azimuth * math.pi/180.0, 89.0, self.dotColor, + self.reddot = self.axes.plot(-azimuth * math.pi / 180.0, 89.0, self.dotColor, markerfacecolor="None", markersize=16, fillstyle=None) self.draw() - diff --git a/gr-qtgui/python/qtgui/compass.py b/gr-qtgui/python/qtgui/compass.py index 2c8a766f14..f1cdabf7d9 100644 --- a/gr-qtgui/python/qtgui/compass.py +++ b/gr-qtgui/python/qtgui/compass.py @@ -27,13 +27,14 @@ NeedleFull = 1 NeedleIndicator = 0 NeedleMirrored = 2 + class LabeledCompass(QFrame): def __init__(self, lbl, min_size, update_time, setDebug=False, needleType=NeedleFull, position=1, backgroundColor='default'): # Positions: 1 = above, 2=below, 3=left, 4=right QFrame.__init__(self) self.numberControl = Compass(min_size, update_time, setDebug, - needleType, position, backgroundColor) + needleType, position, backgroundColor) if position < 3: layout = QVBoxLayout() @@ -62,17 +63,20 @@ class LabeledCompass(QFrame): self.setLayout(layout) if lbl: - self.setMinimumSize(min_size+30, min_size+35) + self.setMinimumSize(min_size + 30, min_size + 35) else: self.setMinimumSize(min_size, min_size) self.show() + def change_angle(self, angle): self.numberControl.change_angle(angle) def setColors(self, backgroundColor='default', needleTip='red', needleBody='black', scaleColor='black'): - self.numberControl.setColors(backgroundColor, needleTip, needleBody, scaleColor) + self.numberControl.setColors( + backgroundColor, needleTip, needleBody, scaleColor) + class Compass(QWidget): angleChanged = pyqtSignal(float) @@ -116,16 +120,18 @@ class Compass(QWidget): painter.setRenderHint(QPainter.Antialiasing) if self.backgroundColor == 'default': - painter.fillRect(event.rect(), self.palette().brush(QPalette.Window)) + painter.fillRect( + event.rect(), self.palette().brush(QPalette.Window)) else: size = self.size() - center_x = size.width()/2 + center_x = size.width() / 2 diameter = size.height() brush = QBrush(QColor(self.backgroundColor), Qtc.SolidPattern) painter.setBrush(brush) painter.setPen(QPen(QColor(self.scaleColor), 2)) painter.setRenderHint(QPainter.Antialiasing) - painter.drawEllipse(center_x-diameter/2+1, 1, diameter-4, diameter-4) + painter.drawEllipse(center_x - diameter / 2 + 1, + 1, diameter - 4, diameter - 4) self.drawMarkings(painter) self.drawNeedle(painter) @@ -134,9 +140,9 @@ class Compass(QWidget): def drawMarkings(self, painter): painter.save() - painter.translate(self.width()/2, self.height()/2) - scale = min((self.width() - self._margins)/120.0, - (self.height() - self._margins)/120.0) + painter.translate(self.width() / 2, self.height() / 2) + scale = min((self.width() - self._margins) / 120.0, + (self.height() - self._margins) / 120.0) painter.scale(scale, scale) font = QFont(self.font()) @@ -151,7 +157,8 @@ class Compass(QWidget): if i % 45 == 0: painter.drawLine(0, -40, 0, -50) - painter.drawText(-metrics.width(self._pointText[i])/2.0, -52, self._pointText[i]) + painter.drawText(-metrics.width( + self._pointText[i]) / 2.0, -52, self._pointText[i]) else: painter.drawLine(0, -45, 0, -50) @@ -163,9 +170,9 @@ class Compass(QWidget): def drawNeedle(self, painter): painter.save() # Set up painter - painter.translate(self.width()/2, self.height()/2) - scale = min((self.width() - self._margins)/120.0, - (self.height() - self._margins)/120.0) + painter.translate(self.width() / 2, self.height() / 2) + scale = min((self.width() - self._margins) / 120.0, + (self.height() - self._margins) / 120.0) painter.scale(scale, scale) painter.setPen(QPen(Qtc.NoPen)) @@ -211,7 +218,7 @@ class Compass(QWidget): painter.drawPolygon( QPolygon([QPoint(-3, -25), QPoint(0, -45), QPoint(3, -25), QPoint(0, -30), QPoint(-3, -25)]) - ) + ) painter.restore() @@ -240,12 +247,15 @@ class GrCompass(gr.sync_block, LabeledCompass): and mirrored (mirrored is useful for direction-finding where an ambiguity exists in front/back detection angle). """ + def __init__(self, title, min_size, update_time, setDebug=False, needleType=NeedleFull, usemsg=False, position=1, backgroundColor='default'): if usemsg: - gr.sync_block.__init__(self, name="QTCompass", in_sig=[], out_sig=[]) + gr.sync_block.__init__( + self, name="QTCompass", in_sig=[], out_sig=[]) else: - gr.sync_block.__init__(self, name="QTCompass", in_sig=[numpy.float32], out_sig=[]) + gr.sync_block.__init__(self, name="QTCompass", in_sig=[ + numpy.float32], out_sig=[]) LabeledCompass.__init__(self, title, min_size, update_time, setDebug, needleType, position, backgroundColor) @@ -266,7 +276,8 @@ class GrCompass(gr.sync_block, LabeledCompass): if type(new_val) == float or type(new_val) == int: super().change_angle(float(new_val)) else: - gr.log.error("Value received was not an int or a float: %s" % str(type(new_val))) + gr.log.error( + "Value received was not an int or a float: %s" % str(type(new_val))) except Exception as e: gr.log.error("Error with message conversion: %s" % str(e)) diff --git a/gr-qtgui/python/qtgui/dialcontrol.py b/gr-qtgui/python/qtgui/dialcontrol.py index 2e19e18219..1c7077176c 100644 --- a/gr-qtgui/python/qtgui/dialcontrol.py +++ b/gr-qtgui/python/qtgui/dialcontrol.py @@ -16,6 +16,7 @@ from PyQt5.QtCore import QSize from gnuradio import gr import pmt + class LabeledDialControl(QFrame): def __init__(self, lbl='', parent=None, minimum=0, maximum=100, defaultvalue=0, backgroundColor='default', changedCallback=None, @@ -36,7 +37,7 @@ class LabeledDialControl(QFrame): self.lblcontrol.setAlignment(Qtc.AlignCenter) if self.showvalue: - textstr = self.buildTextStr(defaultvalue*self.scaleFactor) + textstr = self.buildTextStr(defaultvalue * self.scaleFactor) self.lblcontrol.setText(textstr) if len or self.showvalue: @@ -73,6 +74,7 @@ class LabeledDialControl(QFrame): textstr = self.buildTextStr(new_value) self.lblcontrol.setText(textstr) + class DialControl(Qt.QDial): def __init__(self, minimum=0, maximum=100, defaultvalue=0, backgroundColor='default', lablelCallback=None, changedCallback=None, minsize=100): @@ -99,6 +101,7 @@ class DialControl(Qt.QDial): if self.lablelCallback is not None: self.lablelCallback(self.value()) + class GrDialControl(gr.sync_block, LabeledDialControl): """ This block creates a dial control. The control does control a @@ -112,10 +115,12 @@ class GrDialControl(gr.sync_block, LabeledDialControl): the desired range. Think of the min/max as the increments, and the scale factor as the adjustment to get the values you want. """ + def __init__(self, lbl, parent, minimum, maximum, defaultvalue, backgroundColor='default', varCallback=None, isFloat=False, scaleFactor=1, minsize=100, showvalue=False, outputmsgname='value'): - gr.sync_block.__init__(self, name="GrDialControl", in_sig=None, out_sig=None) + gr.sync_block.__init__(self, name="GrDialControl", + in_sig=None, out_sig=None) LabeledDialControl.__init__(self, lbl, parent, minimum, maximum, defaultvalue, backgroundColor, self.valueChanged, minsize, isFloat, scaleFactor, showvalue) @@ -139,4 +144,3 @@ class GrDialControl(gr.sync_block, LabeledDialControl): else: self.message_port_pub(pmt.intern("value"), pmt.cons(pmt.intern(self.outputmsgname), pmt.from_long(new_value))) - diff --git a/gr-qtgui/python/qtgui/dialgauge.py b/gr-qtgui/python/qtgui/dialgauge.py index af96f2e096..6dbb1bf84b 100644 --- a/gr-qtgui/python/qtgui/dialgauge.py +++ b/gr-qtgui/python/qtgui/dialgauge.py @@ -18,6 +18,7 @@ from PyQt5.QtCore import Qt as Qtc from gnuradio import gr import pmt + class LabeledDialGauge(QFrame): # Positions: 1 = above, 2=below, 3=left, 4=right def __init__(self, lbl='', barColor='blue', backgroundColor='white', fontColor='black', @@ -45,7 +46,8 @@ class LabeledDialGauge(QFrame): self.lblcontrol.setText(lbl) if fontColor != 'default': - self.lblcontrol.setStyleSheet("QLabel { color : " + fontColor + "; }") + self.lblcontrol.setStyleSheet( + "QLabel { color : " + fontColor + "; }") # add top or left if len: @@ -69,6 +71,7 @@ class LabeledDialGauge(QFrame): def setValue(self, new_value): self.numberControl.setValue(new_value) + class DialGauge(QFrame): def __init__(self, barColor='blue', backgroundColor='white', fontColor='black', minValue=0, maxValue=100, maxSize=80, @@ -97,7 +100,7 @@ class DialGauge(QFrame): self.startAngle = 0.0 self.endAngle = 360.0 - self.degScaler = 16.0 # The span angle must be specified in 1/16 of a degree units + self.degScaler = 16.0 # The span angle must be specified in 1/16 of a degree units self.penWidth = max(int(0.1 * maxSize), 6) self.halfPenWidth = int(self.penWidth / 2) @@ -122,15 +125,17 @@ class DialGauge(QFrame): size = self.size() - percentRange = float(self.value - self.minValue) / float(self.maxValue - self.minValue) - endAngle = self.startAngle + round(percentRange * float(self.endAngle - self.startAngle), 0) + percentRange = float(self.value - self.minValue) / \ + float(self.maxValue - self.minValue) + endAngle = self.startAngle + \ + round(percentRange * float(self.endAngle - self.startAngle), 0) # Now convert angles to 1/16 scale startAngle = int(round(self.startAngle * self.degScaler, 0)) endAngle = int(round(endAngle * self.degScaler, 0)) - rect = QtCore.QRect(self.halfPenWidth, self.halfPenWidth, size.width()-self.penWidth, - size.height()-self.penWidth) + rect = QtCore.QRect(self.halfPenWidth, self.halfPenWidth, size.width() - self.penWidth, + size.height() - self.penWidth) # Set up the painting canvass painter = QPainter() @@ -146,7 +151,7 @@ class DialGauge(QFrame): else: printText = str(int(self.value)) - painter.drawText(size.width()/2-self.metrics.width(printText)/2, size.height()/2, + painter.drawText(size.width() / 2 - self.metrics.width(printText) / 2, size.height() / 2, printText) painter.save() @@ -155,27 +160,31 @@ class DialGauge(QFrame): # First draw complete circle painter.setPen(QPen(QColor(self.backgroundColor), self.penWidth)) - painter.drawArc(rect, startAngle, self.endAngle*self.degScaler) + painter.drawArc(rect, startAngle, self.endAngle * self.degScaler) # First draw complete circle painter.setPen(QPen(QColor(self.barColor), self.penWidth)) painter.drawArc(rect, startAngle, -endAngle) painter.setPen(QPen(QColor('darkgray'), 2)) - painter.drawEllipse(1, 1, rect.width()+self.penWidth-2, rect.width()+self.penWidth-2) - painter.drawEllipse(1+self.penWidth, 1+self.penWidth, rect.width()-self.penWidth-2, - rect.width()-self.penWidth-2) + painter.drawEllipse(1, 1, rect.width() + self.penWidth - + 2, rect.width() + self.penWidth - 2) + painter.drawEllipse(1 + self.penWidth, 1 + self.penWidth, rect.width() - self.penWidth - 2, + rect.width() - self.penWidth - 2) painter.restore() painter.end() + class GrDialGauge(gr.sync_block, LabeledDialGauge): """ This block creates a dial-style gauge. The value can be set either with a variable or an input message. """ + def __init__(self, lbl='', barColor='blue', backgroundColor='white', fontColor='black', minValue=0, maxValue=100, maxSize=80, position=1, isFloat=False, showValue=False, fixedOrMin=True, parent=None): - gr.sync_block.__init__(self, name="DialGauge", in_sig=None, out_sig=None) + gr.sync_block.__init__(self, name="DialGauge", + in_sig=None, out_sig=None) LabeledDialGauge.__init__(self, lbl, barColor, backgroundColor, fontColor, minValue, maxValue, maxSize, position, isFloat, showValue, fixedOrMin, parent) @@ -188,7 +197,6 @@ class GrDialGauge(gr.sync_block, LabeledDialGauge): self.message_port_register_in(pmt.intern("value")) self.set_msg_handler(pmt.intern("value"), self.msgHandler) - def msgHandler(self, msg): try: new_val = pmt.to_python(pmt.cdr(msg)) @@ -197,12 +205,10 @@ class GrDialGauge(gr.sync_block, LabeledDialGauge): super().setValue(new_val) else: gr.log.error("Value received was not an int or a float. " - "Received %s" % str(type(new_val))) + "Received %s" % str(type(new_val))) except Exception as e: gr.log.error("Error with message conversion: %s" % str(e)) - def setValue(self, new_value): super().setValue(new_value) - diff --git a/gr-qtgui/python/qtgui/digitalnumbercontrol.py b/gr-qtgui/python/qtgui/digitalnumbercontrol.py index 44ddfbd8ca..cbaf322b7d 100644 --- a/gr-qtgui/python/qtgui/digitalnumbercontrol.py +++ b/gr-qtgui/python/qtgui/digitalnumbercontrol.py @@ -23,13 +23,14 @@ import pmt # # + class LabeledDigitalNumberControl(QFrame): def __init__(self, lbl='', min_freq_hz=0, max_freq_hz=6000000000, parent=None, thousands_separator=',', background_color='black', fontColor='white', click_callback=None): QFrame.__init__(self, parent) self.numberControl = DigitalNumberControl(min_freq_hz, max_freq_hz, self, - thousands_separator, background_color, fontColor, click_callback) + thousands_separator, background_color, fontColor, click_callback) layout = QVBoxLayout() @@ -47,9 +48,9 @@ class LabeledDigitalNumberControl(QFrame): def minimumSizeHint(self): if self.hasLabel: - return QSize(self.numberControl.minimumWidth()+10, 100) + return QSize(self.numberControl.minimumWidth() + 10, 100) else: - return QSize(self.numberControl.minimumWidth()+10, 50) + return QSize(self.numberControl.minimumWidth() + 10, 50) def setReadOnly(self, b_read_only): self.numberControl.setReadOnly(b_read_only) @@ -60,6 +61,7 @@ class LabeledDigitalNumberControl(QFrame): def getFrequency(self): return self.numberControl.getFrequency() + class DigitalNumberControl(QFrame): # Notifies to avoid thread conflicts on paints updateInt = pyqtSignal(int) @@ -96,7 +98,7 @@ class DigitalNumberControl(QFrame): fm = QFontMetrics(self.numberFont) if len(self.thousands_separator) > 0: # The -1 makes sure we don't count an extra for 123,456,789. Answer should be 2 not 3. - numgroups = int(float(self.numDigitsInFreq-1) / 3.0) + numgroups = int(float(self.numDigitsInFreq - 1) / 3.0) if numgroups > 0: for i in range(0, numgroups): teststr += self.thousands_separator @@ -129,7 +131,8 @@ class DigitalNumberControl(QFrame): if self.read_only: if self.debug_click: - gr.log.info("click received but read-only. Not changing frequency.") + gr.log.info( + "click received but read-only. Not changing frequency.") return fm = QFontMetrics(self.numberFont) @@ -154,12 +157,12 @@ class DigitalNumberControl(QFrame): found_number = False clicked_thousands = False - for i in range(1, len(textstr)+1): + for i in range(1, len(textstr) + 1): width = fm.width(textstr[-i:]) charstr = textstr[-i:] widthchar = fm.width(charstr[0]) - if clickpos >= (width-widthchar) and clickpos <= width: - clicked_char = i-1 + if clickpos >= (width - widthchar) and clickpos <= width: + clicked_char = i - 1 clicked_num_index = clicked_char @@ -170,7 +173,8 @@ class DigitalNumberControl(QFrame): numSeps = charstr.count(self.thousands_separator) clicked_num_index -= numSeps if self.debug_click: - gr.log.info("clicked number: " + str(clicked_num_index)) + gr.log.info("clicked number: " + + str(clicked_num_index)) else: clicked_thousands = True if self.debug_click: @@ -181,7 +185,7 @@ class DigitalNumberControl(QFrame): # Remember y=0 is at the top so this is reversed clicked_up = False - if self.offset.y() > self.size().height()/2: + if self.offset.y() > self.size().height() / 2: if self.debug_click: gr.log.info('clicked down') else: @@ -200,7 +204,7 @@ class DigitalNumberControl(QFrame): # Cannot call setFrequency to emit. Change must happen now for # paint event when clicked. self.setFrequencyNow(cur_freq) - + if self.click_callback is not None: self.click_callback(self.getFrequency()) break @@ -208,7 +212,7 @@ class DigitalNumberControl(QFrame): if (not found_number) and (not clicked_thousands): # See if we clicked in the high area, if so, increment there. clicked_up = False - if self.offset.y() > self.size().height()/2: + if self.offset.y() > self.size().height() / 2: if self.debug_click: gr.log.info('clicked down in the high area') else: @@ -228,16 +232,17 @@ class DigitalNumberControl(QFrame): # Cannot call setFrequency to emit. Change must happen now for # paint event when clicked. self.setFrequencyNow(cur_freq) - + if self.click_callback is not None: if self.debug_click: gr.log.info('Calling self.click_callback') - + self.click_callback(self.getFrequency()) else: if self.debug_click: - gr.log.info('self.click_callback is None. Not calling callback.') - + gr.log.info( + 'self.click_callback is None. Not calling callback.') + def setColors(self, background, fontColor): self.background_color = background self.fontColor = fontColor @@ -265,7 +270,7 @@ class DigitalNumberControl(QFrame): if (new_freq >= self.min_freq) and (new_freq <= self.max_freq): self.cur_freq = int(new_freq) self.update() - + def setFrequency(self, new_freq): if type(new_freq) == int: self.updateInt.emit(new_freq) @@ -290,7 +295,7 @@ class DigitalNumberControl(QFrame): brush = QBrush() brush.setColor(self.background_color) brush.setStyle(Qt.SolidPattern) - rect = QtCore.QRect(2, 2, size.width()-4, size.height()-4) + rect = QtCore.QRect(2, 2, size.width() - 4, size.height() - 4) painter.fillRect(rect, brush) self.numberFont.setPixelSize(0.9 * size.height()) @@ -307,13 +312,15 @@ class DigitalNumberControl(QFrame): else: textstr = str(self.getFrequency()) - rect = QtCore.QRect(0, 0, size.width()-4, size.height()) - + rect = QtCore.QRect(0, 0, size.width() - 4, size.height()) + painter.drawText(rect, Qt.AlignRight + Qt.AlignVCenter, textstr) # ################################################################################ # GNU Radio Class + + class MsgDigitalNumberControl(gr.sync_block, LabeledDigitalNumberControl): def __init__(self, lbl='', min_freq_hz=0, max_freq_hz=6000000000, parent=None, thousands_separator=',', background_color='black', fontColor='white', @@ -321,7 +328,7 @@ class MsgDigitalNumberControl(gr.sync_block, LabeledDigitalNumberControl): gr.sync_block.__init__(self, name="MsgDigitalNumberControl", in_sig=None, out_sig=None) LabeledDigitalNumberControl.__init__(self, lbl, min_freq_hz, max_freq_hz, parent, - thousands_separator, background_color, fontColor, self.click_callback) + thousands_separator, background_color, fontColor, self.click_callback) self.var_callback = var_callback self.outputmsgname = outputmsgname @@ -339,7 +346,8 @@ class MsgDigitalNumberControl(gr.sync_block, LabeledDigitalNumberControl): self.setValue(new_val) else: - gr.log.error("Value received was not an int or a float. %s" % str(type(new_val))) + gr.log.error( + "Value received was not an int or a float. %s" % str(type(new_val))) except Exception as e: gr.log.error("Error with message conversion: %s" % str(e)) @@ -354,16 +362,17 @@ class MsgDigitalNumberControl(gr.sync_block, LabeledDigitalNumberControl): def click_callback(self, new_value): self.call_var_callback(new_value) - self.message_port_pub(pmt.intern("valueout"), pmt.cons(pmt.intern(self.outputmsgname), pmt.from_double(float(new_value)))) + self.message_port_pub(pmt.intern("valueout"), pmt.cons( + pmt.intern(self.outputmsgname), pmt.from_double(float(new_value)))) def setValue(self, new_val): self.setFrequency(new_val) - self.message_port_pub(pmt.intern("valueout"), pmt.cons(pmt.intern(self.outputmsgname), pmt.from_double(float(self.getFrequency())))) + self.message_port_pub(pmt.intern("valueout"), pmt.cons(pmt.intern( + self.outputmsgname), pmt.from_double(float(self.getFrequency())))) def getValue(self): self.getFrequency() def setReadOnly(self, b_read_only): super().setReadOnly(b_read_only) - diff --git a/gr-qtgui/python/qtgui/distanceradar.py b/gr-qtgui/python/qtgui/distanceradar.py index 5659045c27..6619ef2174 100644 --- a/gr-qtgui/python/qtgui/distanceradar.py +++ b/gr-qtgui/python/qtgui/distanceradar.py @@ -15,10 +15,11 @@ import numpy as np import matplotlib.pyplot as plt from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure - + from gnuradio import gr import pmt + class DistanceRadar(gr.sync_block, FigureCanvas): """ This block creates a radar-like screen used to represent distance or size. @@ -28,9 +29,11 @@ class DistanceRadar(gr.sync_block, FigureCanvas): Note: Incoming values should range between 0 (center bullseye) and 100 (all the way out) """ + def __init__(self, lbl, ticklabels, backgroundColor, fontColor, ringColor, Parent=None, width=4, height=4, dpi=100): - gr.sync_block.__init__(self, name="distanceradar", in_sig=None, out_sig=None) + gr.sync_block.__init__(self, name="distanceradar", + in_sig=None, out_sig=None) self.lbl = lbl @@ -43,15 +46,16 @@ class DistanceRadar(gr.sync_block, FigureCanvas): self.fig = Figure(figsize=(width, height), dpi=dpi) self.fig.patch.set_facecolor(self.backgroundColor) - self.axes = self.fig.add_subplot(111, polar=True, facecolor=self.backgroundColor) + self.axes = self.fig.add_subplot( + 111, polar=True, facecolor=self.backgroundColor) # Create an "invisible" line at 100 to set the max for the plot - self.axes.plot(np.linspace(0, 2*np.pi, 100), np.ones(100)*100, color=self.fontColor, + self.axes.plot(np.linspace(0, 2 * np.pi, 100), np.ones(100) * 100, color=self.fontColor, linestyle='') # Plot line: Initialize out to 100 and blank radius = 100 - self.blackline = self.axes.plot(np.linspace(0, 2*np.pi, 100), np.ones(100)*radius, + self.blackline = self.axes.plot(np.linspace(0, 2 * np.pi, 100), np.ones(100) * radius, color=self.fontColor, linestyle='-') self.redline = None @@ -70,9 +74,8 @@ class DistanceRadar(gr.sync_block, FigureCanvas): FigureCanvas.__init__(self, self.fig) self.setParent(Parent) - self.title = self.fig.suptitle(self.lbl, fontsize=8, fontweight='bold', - color=self.fontColor) + color=self.fontColor) FigureCanvas.setSizePolicy(self, QtWidgets.QSizePolicy.Expanding, @@ -87,7 +90,7 @@ class DistanceRadar(gr.sync_block, FigureCanvas): self.updateData(new_val) else: gr.log.error("Value received was not an int or a " - "float: %s" % str(type(new_val))) + "float: %s" % str(type(new_val))) except Exception as e: gr.log.error("Error with message conversion: %s" % str(e)) @@ -95,7 +98,7 @@ class DistanceRadar(gr.sync_block, FigureCanvas): def updateData(self, radius): if self.redline is not None: self.redline.pop(0).remove() - self.redline = self.axes.plot(np.linspace(0, 2*np.pi, 100), np.ones(100)*radius, + self.redline = self.axes.plot(np.linspace(0, 2 * np.pi, 100), np.ones(100) * radius, color='r', linestyle='-') if self.filledcircle: @@ -111,4 +114,3 @@ class DistanceRadar(gr.sync_block, FigureCanvas): self.bullseye = self.axes.add_artist(circle) self.draw() - diff --git a/gr-qtgui/python/qtgui/graphicitem.py b/gr-qtgui/python/qtgui/graphicitem.py index ecc7cc20fc..871aa09497 100644 --- a/gr-qtgui/python/qtgui/graphicitem.py +++ b/gr-qtgui/python/qtgui/graphicitem.py @@ -20,6 +20,7 @@ import sys from gnuradio import gr import pmt + class GrGraphicItem(gr.sync_block, QLabel): """ This block displays the selected graphic item. You can pass a @@ -32,8 +33,10 @@ class GrGraphicItem(gr.sync_block, QLabel): Otherwise items are indexed by filename and can be animated throughout the background image. """ + def __init__(self, image_file, scaleImage=True, fixedSize=False, setWidth=0, setHeight=0): - gr.sync_block.__init__(self, name="GrGraphicsItem", in_sig=None, out_sig=None) + gr.sync_block.__init__(self, name="GrGraphicsItem", + in_sig=None, out_sig=None) QLabel.__init__(self) if not os.path.isfile(image_file): @@ -67,9 +70,9 @@ class GrGraphicItem(gr.sync_block, QLabel): overlayitem = pmt.to_python(pmt.car(msg)) if overlayitem is None: gr.log.error('Overlay message contains None in the car portion ' - 'of the message. Please pass in a dictionary or list of dictionaries in this ' - 'portion of the message. Each dictionary should have the following keys: ' - 'filename,x,y. Use x=y=-1 to remove an overlay item.') + 'of the message. Please pass in a dictionary or list of dictionaries in this ' + 'portion of the message. Each dictionary should have the following keys: ' + 'filename,x,y. Use x=y=-1 to remove an overlay item.') return if type(overlayitem) is dict: @@ -79,41 +82,43 @@ class GrGraphicItem(gr.sync_block, QLabel): itemlist = overlayitem else: gr.log.error("Overlay message type is not correct. Please pass in " - "a dictionary or list of dictionaries in this portion of the message. Each " - "dictionary should have the following keys: filename,x,y. Use x=y=-1 to " - "remove an overlay item.") + "a dictionary or list of dictionaries in this portion of the message. Each " + "dictionary should have the following keys: filename,x,y. Use x=y=-1 to " + "remove an overlay item.") return # Check each dict item to make sure it's valid. for curitem in itemlist: if type(curitem) == dict: if 'filename' not in curitem: - gr.log.error("Dictionary item did not contain the 'filename' key.") + gr.log.error( + "Dictionary item did not contain the 'filename' key.") gr.log.error("Received " + str(curitem)) continue if 'x' not in curitem: gr.log.error("The dictionary for filename " + - curitem['filename'] + " did not contain an 'x' key.") + curitem['filename'] + " did not contain an 'x' key.") gr.log.error("Received " + str(curitem)) continue if 'y' not in curitem: gr.log.error("The dictionary for filename " + - curitem['filename'] + " did not contain an 'y' key.") + curitem['filename'] + " did not contain an 'y' key.") gr.log.error("Received " + str(curitem)) continue if not os.path.isfile(curitem['filename']): gr.log.error("Unable to find overlay file " + - curitem['filename']) + curitem['filename']) gr.log.error("Received " + str(curitem)) continue # Now either add/update our list or remove the item. if curitem['x'] == -1 and curitem['y'] == -1: try: - del self.overlays[curitem['filename']] # remove item + # remove item + del self.overlays[curitem['filename']] except: pass else: @@ -142,9 +147,10 @@ class GrGraphicItem(gr.sync_block, QLabel): scale = curOverlay['scalefactor'] w = newOverlay.width() h = newOverlay.height() - newOverlay = newOverlay.scaled(int(w*scale), int(h*scale), + newOverlay = newOverlay.scaled(int(w * scale), int(h * scale), Qtc.KeepAspectRatio) - painter.drawPixmap(curOverlay['x'], curOverlay['y'], newOverlay) + painter.drawPixmap( + curOverlay['x'], curOverlay['y'], newOverlay) except Exception as e: gr.log.error("Error adding overlay: %s" % str(e)) return @@ -172,13 +178,13 @@ class GrGraphicItem(gr.sync_block, QLabel): self.updateGraphic() else: gr.log.error("Value received was not an int or " - "a bool: %s" % str(type(new_val))) + "a bool: %s" % str(type(new_val))) except Exception as e: gr.log.error("Error with message conversion: %s" % str(e)) def minimumSizeHint(self): - return QSize(self.pixmap.width(),self.pixmap.height()) + return QSize(self.pixmap.width(), self.pixmap.height()) def resizeEvent(self, event): if self.scaleImage: @@ -191,4 +197,3 @@ class GrGraphicItem(gr.sync_block, QLabel): Qtc.KeepAspectRatio) self.updateGraphic() - diff --git a/gr-qtgui/python/qtgui/graphicoverlay.py b/gr-qtgui/python/qtgui/graphicoverlay.py index defef31d17..dad40dfe13 100644 --- a/gr-qtgui/python/qtgui/graphicoverlay.py +++ b/gr-qtgui/python/qtgui/graphicoverlay.py @@ -18,39 +18,42 @@ import pmt # This thread just gets us out of the sync_block's init function so the messaging # system and scheduler are active. + + class offloadThread(threading.Thread): - def __init__(self, callback, overlayList, listDelay, repeat): - threading.Thread.__init__(self) - self.callback = callback - self.overlayList = overlayList - self.listDelay = listDelay - self.threadRunning = False - self.stopThread = False - self.repeat = repeat + def __init__(self, callback, overlayList, listDelay, repeat): + threading.Thread.__init__(self) + self.callback = callback + self.overlayList = overlayList + self.listDelay = listDelay + self.threadRunning = False + self.stopThread = False + self.repeat = repeat - def run(self): - self.stopThread = False - self.threadRunning = True + def run(self): + self.stopThread = False + self.threadRunning = True - # Wait for main __init__ to finish - time.sleep(0.5) + # Wait for main __init__ to finish + time.sleep(0.5) - if (type(self.overlayList) == list and self.listDelay > 0.0): - while self.repeat and not self.stopThread: - for curItem in self.overlayList: - self.callback(curItem) + if (type(self.overlayList) == list and self.listDelay > 0.0): + while self.repeat and not self.stopThread: + for curItem in self.overlayList: + self.callback(curItem) - if self.stopThread: - break + if self.stopThread: + break - time.sleep(self.listDelay) + time.sleep(self.listDelay) - if self.stopThread: - break - else: - self.callback(self.overlayList) + if self.stopThread: + break + else: + self.callback(self.overlayList) + + self.threadRunning = False - self.threadRunning = False class GrGraphicOverlay(gr.sync_block): """ @@ -69,6 +72,7 @@ class GrGraphicOverlay(gr.sync_block): you can use a list with the same file but different coordinates and use the update delay > 0.0 to animate it. """ + def __init__(self, overlayList, listDelay, repeat): gr.sync_block.__init__(self, name="GrGraphicsOverlay", in_sig=None, out_sig=None) @@ -77,8 +81,8 @@ class GrGraphicOverlay(gr.sync_block): self.listDelay = listDelay if type(self.overlayList) is not dict and type(self.overlayList) is not list: gr.log.error("The specified input is not valid. " - "Please specify either a dictionary item with the following keys: " - "'filename','x','y'[,'scalefactor'] or a list of dictionary items.") + "Please specify either a dictionary item with the following keys: " + "'filename','x','y'[,'scalefactor'] or a list of dictionary items.") sys.exit(1) self.message_port_register_out(pmt.intern("overlay")) @@ -100,4 +104,3 @@ class GrGraphicOverlay(gr.sync_block): time.sleep(0.1) return True - diff --git a/gr-qtgui/python/qtgui/ledindicator.py b/gr-qtgui/python/qtgui/ledindicator.py index 09b2bd8e19..094197cf20 100644 --- a/gr-qtgui/python/qtgui/ledindicator.py +++ b/gr-qtgui/python/qtgui/ledindicator.py @@ -18,12 +18,14 @@ from PyQt5.QtGui import QRadialGradient from gnuradio import gr import pmt + class LabeledLEDIndicator(QFrame): # Positions: 1 = above, 2=below, 3=left, 4=right def __init__(self, lbl='', onColor='green', offColor='red', initialState=False, maxSize=80, position=1, alignment=1, valignment=1, parent=None): QFrame.__init__(self, parent) - self.numberControl = LEDIndicator(onColor, offColor, initialState, maxSize, parent) + self.numberControl = LEDIndicator( + onColor, offColor, initialState, maxSize, parent) if position < 3: layout = QVBoxLayout() @@ -72,17 +74,18 @@ class LabeledLEDIndicator(QFrame): textfont = self.lblcontrol.font() metrics = QFontMetricsF(textfont) - maxWidth = max((maxSize+30), (maxSize + metrics.width(lbl)+4)) - maxHeight = max((maxSize+35), (maxSize + metrics.height()+2)) + maxWidth = max((maxSize + 30), (maxSize + metrics.width(lbl) + 4)) + maxHeight = max((maxSize + 35), (maxSize + metrics.height() + 2)) self.setMinimumSize(maxWidth, maxHeight) else: - self.setMinimumSize(maxSize+2, maxSize+2) + self.setMinimumSize(maxSize + 2, maxSize + 2) self.show() def setState(self, on_off): self.numberControl.setState(on_off) + class LEDIndicator(QFrame): def __init__(self, onColor='green', offColor='red', initialState=False, maxSize=80, parent=None): @@ -112,11 +115,11 @@ class LEDIndicator(QFrame): if smallest_dim > size.height(): smallest_dim = size.height() - smallest_dim = smallest_dim/2 + smallest_dim = smallest_dim / 2 smallest_dim -= 2 - center_x = size.width()/2 - center_y = size.height()/2 + center_x = size.width() / 2 + center_y = size.height() / 2 centerpoint = QPoint(center_x, center_y) radius = smallest_dim @@ -124,14 +127,14 @@ class LEDIndicator(QFrame): painter.setPen(QPen(QColor('lightgray'), 0)) brush.setStyle(Qtc.SolidPattern) - radial = QRadialGradient(center_x, center_y/2, radius) + radial = QRadialGradient(center_x, center_y / 2, radius) radial.setColorAt(0, Qtc.white) radial.setColorAt(0.8, Qtc.darkGray) painter.setBrush(QBrush(radial)) painter.drawEllipse(centerpoint, radius, radius) # Draw the colored center - radial = QRadialGradient(center_x, center_y/2, radius) + radial = QRadialGradient(center_x, center_y / 2, radius) radial.setColorAt(0, Qtc.white) if self.curState: @@ -159,13 +162,16 @@ class LEDIndicator(QFrame): radius = radius - 9 painter.drawEllipse(centerpoint, radius, radius) + class GrLEDIndicator(gr.sync_block, LabeledLEDIndicator): """ This block makes a basic LED indicator """ + def __init__(self, lbl='', onColor='green', offColor='red', initialState=False, maxSize=80, position=1, alignment=1, valignment=1, parent=None): - gr.sync_block.__init__(self, name="LEDIndicator", in_sig=None, out_sig=None) + gr.sync_block.__init__(self, name="LEDIndicator", + in_sig=None, out_sig=None) LabeledLEDIndicator.__init__(self, lbl, onColor, offColor, initialState, maxSize, position, alignment, valignment, parent) self.lbl = lbl @@ -173,7 +179,6 @@ class GrLEDIndicator(gr.sync_block, LabeledLEDIndicator): self.message_port_register_in(pmt.intern("state")) self.set_msg_handler(pmt.intern("state"), self.msgHandler) - def msgHandler(self, msg): try: new_val = pmt.to_python(pmt.cdr(msg)) @@ -187,11 +192,11 @@ class GrLEDIndicator(gr.sync_block, LabeledLEDIndicator): else: super().setState(False) else: - gr.log.error("Value received was not an int or a bool: %s" % str(type(new_val))) + gr.log.error( + "Value received was not an int or a bool: %s" % str(type(new_val))) except Exception as e: gr.log.error("Error with message conversion: %s" % str(e)) def setState(self, on_off): super().setState(on_off) - diff --git a/gr-qtgui/python/qtgui/levelgauge.py b/gr-qtgui/python/qtgui/levelgauge.py index cee33eb58d..7703400034 100644 --- a/gr-qtgui/python/qtgui/levelgauge.py +++ b/gr-qtgui/python/qtgui/levelgauge.py @@ -21,6 +21,7 @@ from PyQt5.QtGui import QPalette from gnuradio import gr import pmt + class LabeledLevelGauge(QFrame): # Positions: 1 = above, 2=below, 3=left, 4=right def __init__(self, lbl='', barColor='blue', backgroundColor='white', fontColor='black', @@ -48,11 +49,12 @@ class LabeledLevelGauge(QFrame): # For whatever reason, the progressbar doesn't show the number in the bar if it's # vertical, only if it's horizontal if self.showvalue and (isFloat or self.isVertical): - textstr = self.buildTextStr(minValue/self.scaleFactor) + textstr = self.buildTextStr(minValue / self.scaleFactor) self.lblcontrol.setText(textstr) if fontColor != 'default': - self.lblcontrol.setStyleSheet("QLabel { color : " + fontColor + "; }") + self.lblcontrol.setStyleSheet( + "QLabel { color : " + fontColor + "; }") # add top or left if len: @@ -102,6 +104,7 @@ class LabeledLevelGauge(QFrame): self.numberControl.setValue(new_value) + class LevelGauge(QProgressBar): # Notifies to avoid thread conflicts on paints updateInt = pyqtSignal(int) @@ -170,6 +173,7 @@ class LevelGauge(QProgressBar): else: self.updateFloat.emit(new_value) + class GrLevelGauge(gr.sync_block, LabeledLevelGauge): """ This block creates a level gauge. The value can be set either @@ -182,10 +186,12 @@ class GrLevelGauge(gr.sync_block, LabeledLevelGauge): are 0-100 but your incoming values are 0.0-1.0, you will need to set a scalefactor of 100. """ + def __init__(self, lbl='', barColor='blue', backgroundColor='white', fontColor='black', minValue=0, maxValue=100, maxSize=80, isVertical=True, position=1, isFloat=False, scaleFactor=1, showValue=False, parent=None): - gr.sync_block.__init__(self, name="LevelGauge", in_sig=None, out_sig=None) + gr.sync_block.__init__(self, name="LevelGauge", + in_sig=None, out_sig=None) LabeledLevelGauge.__init__(self, lbl, barColor, backgroundColor, fontColor, minValue, maxValue, maxSize, position, isVertical, isFloat, scaleFactor, showValue, parent) @@ -205,7 +211,8 @@ class GrLevelGauge(gr.sync_block, LabeledLevelGauge): if type(new_val) == float or type(new_val) == int: super().setValue(new_val) else: - gr.log.error("Value received was not an int or a float: %s" % str(type(new_val))) + gr.log.error( + "Value received was not an int or a float: %s" % str(type(new_val))) except Exception as e: gr.log.error("Error with message conversion: %s" % str(e)) diff --git a/gr-qtgui/python/qtgui/msgcheckbox.py b/gr-qtgui/python/qtgui/msgcheckbox.py index f01c78bc02..d1fde95a57 100644 --- a/gr-qtgui/python/qtgui/msgcheckbox.py +++ b/gr-qtgui/python/qtgui/msgcheckbox.py @@ -16,6 +16,7 @@ from PyQt5.QtCore import Qt as Qtc from gnuradio import gr import pmt + class CheckBoxEx(Qt.QCheckBox): def __init__(self, lbl, callback=None): Qt.QCheckBox.__init__(self) @@ -28,6 +29,7 @@ class CheckBoxEx(Qt.QCheckBox): if self.callback is not None: self.callback(super().isChecked()) + class MsgCheckBox(gr.sync_block, QFrame): """ This block creates a variable checkbox. Leave the label blank to @@ -39,9 +41,11 @@ class MsgCheckBox(gr.sync_block, QFrame): This control will also produce a state message matching the set values. """ + def __init__(self, callback, lbl, pressedReleasedDict, initPressed, alignment, valignment, outputmsgname='value'): - gr.sync_block.__init__(self, name="MsgCheckBox", in_sig=None, out_sig=None) + gr.sync_block.__init__(self, name="MsgCheckBox", + in_sig=None, out_sig=None) QFrame.__init__(self) self.outputmsgname = outputmsgname @@ -84,36 +88,36 @@ class MsgCheckBox(gr.sync_block, QFrame): if type(self.pressReleasedDict['Pressed']) == bool: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_bool(self.pressReleasedDict['Pressed']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_bool(self.pressReleasedDict['Pressed']))) elif type(self.pressReleasedDict['Pressed']) == int: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_long(self.pressReleasedDict['Pressed']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_long(self.pressReleasedDict['Pressed']))) elif type(self.pressReleasedDict['Pressed']) == float: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_double(self.pressReleasedDict['Pressed']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_double(self.pressReleasedDict['Pressed']))) else: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.intern(self.pressReleasedDict['Pressed']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.intern(self.pressReleasedDict['Pressed']))) else: self.callback(self.pressReleasedDict['Released']) if type(self.pressReleasedDict['Released']) == bool: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_bool(self.pressReleasedDict['Released']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_bool(self.pressReleasedDict['Released']))) elif type(self.pressReleasedDict['Released']) == int: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_long(self.pressReleasedDict['Released']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_long(self.pressReleasedDict['Released']))) elif type(self.pressReleasedDict['Released']) == float: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_double(self.pressReleasedDict['Released']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_double(self.pressReleasedDict['Released']))) else: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.intern(self.pressReleasedDict['Released']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.intern(self.pressReleasedDict['Released']))) diff --git a/gr-qtgui/python/qtgui/msgpushbutton.py b/gr-qtgui/python/qtgui/msgpushbutton.py index a3ecaf06c5..4865cc1eb9 100644 --- a/gr-qtgui/python/qtgui/msgpushbutton.py +++ b/gr-qtgui/python/qtgui/msgpushbutton.py @@ -13,6 +13,7 @@ from PyQt5 import Qt from gnuradio import gr import pmt + class MsgPushButton(gr.sync_block, Qt.QPushButton): """ This block creates a variable push button that creates a message @@ -20,8 +21,10 @@ class MsgPushButton(gr.sync_block, Qt.QPushButton): the label. You can define both the output message pmt name as well as the value and value type. """ + def __init__(self, lbl, msgName, msgValue, relBackColor, relFontColor): - gr.sync_block.__init__(self, name="MsgPushButton", in_sig=None, out_sig=None) + gr.sync_block.__init__(self, name="MsgPushButton", + in_sig=None, out_sig=None) Qt.QPushButton.__init__(self, lbl) self.lbl = lbl @@ -44,13 +47,13 @@ class MsgPushButton(gr.sync_block, Qt.QPushButton): def onBtnClicked(self, pressed): if type(self.msgValue) == int: self.message_port_pub(pmt.intern("pressed"), - pmt.cons(pmt.intern(self.msgName), pmt.from_long(self.msgValue))) + pmt.cons(pmt.intern(self.msgName), pmt.from_long(self.msgValue))) elif type(self.msgValue) == float: self.message_port_pub(pmt.intern("pressed"), - pmt.cons(pmt.intern(self.msgName), pmt.from_double(self.msgValue))) + pmt.cons(pmt.intern(self.msgName), pmt.from_double(self.msgValue))) elif type(self.msgValue) == str: self.message_port_pub(pmt.intern("pressed"), - pmt.cons(pmt.intern(self.msgName), pmt.intern(self.msgValue))) + pmt.cons(pmt.intern(self.msgName), pmt.intern(self.msgValue))) elif type(self.msgValue) == bool: self.message_port_pub(pmt.intern("pressed"), - pmt.cons(pmt.intern(self.msgName), pmt.from_bool(self.msgValue))) + pmt.cons(pmt.intern(self.msgName), pmt.from_bool(self.msgValue))) diff --git a/gr-qtgui/python/qtgui/range.py.cmakein b/gr-qtgui/python/qtgui/range.py.cmakein index 05f2f421e0..1fc85b8e4c 100755 --- a/gr-qtgui/python/qtgui/range.py.cmakein +++ b/gr-qtgui/python/qtgui/range.py.cmakein @@ -37,21 +37,22 @@ class Range(object): self.precision = (precision + 2) if precision > 0 else 0 def find_nsteps(self): - self.nsteps = (self.max + self.step - self.min)/self.step + self.nsteps = (self.max + self.step - self.min) / self.step def demap_range(self, val): if val > self.max: val = self.max if val < self.min: val = self.min - return ((val-self.min)/self.step) + return ((val - self.min) / self.step) def map_range(self, val): if val > self.nsteps: val = self.max if val < 0: val = 0 - return (val*self.step+self.min) + return (val * self.step + self.min) + class QEngValidator(Qt.QValidator): def __init__(self, minimum, maximum, parent): @@ -63,9 +64,9 @@ class QEngValidator(Qt.QValidator): def validate(self, s, pos): try: - val=eng_notation.str_to_num(s) + val = eng_notation.str_to_num(s) except (IndexError, ValueError) as e: - if re.match(self.re,s): + if re.match(self.re, s): self.parent.setStyleSheet("background-color: yellow;") return (Qt.QValidator.Intermediate, s, pos) else: @@ -83,6 +84,7 @@ class QEngValidator(Qt.QValidator): def fixup(self, s): pass + class RangeWidget(QtWidgets.QWidget): def __init__(self, ranges, slot, label, style, rangeType=float, orientation=QtCore.Qt.Horizontal): """ Creates the QT Range widget """ @@ -100,38 +102,45 @@ class RangeWidget(QtWidgets.QWidget): self.notifyChanged = slot layout = Qt.QHBoxLayout() - layout.setContentsMargins( 0,0,0,0 ) + layout.setContentsMargins(0, 0, 0, 0) label = Qt.QLabel(label) layout.addWidget(label) if style == "dial": - self.d_widget = self.Dial(self, self.range, self.notifyChanged, rangeType) + self.d_widget = self.Dial( + self, self.range, self.notifyChanged, rangeType) elif style == "slider": - self.d_widget = self.Slider(self, self.range, self.notifyChanged, rangeType, orientation) + self.d_widget = self.Slider( + self, self.range, self.notifyChanged, rangeType, orientation) elif style == "counter": # The counter widget can be directly wired to the notifyChanged slot - self.d_widget = self.Counter(self, self.range, self.notifyChanged, rangeType) + self.d_widget = self.Counter( + self, self.range, self.notifyChanged, rangeType) elif style == "eng": # Text input with engineering notation support - self.d_widget = self.Eng(self, self.range, self.notifyChanged, rangeType) + self.d_widget = self.Eng( + self, self.range, self.notifyChanged, rangeType) elif style == "eng_slider": - self.d_widget = self.EngSlider(self, self.range, self.notifyChanged, rangeType, orientation) + self.d_widget = self.EngSlider( + self, self.range, self.notifyChanged, rangeType, orientation) else: # The CounterSlider needs its own internal handlers before calling notifyChanged - self.d_widget = self.CounterSlider(self, self.range, self.notifyChanged, rangeType, orientation) + self.d_widget = self.CounterSlider( + self, self.range, self.notifyChanged, rangeType, orientation) layout.addWidget(self.d_widget) self.setLayout(layout) class Dial(QtWidgets.QDial): """ Creates the range using a dial """ + def __init__(self, parent, ranges, slot, rangeType=float): QtWidgets.QDial.__init__(self, parent) self.rangeType = rangeType # Setup the dial - self.setRange(0, int(ranges.nsteps-1)) + self.setRange(0, int(ranges.nsteps - 1)) self.setSingleStep(1) self.setNotchesVisible(True) self.range = ranges @@ -151,13 +160,14 @@ class RangeWidget(QtWidgets.QWidget): class Slider(QtWidgets.QSlider): """ Creates the range using a slider """ + def __init__(self, parent, ranges, slot, rangeType=float, orientation=QtCore.Qt.Horizontal): QtWidgets.QSlider.__init__(self, orientation, parent) self.rangeType = rangeType # Setup the slider - #self.setFocusPolicy(QtCore.Qt.NoFocus) + # self.setFocusPolicy(QtCore.Qt.NoFocus) self.setRange(0, int(ranges.nsteps - 1)) self.setTickPosition(2) self.setSingleStep(1) @@ -169,7 +179,7 @@ class RangeWidget(QtWidgets.QWidget): self.setValue(temp) if ranges.nsteps > ranges.min_length: - interval = int(ranges.nsteps/ranges.min_length) + interval = int(ranges.nsteps / ranges.min_length) self.setTickInterval(interval) self.setPageStep(interval) else: @@ -188,9 +198,9 @@ class RangeWidget(QtWidgets.QWidget): def mousePressEvent(self, event): if((event.button() == QtCore.Qt.LeftButton)): if self.orientation == QtCore.Qt.Horizontal: - new = self.minimum() + ((self.maximum()-self.minimum()) * event.x()) / self.width() + new = self.minimum() + ((self.maximum() - self.minimum()) * event.x()) / self.width() else: - new = self.minimum() + ((self.maximum()-self.minimum()) * event.y()) / self.height() + new = self.minimum() + ((self.maximum() - self.minimum()) * event.y()) / self.height() self.setValue(int(new)) event.accept() # Use repaint rather than calling the super mousePressEvent. @@ -199,15 +209,16 @@ class RangeWidget(QtWidgets.QWidget): def mouseMoveEvent(self, event): if self.orientation == QtCore.Qt.Horizontal: - new = self.minimum() + ((self.maximum()-self.minimum()) * event.x()) / self.width() + new = self.minimum() + ((self.maximum() - self.minimum()) * event.x()) / self.width() else: - new = self.minimum() + ((self.maximum()-self.minimum()) * event.y()) / self.height() + new = self.minimum() + ((self.maximum() - self.minimum()) * event.y()) / self.height() self.setValue(int(new)) event.accept() QtWidgets.QSlider.repaint(self) class Counter(QtWidgets.QDoubleSpinBox): """ Creates the range using a counter """ + def __init__(self, parent, ranges, slot, rangeType=float): QtWidgets.QDoubleSpinBox.__init__(self, parent) @@ -230,6 +241,7 @@ class RangeWidget(QtWidgets.QWidget): class Eng(QtWidgets.QLineEdit): """ Creates the range using a text input """ + def __init__(self, parent, ranges, slot, rangeType=float): QtWidgets.QLineEdit.__init__(self) @@ -251,6 +263,7 @@ class RangeWidget(QtWidgets.QWidget): class CounterSlider(QtWidgets.QWidget): """ Creates the range using a counter and slider """ + def __init__(self, parent, ranges, slot, rangeType=float, orientation=QtCore.Qt.Horizontal): QtWidgets.QWidget.__init__(self, parent) @@ -259,12 +272,14 @@ class RangeWidget(QtWidgets.QWidget): # Slot to call in the parent self.notifyChanged = slot - self.slider = RangeWidget.Slider(parent, ranges, self.sliderChanged, rangeType, orientation) - self.counter = RangeWidget.Counter(parent, ranges, self.counterChanged, rangeType) + self.slider = RangeWidget.Slider( + parent, ranges, self.sliderChanged, rangeType, orientation) + self.counter = RangeWidget.Counter( + parent, ranges, self.counterChanged, rangeType) # Need another horizontal layout to wrap the other widgets. layout = Qt.QHBoxLayout() - layout.setContentsMargins( 0,0,0,0 ) + layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(10) layout.addWidget(self.slider) layout.addWidget(self.counter) @@ -308,6 +323,7 @@ class RangeWidget(QtWidgets.QWidget): class EngSlider(QtWidgets.QWidget): """ Creates the range using a counter and slider """ + def __init__(self, parent, ranges, slot, rangeType=float, orientation=QtCore.Qt.Horizontal): QtWidgets.QWidget.__init__(self, parent) @@ -317,8 +333,10 @@ class RangeWidget(QtWidgets.QWidget): # Slot to call in the parent self.notifyChanged = slot - self.slider = RangeWidget.Slider(parent, ranges, self.sliderChanged, rangeType, orientation) - self.counter = RangeWidget.Eng(parent, ranges, self.counterChanged, rangeType) + self.slider = RangeWidget.Slider( + parent, ranges, self.sliderChanged, rangeType, orientation) + self.counter = RangeWidget.Eng( + parent, ranges, self.counterChanged, rangeType) # Need another horizontal layout to wrap the other widgets. layout = Qt.QHBoxLayout() @@ -338,7 +356,8 @@ class RangeWidget(QtWidgets.QWidget): if not self.ignoreSlider: # convert Value to eng string self.ignoreCounter = True - self.counter.setText(eng_notation.num_to_str(self.rangeType(value))) + self.counter.setText( + eng_notation.num_to_str(self.rangeType(value))) self.notifyChanged(self.rangeType(value)) self.ignoreSlider = False @@ -346,17 +365,17 @@ class RangeWidget(QtWidgets.QWidget): """ Handles changing the slider when the counter is updated """ # Get the current slider value and check to see if the new value changes it current = self.slider.value() - print("counterChanged",value,"ign",self.ignoreCounter) + print("counterChanged", value, "ign", self.ignoreCounter) new = int(round(self.range.demap_range(value), 0)) # If it needs to change, ignore the slider event # Otherwise, the slider will cause the counter to round to the nearest tick if current != new: - self.ignoreSlider = True - self.slider.setValue(new) + self.ignoreSlider = True + self.slider.setValue(new) if not self.ignoreCounter: - print("to notify",self.rangeType(value)) + print("to notify", self.rangeType(value)) self.notifyChanged(self.rangeType(value)) self.ignoreCounter = False @@ -369,6 +388,7 @@ class RangeWidget(QtWidgets.QWidget): self.slider.setValue(new) self.first = False + if __name__ == "__main__": from PyQt5 import Qt import sys @@ -377,7 +397,8 @@ if __name__ == "__main__": print("Value updated - " + str(frequency)) app = Qt.QApplication(sys.argv) - widget = RangeWidget(Range(0, 100, 10, 1, 100), valueChanged, "Test", "counter_slider", int) + widget = RangeWidget(Range(0, 100, 10, 1, 100), + valueChanged, "Test", "counter_slider", int) widget.show() widget.setWindowTitle("Test Qt Range") diff --git a/gr-qtgui/python/qtgui/togglebutton.py b/gr-qtgui/python/qtgui/togglebutton.py index 99358cd0e4..cfa0f91d33 100644 --- a/gr-qtgui/python/qtgui/togglebutton.py +++ b/gr-qtgui/python/qtgui/togglebutton.py @@ -14,6 +14,7 @@ from PyQt5 import Qt from gnuradio import gr import pmt + class ToggleButton(gr.sync_block, Qt.QPushButton): """ This block creates a variable toggle button. Leave the label @@ -24,8 +25,10 @@ class ToggleButton(gr.sync_block, Qt.QPushButton): or released. This button will also produce a state message matching the set values. """ + def __init__(self, callback, lbl, pressedReleasedDict, initPressed, outputmsgname='value'): - gr.sync_block.__init__(self, name="ToggleButton", in_sig=None, out_sig=None) + gr.sync_block.__init__(self, name="ToggleButton", + in_sig=None, out_sig=None) Qt.QPushButton.__init__(self, lbl) self.setCheckable(True) self.lbl = lbl @@ -89,34 +92,34 @@ class ToggleButton(gr.sync_block, Qt.QPushButton): if pressed: if type(self.pressReleasedDict['Pressed']) == bool: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_bool(self.pressReleasedDict['Pressed']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_bool(self.pressReleasedDict['Pressed']))) elif type(self.pressReleasedDict['Pressed']) == int: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_long(self.pressReleasedDict['Pressed']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_long(self.pressReleasedDict['Pressed']))) elif type(self.pressReleasedDict['Pressed']) == float: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_double(self.pressReleasedDict['Pressed']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_double(self.pressReleasedDict['Pressed']))) else: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.intern(self.pressReleasedDict['Pressed']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.intern(self.pressReleasedDict['Pressed']))) else: if type(self.pressReleasedDict['Released']) == bool: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_bool(self.pressReleasedDict['Released']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_bool(self.pressReleasedDict['Released']))) elif type(self.pressReleasedDict['Released']) == int: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_long(self.pressReleasedDict['Released']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_long(self.pressReleasedDict['Released']))) elif type(self.pressReleasedDict['Released']) == float: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_double(self.pressReleasedDict['Released']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_double(self.pressReleasedDict['Released']))) else: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.intern(self.pressReleasedDict['Released']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.intern(self.pressReleasedDict['Released']))) diff --git a/gr-qtgui/python/qtgui/toggleswitch.py b/gr-qtgui/python/qtgui/toggleswitch.py index a869e574de..ce57f907bb 100644 --- a/gr-qtgui/python/qtgui/toggleswitch.py +++ b/gr-qtgui/python/qtgui/toggleswitch.py @@ -17,13 +17,14 @@ from PyQt5.QtGui import QPainter, QBrush, QColor, QPen, QFontMetricsF from PyQt5.QtCore import Qt as Qtc from PyQt5.QtCore import QRect + class LabeledToggleSwitch(QFrame): # Positions: 1 = above, 2=below, 3=left, 4=right def __init__(self, lbl='', onColor='green', offColor='red', initialState=False, maxSize=50, position=1, parent=None, callback=None, alignment=1, valignment=1): QFrame.__init__(self, parent) self.numberControl = ToggleSwitch(onColor, offColor, initialState, maxSize, - parent, callback) + parent, callback) if position < 3: layout = QVBoxLayout() @@ -33,9 +34,9 @@ class LabeledToggleSwitch(QFrame): self.lbl = lbl self.lblcontrol = QLabel(lbl, self) - if position == 3: # left of switch + if position == 3: # left of switch self.lblcontrol.setAlignment(Qtc.AlignRight) - elif position == 4: # right of switch + elif position == 4: # right of switch self.lblcontrol.setAlignment(Qtc.AlignLeft) else: # Above or below @@ -74,8 +75,9 @@ class LabeledToggleSwitch(QFrame): textfont = self.lblcontrol.font() metrics = QFontMetricsF(textfont) - maxWidth = max((maxSize+4), (maxSize*2 + metrics.width(lbl))) - maxHeight = max((maxSize/2+4), (maxSize/2 + metrics.height()+2)) + maxWidth = max((maxSize + 4), (maxSize * 2 + metrics.width(lbl))) + maxHeight = max((maxSize / 2 + 4), + (maxSize / 2 + metrics.height() + 2)) self.setMinimumSize(int(maxWidth), int(maxHeight)) @@ -84,6 +86,7 @@ class LabeledToggleSwitch(QFrame): def setState(self, on_off): self.numberControl.setState(on_off) + class ToggleSwitch(QFrame): def __init__(self, onColor='green', offColor='red', initialState=False, maxSize=50, parent=None, callback=None): @@ -94,8 +97,8 @@ class ToggleSwitch(QFrame): self.onColor = QColor(onColor) self.offColor = QColor(offColor) self.callback = callback - self.setMinimumSize(maxSize, maxSize/2) - self.setMaximumSize(maxSize, maxSize/2) + self.setMinimumSize(maxSize, maxSize / 2) + self.setMaximumSize(maxSize, maxSize / 2) def setState(self, on_off): self.curState = on_off @@ -113,7 +116,7 @@ class ToggleSwitch(QFrame): size = self.size() brush = QBrush() - center_x = size.width()/2 + center_x = size.width() / 2 if self.curState: brush.setColor(self.onColor) @@ -126,38 +129,43 @@ class ToggleSwitch(QFrame): painter.setBrush(brush) # Draw the switch background - centerRect = QRect(size.width()/4, 0, size.width()/2-4, size.height()) + centerRect = QRect(size.width() / 4, 0, + size.width() / 2 - 4, size.height()) painter.drawRect(centerRect) painter.drawEllipse(0, 0, size.height(), size.height()) - painter.drawEllipse(size.width()/2, 0, size.height(), size.height()) + painter.drawEllipse(size.width() / 2, 0, size.height(), size.height()) # Draw the switch itself brush.setColor(QColor('white')) painter.setBrush(brush) painter.setPen(QPen(QColor('white'), 0)) if self.curState: - painter.drawEllipse(center_x+2, 2, size.height() - 4, size.height() - 4) + painter.drawEllipse( + center_x + 2, 2, size.height() - 4, size.height() - 4) else: painter.drawEllipse(2, 2, size.height() - 4, size.height() - 4) def mousePressEvent(self, event): - if event.x() <= self.size().width()/2: + if event.x() <= self.size().width() / 2: self.setState(False) else: self.setState(True) super().update() + class GrToggleSwitch(gr.sync_block, LabeledToggleSwitch): """ This block creates a modern toggle switch. The variable will take on one value or the other as set in the dialog. This button will also produce a state message matching the set values. """ + def __init__(self, callback, lbl, pressedReleasedDict, initialState=False, onColor='green', offColor='silver', position=3, maxSize=50, alignment=1, valignment=1, parent=None, outputmsgname='value'): - gr.sync_block.__init__(self, name="ToggleSwitch", in_sig=None, out_sig=None) + gr.sync_block.__init__(self, name="ToggleSwitch", + in_sig=None, out_sig=None) LabeledToggleSwitch.__init__(self, lbl, onColor, offColor, initialState, maxSize, position, parent, self.notifyUpdate, alignment, valignment) @@ -177,34 +185,34 @@ class GrToggleSwitch(gr.sync_block, LabeledToggleSwitch): if new_val: if type(self.pressReleasedDict['Pressed']) == bool: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_bool(self.pressReleasedDict['Pressed']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_bool(self.pressReleasedDict['Pressed']))) elif type(self.pressReleasedDict['Pressed']) == int: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_long(self.pressReleasedDict['Pressed']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_long(self.pressReleasedDict['Pressed']))) elif type(self.pressReleasedDict['Pressed']) == float: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_double(self.pressReleasedDict['Pressed']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_double(self.pressReleasedDict['Pressed']))) else: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.intern(self.pressReleasedDict['Pressed']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.intern(self.pressReleasedDict['Pressed']))) else: if type(self.pressReleasedDict['Released']) == bool: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_bool(self.pressReleasedDict['Released']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_bool(self.pressReleasedDict['Released']))) elif type(self.pressReleasedDict['Released']) == int: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_long(self.pressReleasedDict['Released']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_long(self.pressReleasedDict['Released']))) elif type(self.pressReleasedDict['Released']) == float: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.from_double(self.pressReleasedDict['Released']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.from_double(self.pressReleasedDict['Released']))) else: self.message_port_pub(pmt.intern("state"), - pmt.cons(pmt.intern(self.outputmsgname), - pmt.intern(self.pressReleasedDict['Released']))) + pmt.cons(pmt.intern(self.outputmsgname), + pmt.intern(self.pressReleasedDict['Released']))) diff --git a/gr-qtgui/python/qtgui/util.py.cmakein b/gr-qtgui/python/qtgui/util.py.cmakein index 1eb0699938..cdf90608db 100644 --- a/gr-qtgui/python/qtgui/util.py.cmakein +++ b/gr-qtgui/python/qtgui/util.py.cmakein @@ -15,9 +15,9 @@ from gnuradio import gr def check_set_qss(): app = QtWidgets.qApp - qssfile = gr.prefs().get_string("qtgui","qss","") - if(len(qssfile)>0): + qssfile = gr.prefs().get_string("qtgui", "qss", "") + if(len(qssfile) > 0): try: app.setStyleSheet(open(qssfile).read()) except: - print("WARNING: bad QSS file, %s"%(qssfile)) + print("WARNING: bad QSS file, %s" % (qssfile)) |