def __init__(self, *args): QWidget.__init__(self, *args) lo = QHBoxLayout(self) lo.setContentsMargins(0, 0, 0, 0) lo.setSpacing(5) # type selector self.wtypesel = QComboBox(self) for i, tp in enumerate(self.ValueTypes): self.wtypesel.addItem(tp.__name__) self.wtypesel.activated[int].connect(self._selectTypeNum) typesel_lab = QLabel("&Type:", self) typesel_lab.setBuddy(self.wtypesel) lo.addWidget(typesel_lab, 0) lo.addWidget(self.wtypesel, 0) self.wvalue = QLineEdit(self) self.wvalue_lab = QLabel("&Value:", self) self.wvalue_lab.setBuddy(self.wvalue) self.wbool = QComboBox(self) self.wbool.addItems(["false", "true"]) self.wbool.setCurrentIndex(1) lo.addWidget(self.wvalue_lab, 0) lo.addWidget(self.wvalue, 1) lo.addWidget(self.wbool, 1) self.wvalue.hide() # make input validators self._validators = {int: QIntValidator(self), float: QDoubleValidator(self)} # select bool type initially self._selectTypeNum(0)
def get_search_widget(self): """ Create and return the search QWidget :return: search QWidget :rtype: QWidget """ widget = QWidget() layout = QHBoxLayout() layout.setSpacing(0) widget.setLayout(layout) # Search label search_lbl = QLabel(_('Search Host')) search_lbl.setObjectName('bordertitle') search_lbl.setFixedHeight(25) search_lbl.setToolTip(_('Search Host')) layout.addWidget(search_lbl) # QLineEdit self.line_search.setFixedHeight(search_lbl.height()) layout.addWidget(self.line_search) self.create_line_search([]) return widget
def get_search_widget(self): """ Create and return the search QWidget :return: search QWidget :rtype: QWidget """ widget = QWidget() layout = QHBoxLayout() layout.setSpacing(0) layout.setContentsMargins(5, 20, 5, 10) widget.setLayout(layout) # Search label search_lbl = QLabel(_('Search Problems')) search_lbl.setObjectName('bordertitle') search_lbl.setFixedHeight(25) search_lbl.setToolTip(_('Search Problems')) layout.addWidget(search_lbl) # QLineEdit self.line_search.setFixedHeight(search_lbl.height()) self.line_search.setPlaceholderText(_('Type text to filter problems...')) layout.addWidget(self.line_search) # Refresh button refresh_btn = QPushButton(_('Refresh')) refresh_btn.setObjectName('ok') refresh_btn.setFixedSize(120, search_lbl.height()) refresh_btn.setToolTip(_('Refresh problems')) refresh_btn.clicked.connect(self.update_problems_data) layout.addWidget(refresh_btn) return widget
def get_search_widget(self): """ Create and return the search QWidget :return: search QWidget :rtype: QWidget """ widget = QWidget() layout = QHBoxLayout() layout.setSpacing(0) widget.setLayout(layout) # Search label search_lbl = QLabel(_('Search Host')) search_lbl.setObjectName('bordertitle') search_lbl.setFixedHeight(25) search_lbl.setToolTip(_('Search Host')) layout.addWidget(search_lbl) # QLineEdit self.line_search.setFixedHeight(search_lbl.height()) layout.addWidget(self.line_search) self.create_line_search([]) return widget
class _HomeTab(QWidget): """Home tab which contains information about EvilOSX.""" def __init__(self): super().__init__() self._layout = QHBoxLayout() self.setLayout(self._layout) message_label = QLabel("""\ Welcome to <b>EvilOSX</b>:<br/> An evil RAT (Remote Administration Tool) for macOS / OS X.<br/><br/><br/> Author: Marten4n6<br/> License: GPLv3<br/> Version: <b>{}</b> """.format(VERSION)) logo_label = QLabel() logo_path = path.join(path.dirname(__file__), path.pardir, path.pardir, "data", "images", "logo_334x600.png") logo_label.setPixmap(QPixmap(logo_path)) self._layout.setAlignment(Qt.AlignCenter) self._layout.setSpacing(50) self._layout.addWidget(message_label) self._layout.addWidget(logo_label)
def __init__(self, *args): QFrame.__init__(self, *args) self.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken) self.edit = QTextBrowser() self.edit.setFrameStyle(QFrame.NoFrame) self.number_bar = self.NumberBar() self.number_bar.setTextEdit(self.edit) hbox = QHBoxLayout(self) hbox.setSpacing(0) margins = QMargins(0, 0, 0, 0) hbox.setContentsMargins(margins) hbox.addWidget(self.number_bar) hbox.addWidget(self.edit) self.edit.installEventFilter(self) self.edit.viewport().installEventFilter(self) config = Config() style_str = config.array_config_str('log_line_number_style') self.setStyleSheet(style_str)
def __init__(self, parent, label, filename=None, dialog_label=None, file_types=None, default_suffix=None, file_mode=QFileDialog.AnyFile): QWidget.__init__(self, parent) lo = QHBoxLayout(self) lo.setContentsMargins(0, 0, 0, 0) lo.setSpacing(5) # label lab = QLabel(label, self) lo.addWidget(lab, 0) # text field self.wfname = QLineEdit(self) self.wfname.setReadOnly(True) self.setFilename(filename) lo.addWidget(self.wfname, 1) # selector wsel = QToolButton(self) wsel.setText("Choose...") wsel.clicked.connect(self._chooseFile) lo.addWidget(wsel, 0) # other init self._file_dialog = None self._dialog_label = dialog_label or label self._file_types = file_types or "All files (*)" self._file_mode = file_mode self._default_suffix = default_suffix self._dir = None
def _set_common_top_ui(self): top_frame = QFrame() top_frame.setMaximumHeight(60) top_layout = QVBoxLayout(top_frame) self.layout.addWidget(top_frame) common_top_frame = QFrame() common_top_frame.setMinimumHeight(50) common_top_frame.setMaximumHeight(50) common_top_layout = QHBoxLayout(common_top_frame) top_layout.addWidget(common_top_frame) common_top_layout.addStretch(0) label = QLabel(i18n[self.lang]['Type'] + ':') self.label_type = QLabel('') self.label_type.setStyleSheet('''color: gray;font:bold;''') common_top_layout.addWidget(label) common_top_layout.addWidget(self.label_type) label = QLabel(i18n[self.lang]['Mode'] + ':') self.label_mode = QLabel('') self.label_mode.setStyleSheet('''color: gray;font:bold;''') common_top_layout.addWidget(label) common_top_layout.addWidget(self.label_mode) label = QLabel(i18n[self.lang]['HardwareVersion'] + ':') self.label_hard_version = QLabel('') self.label_hard_version.setStyleSheet('''color: gray;font:bold;''') common_top_layout.addWidget(label) common_top_layout.addWidget(self.label_hard_version) label = QLabel(i18n[self.lang]['FirmwareVersion'] + ':') self.label_firm_version = QLabel('') self.label_firm_version.setStyleSheet('''color: gray;font:bold;''') common_top_layout.addWidget(label) common_top_layout.addWidget(self.label_firm_version) label_1 = QLabel(i18n[self.lang]['Connected'] + ':') self.label_connected = QLabel() img = QImage() self.label_connected.setMaximumHeight(20) self.label_connected.setMaximumWidth(20) self.label_connected.setScaledContents(True) if img.load(disconnect_icon_path): self.label_connected.setPixmap(QPixmap.fromImage(img)) self.lnt_addr = QLineEdit('COM12') self.lnt_addr.setMaximumWidth(50) self.lnt_addr.setMinimumWidth(30) self.btn_connect = QPushButton(i18n[self.lang]['Connect']) # self.btn_connect.setMaximumWidth(50) # common_top_layout.addStretch(0) common_top_layout.setSpacing(10) common_top_layout.addWidget(label_1) common_top_layout.addWidget(self.label_connected) common_top_layout.addWidget(self.lnt_addr) common_top_layout.addWidget(self.btn_connect)
def createArduinoCalibrationControls(): gb = QGroupBox("Arduino Calibration") vbox = QVBoxLayout() #------------------------------------------- layout = QHBoxLayout() label = QLabel("Set current position as:") lineEdit = QLineEdit() degreesLabel = QLabel("deg") set_btn = QPushButton("Set") lineEdit.setMaximumWidth(30) set_btn.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) set_btn.clicked.connect(lambda: send_cmd(["=" + lineEdit.displayText()])) layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(label) layout.addWidget(lineEdit) layout.addWidget(degreesLabel) layout.addWidget(set_btn) upper = QWidget() upper.setLayout(layout) #------------------------------------------- layout = QHBoxLayout() btn0 = QPushButton("Set as 0") btn180 = QPushButton("Set as 180") btn0.clicked.connect(lambda: send_cmd(["=0"])) btn180.clicked.connect(lambda: send_cmd(["=180"])) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(0) layout.addWidget(btn0) layout.addWidget(btn180) layout.addStretch(1) lower = QWidget() lower.setLayout(layout) #------------------------------------------- vbox.setContentsMargins(0, 0, 0, 0) vbox.setSpacing(0) vbox.addWidget(upper) vbox.addWidget(lower) gb.setLayout(vbox) return gb
def make_labelled(parent, label: str, widget: QWidget): """Put a widget into a container with a label to the left of it. Like a single row of a `QFormLayout`""" container = QWidget(parent) label_widget = QLabel(label) layout = QHBoxLayout(container) layout.setSpacing(0) layout.addWidget(label_widget) layout.addWidget(widget) layout.setContentsMargins(0, 0, 0, 0) return container
def __init__(self, parent): QWidget.__init__(self, parent) layout = QHBoxLayout() layout.setSpacing(5) layout.setContentsMargins(0, 0, 0, 0) self.tags_box = EditWithComplete(parent) layout.addWidget(self.tags_box, stretch=1000) self.editor_button = QToolButton(self) self.editor_button.setToolTip(_('Open Item Editor')) self.editor_button.setIcon(QIcon(I('chapters.png'))) layout.addWidget(self.editor_button) self.setLayout(layout)
def __init__(self, parent, values): QWidget.__init__(self, parent) layout = QHBoxLayout() layout.setSpacing(5) layout.setContentsMargins(0, 0, 0, 0) self.tags_box = EditWithComplete(parent) self.tags_box.update_items_cache(values) layout.addWidget(self.tags_box, stretch=3) self.checkbox = QCheckBox(_('Remove all tags'), parent) layout.addWidget(self.checkbox) layout.addStretch(1) self.setLayout(layout) self.checkbox.stateChanged[int].connect(self.box_touched)
class windowTitle(QFrame): def __init__(self, parent, closeButton=True): QFrame.__init__(self, parent) self.setMaximumSize(QSize(9999999, 22)) self.setObjectName("windowTitle") self.hboxlayout = QHBoxLayout(self) self.hboxlayout.setSpacing(0) self.hboxlayout.setContentsMargins(0, 0, 4, 0) self.label = QLabel(self) self.label.setObjectName("label") self.label.setStyleSheet( "padding-left:4px; font:bold 11px; color: #FFFFFF;") self.hboxlayout.addWidget(self.label) spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.hboxlayout.addItem(spacerItem) if closeButton: self.pushButton = QPushButton(self) self.pushButton.setFocusPolicy(Qt.NoFocus) self.pushButton.setObjectName("pushButton") self.pushButton.setStyleSheet("font:bold;") self.pushButton.setText("X") self.hboxlayout.addWidget(self.pushButton) self.dragPosition = None self.mainwidget = self.parent() self.setStyleSheet(""" QFrame#windowTitle {background-color:#222222;color:#FFF;} """) # Initial position to top left self.dragPosition = self.mainwidget.frameGeometry().topLeft() def mousePressEvent(self, event): if event.button() == Qt.LeftButton: self.dragPosition = event.globalPos( ) - self.mainwidget.frameGeometry().topLeft() event.accept() def mouseMoveEvent(self, event): if event.buttons() & Qt.LeftButton: self.mainwidget.move(event.globalPos() - self.dragPosition) event.accept()
def initialize(self, child_widget, title, exitapp): """ Initialize QWidget :param child_widget: widget child of LogoQWidget, needed for action button and layout :type child_widget: QWidget :param title: title of widget :type title: str :param exitapp: define if close button close application or just child QWidget :type exitapp: bool """ self.child_widget = child_widget logo_layout = QHBoxLayout() self.setLayout(logo_layout) logo_label = QLabel() logo_label.setObjectName('widget_title') logo_label.setText('%s' % title) logo_layout.addWidget(logo_label, 0) logo_layout.addStretch(child_widget.width()) logo_layout.setSpacing(0) minimize_btn = QPushButton() minimize_btn.setIcon(QIcon(settings.get_image('minimize'))) minimize_btn.setFixedSize(24, 24) minimize_btn.setObjectName('app_widget') minimize_btn.clicked.connect(self.minimize) logo_layout.addWidget(minimize_btn, 1) maximize_btn = QPushButton() maximize_btn.setIcon(QIcon(settings.get_image('maximize'))) maximize_btn.setFixedSize(24, 24) maximize_btn.setObjectName('app_widget') maximize_btn.clicked.connect(self.minimize_maximize) logo_layout.addWidget(maximize_btn, 2) close_btn = QPushButton() close_btn.setIcon(QIcon(settings.get_image('exit'))) close_btn.setObjectName('app_widget') close_btn.setFixedSize(24, 24) if exitapp: close_btn.clicked.connect(sys.exit) else: close_btn.clicked.connect(child_widget.close) logo_layout.addWidget(close_btn, 3)
def initialize(self, child_widget, title, exitapp): """ Initialize QWidget :param child_widget: widget child of LogoQWidget, needed for action button and layout :type child_widget: QWidget :param title: title of widget :type title: str :param exitapp: define if close button close application or just child QWidget :type exitapp: bool """ self.child_widget = child_widget logo_layout = QHBoxLayout() self.setLayout(logo_layout) logo_label = QLabel() logo_label.setObjectName('widget_title') logo_label.setText('%s' % title) logo_layout.addWidget(logo_label, 0) logo_layout.addStretch(child_widget.width()) logo_layout.setSpacing(0) minimize_btn = QPushButton() minimize_btn.setIcon(QIcon(settings.get_image('minimize'))) minimize_btn.setFixedSize(24, 24) minimize_btn.setObjectName('app_widget') minimize_btn.clicked.connect(self.minimize) logo_layout.addWidget(minimize_btn, 1) maximize_btn = QPushButton() maximize_btn.setIcon(QIcon(settings.get_image('maximize'))) maximize_btn.setFixedSize(24, 24) maximize_btn.setObjectName('app_widget') maximize_btn.clicked.connect(self.minimize_maximize) logo_layout.addWidget(maximize_btn, 2) close_btn = QPushButton() close_btn.setIcon(QIcon(settings.get_image('exit'))) close_btn.setObjectName('app_widget') close_btn.setFixedSize(24, 24) if exitapp: close_btn.clicked.connect(sys.exit) else: close_btn.clicked.connect(child_widget.close) logo_layout.addWidget(close_btn, 3)
def __init__(self, parent, label, extra_widgets=[], style=QFrame.HLine + QFrame.Raised, offset=16): QWidget.__init__(self, parent) lo = QHBoxLayout(self) lo.setContentsMargins(0, 0, 0, 0) lo.setSpacing(4) if offset: frame = QFrame(self) frame.setFrameStyle(style) frame.setMinimumWidth(offset) lo.addWidget(frame, 0) lo.addWidget(QLabel(label, self), 0) frame = QFrame(self) frame.setFrameStyle(style) lo.addWidget(frame, 1) for w in extra_widgets: lo.addWidget(w, 0)
class windowTitle(QFrame): def __init__(self, parent, closeButton=True): QFrame.__init__(self, parent) self.setMaximumSize(QSize(9999999,22)) self.setObjectName("windowTitle") self.hboxlayout = QHBoxLayout(self) self.hboxlayout.setSpacing(0) self.hboxlayout.setContentsMargins(0,0,4,0) self.label = QLabel(self) self.label.setObjectName("label") self.label.setStyleSheet("padding-left:4px; font:bold 11px; color: #FFFFFF;") self.hboxlayout.addWidget(self.label) spacerItem = QSpacerItem(40,20,QSizePolicy.Expanding,QSizePolicy.Minimum) self.hboxlayout.addItem(spacerItem) if closeButton: self.pushButton = QPushButton(self) self.pushButton.setFocusPolicy(Qt.NoFocus) self.pushButton.setObjectName("pushButton") self.pushButton.setStyleSheet("font:bold;") self.pushButton.setText("X") self.hboxlayout.addWidget(self.pushButton) self.dragPosition = None self.mainwidget = self.parent() self.setStyleSheet(""" QFrame#windowTitle {background-color:#222222;color:#FFF;} """) # Initial position to top left self.dragPosition = self.mainwidget.frameGeometry().topLeft() def mousePressEvent(self, event): if event.button() == Qt.LeftButton: self.dragPosition = event.globalPos() - self.mainwidget.frameGeometry().topLeft() event.accept() def mouseMoveEvent(self, event): if event.buttons() & Qt.LeftButton: self.mainwidget.move(event.globalPos() - self.dragPosition) event.accept()
def createTableCollapse(self, text, func): collapseWidget = QWidget() hlayout = QHBoxLayout() collapseWidget.setLayout(hlayout) button = QPushButton('-') hlayout.setSpacing(10) button.clicked.connect(func) button.setFixedWidth(40) label = QLabel('<b style="font-size: 10pt">%s</b>' % text) hlayout.addWidget(button, 1) hlayout.addWidget(label, 20) return (button, collapseWidget)
def __init__(self, parent, values): QWidget.__init__(self, parent) layout = QHBoxLayout() layout.setSpacing(5) layout.setContentsMargins(0, 0, 0, 0) self.tags_box = EditWithComplete(parent) self.tags_box.update_items_cache(values) layout.addWidget(self.tags_box, stretch=3) self.remove_tags_button = QToolButton(parent) self.remove_tags_button.setToolTip(_('Open Item Editor')) self.remove_tags_button.setIcon(QIcon(I('chapters.png'))) layout.addWidget(self.remove_tags_button) self.checkbox = QCheckBox(_('Remove all tags'), parent) layout.addWidget(self.checkbox) layout.addStretch(1) self.setLayout(layout) self.checkbox.stateChanged[int].connect(self.box_touched)
def __init__(self, *args): QFrame.__init__(self, *args) self.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken) self.edit = QPlainTextEdit() self.edit.setFrameStyle(QFrame.NoFrame) self.number_bar = self.NumberBar() self.number_bar.setTextEdit(self.edit) hbox = QHBoxLayout(self) hbox.setSpacing(0) #hbox.setMargin(0) hbox.addWidget(self.number_bar) hbox.addWidget(self.edit) self.edit.installEventFilter(self) self.edit.viewport().installEventFilter(self)
def __init__(self, *args): QFrame.__init__(self, *args) self.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken) self.edit = self.PlainTextEdit() self.number_bar = self.NumberBar(self.edit) self.highlighterclass = None self.highlighter = None hbox = QHBoxLayout(self) hbox.setSpacing(0) hbox.setContentsMargins(0, 0, 0, 0) hbox.addWidget(self.number_bar) hbox.addWidget(self.edit) self.edit.blockCountChanged.connect(self.number_bar.adjustWidth) self.edit.updateRequest.connect(self.number_bar.updateContents)
def createMonitorControls(): gb = QGroupBox("Monitor") #------------------------------------------ layout = QHBoxLayout() label1 = QLabel("Angle:") label2 = QLabel("Half steps:") global angle_le angle_le = QLineEdit() global halfSteps_le halfSteps_le = QLineEdit() angle_le.setMaximumWidth(50) halfSteps_le.setMaximumWidth(50) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(5) layout.addWidget(label1) layout.addWidget(angle_le) layout.addWidget(label2) layout.addWidget(halfSteps_le) layout.addStretch() upper = QWidget() upper.setLayout(layout) #------------------------------------------ vbox = QVBoxLayout() vbox.addWidget(upper) vbox.addStretch(1) vbox.setContentsMargins(0, 0, 0, 0) vbox.setSpacing(0) gb.setLayout(vbox) return gb
def __init__(self, parent, modal=True, flags=Qt.WindowFlags()): QDialog.__init__(self, parent, flags) self.setModal(modal) self.setWindowTitle("Add Tag") lo = QVBoxLayout(self) lo.setContentsMargins(10, 10, 10, 10) lo.setSpacing(5) # tag selector lo1 = QHBoxLayout() lo.addLayout(lo1) lo1.setSpacing(5) self.wtagsel = QComboBox(self) self.wtagsel.setEditable(True) wtagsel_lbl = QLabel("&Tag:", self) wtagsel_lbl.setBuddy(self.wtagsel) lo1.addWidget(wtagsel_lbl, 0) lo1.addWidget(self.wtagsel, 1) self.wtagsel.activated[int].connect(self._check_tag) self.wtagsel.editTextChanged['QString'].connect(self._check_tag_text) # value editor self.valedit = ValueTypeEditor(self) lo.addWidget(self.valedit) # buttons lo.addSpacing(10) lo2 = QHBoxLayout() lo.addLayout(lo2) lo2.setContentsMargins(0, 0, 0, 0) lo2.setContentsMargins(5, 5, 5, 5) self.wokbtn = QPushButton("OK", self) self.wokbtn.setMinimumWidth(128) self.wokbtn.clicked.connect(self.accept) self.wokbtn.setEnabled(False) cancelbtn = QPushButton("Cancel", self) cancelbtn.setMinimumWidth(128) cancelbtn.clicked.connect(self.reject) lo2.addWidget(self.wokbtn) lo2.addStretch(1) lo2.addWidget(cancelbtn) self.setMinimumWidth(384)
def __init__(self, cur_pos_label, *args): QFrame.__init__(self, *args) self.setFrameStyle(QFrame.StyledPanel | QFrame.Sunken) self.edit = QTextEdit() self.edit.setFrameStyle(QFrame.NoFrame) self.edit.setAcceptRichText(False) self.edit.cursorPositionChanged.connect(self.cursorPositionChanged) self.number_bar = NumberBar() self.number_bar.setTextEdit(self.edit) hbox = QHBoxLayout(self) hbox.setSpacing(0) hbox.setContentsMargins(0, 0, 0, 0) hbox.addWidget(self.number_bar) hbox.addWidget(self.edit) self.edit.installEventFilter(self) self.edit.viewport().installEventFilter(self) self.cur_pos_label = cur_pos_label
def get_search_widget(self): """ Create and return the search QWidget :return: search QWidget :rtype: QWidget """ widget = QWidget() layout = QHBoxLayout() layout.setSpacing(0) layout.setContentsMargins(5, 20, 5, 10) widget.setLayout(layout) # Search label search_lbl = QLabel(_('Search Problems')) search_lbl.setObjectName('bordertitle') search_lbl.setFixedHeight(25) search_lbl.setToolTip(_('Search Problems')) layout.addWidget(search_lbl) # QLineEdit self.line_search.setFixedHeight(search_lbl.height()) self.line_search.setPlaceholderText( _('Type text to filter problems...')) layout.addWidget(self.line_search) # Refresh button refresh_btn = QPushButton(_('Refresh')) refresh_btn.setObjectName('ok') refresh_btn.setFixedSize(120, search_lbl.height()) refresh_btn.setToolTip(_('Refresh problems')) refresh_btn.clicked.connect(self.update_problems_data) layout.addWidget(refresh_btn) return widget
class InformationWindow(QWidget): def __init__(self): QWidget.__init__(self, ctx.mainScreen) self.setObjectName("InformationWindow") self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.setFixedHeight(50) self.setMaximumWidth(800) self.setStyleSheet(""" QFrame#frame { border: 1px solid rgba(255,255,255,30); /*border-radius: 4px;*/ background-color: rgba(0,0,0,100);} QLabel { border:none; color:#FFFFFF;} QProgressBar { border: 1px solid white;} QProgressBar::chunk { background-color: #F1610D; width: 0.5px;} """) self.gridlayout = QGridLayout(self) self.frame = QFrame(self) self.frame.setObjectName("frame") self.horizontalLayout = QHBoxLayout(self.frame) self.horizontalLayout.setContentsMargins(10, 0, 10, 0) # Spinner self.spinner = QLabel(self.frame) self.spinner.setMinimumSize(QSize(16, 16)) self.spinner.setMaximumSize(QSize(16, 16)) self.spinner.setIndent(6) self.movie = QMovie(':/images/working.mng') self.spinner.setMovie(self.movie) self.movie.start() self.horizontalLayout.addWidget(self.spinner) # Message self.label = QLabel(self.frame) self.label.setAlignment(Qt.AlignCenter) self.label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.icon = QLabel(self.frame) self.icon.setFixedWidth(16) self.icon.setFixedHeight(16) self.horizontalLayout.setSpacing(10) self.horizontalLayout.addWidget(self.icon) self.horizontalLayout.addWidget(self.label) self.gridlayout.addWidget(self.frame,0,0,1,1) def update(self, message, type=None, spinner=False): fontMetric = self.label.fontMetrics() textWidth = fontMetric.width(message) if type: self.icon.show() if type == "error": self.icon.setPixmap(QPixmap(":/gui/pics/dialog-error.png")) self.setStyleSheet(" QFrame#frame {background-color: rgba(255,0,0,100);} ") elif type == "warning": self.icon.setPixmap(QPixmap(":/gui/pics/dialog-warning.png")) self.setStyleSheet(" QFrame#frame {background-color: rgba(0,0,0,100);} ") self.setFixedWidth(textWidth + self.icon.width() + 50) self.label.setText(message) else: self.icon.hide() self.setStyleSheet(" QFrame#frame {background-color: rgba(0,0,0,100);} ") self.setFixedWidth(textWidth + self.icon.width() + 100) self.label.setText(message) self.spinner.setVisible(spinner) self.move(ctx.mainScreen.width()/2 - self.width()/2, ctx.mainScreen.height() - self.height()/2 - 50) self.show() def refresh(self): ctx.mainScreen.processEvents() def show(self): QWidget.show(self) self.refresh() def hide(self): QWidget.hide(self) self.refresh()
def _updateModel(self, what=SkyModel.UpdateAll, origin=None): if origin is self or not what & (SkyModel.UpdateTags | SkyModel.UpdateGroupStyle): return model = self.model self._setting_model = True # to ignore cellChanged() signals (in valueChanged()) # _item_cb is a dict (with row,col keys) containing the widgets (CheckBoxes ComboBoxes) per each cell self._item_cb = {} # lists of "list" and "plot" checkboxes per each grouping (excepting the default grouping); each entry is an (row,col,item) tuple. # used as argument to self._showControls() self._list_controls = [] self._plot_controls = [] # list of selection callbacks (to which signals are connected) self._callbacks = [] # set requisite number of rows,and start filling self.table.setRowCount(len(model.groupings)) for irow, group in enumerate(model.groupings): self.table.setItem(irow, 0, QTableWidgetItem(group.name)) if group is model.selgroup: self._irow_selgroup = irow # total # source in group: skip for "current" if group is not model.curgroup: self.table.setItem(irow, 1, QTableWidgetItem(str(group.total))) # selection controls: skip for current and selection if group not in (model.curgroup, model.selgroup): btns = QWidget() lo = QHBoxLayout(btns) lo.setContentsMargins(0, 0, 0, 0) lo.setSpacing(0) # make selector buttons (depending on which group we're in) if group is model.defgroup: Buttons = (("+", lambda src, grp=group: True, "select all sources"), ("-", lambda src, grp=group: False, "unselect all sources")) else: Buttons = ( ("=", lambda src, grp=group: grp.func(src), "select only this grouping"), ("+", lambda src, grp=group: src.selected or grp.func(src), "add grouping to selection"), ("-", lambda src, grp=group: src.selected and not grp. func(src), "remove grouping from selection"), ("&&", lambda src, grp=group: src.selected and grp.func(src), "intersect selection with grouping")) lo.addStretch(1) for label, predicate, tooltip in Buttons: btn = QToolButton(btns) btn.setText(label) btn.setMinimumWidth(24) btn.setMaximumWidth(24) btn.setToolTip(tooltip) lo.addWidget(btn) # add callback btn.clicked.connect( self._currier.curry(self.selectSources, predicate)) lo.addStretch(1) self.table.setCellWidget(irow, 2, btns) # "list" checkbox (not for current and selected groupings: these are always listed) if group not in (model.curgroup, model.selgroup): item = self._makeCheckItem("", group, "show_list") self.table.setItem(irow, self.ColList, item) item.setToolTip( """<P>If checked, sources in this grouping will be listed in the source table. If un-checked, sources will be excluded from the table. If partially checked, then the default list/no list setting of "all sources" will be in effect. </P>""") # "plot" checkbox (not for the current grouping, since that's always plotted) if group is not model.curgroup: item = self._makeCheckItem("", group, "show_plot") self.table.setItem(irow, self.ColPlot, item) item.setToolTip( """<P>If checked, sources in this grouping will be included in the plot. If un-checked, sources will be excluded from the plot. If partially checked, then the default plot/no plot setting of "all sources" will be in effect. </P>""") # custom style control # for default, current and selected, this is just a text label if group is model.defgroup: item = QTableWidgetItem("default:") item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter) item.setToolTip( """<P>This is the default plot style used for all sources for which a custom grouping style is not selected.</P>""" ) self.table.setItem(irow, self.ColApply, item) elif group is model.curgroup: item = QTableWidgetItem("") item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter) item.setToolTip( """<P>This is the plot style used for the highlighted source, if any.</P>""" ) self.table.setItem(irow, self.ColApply, item) elif group is model.selgroup: item = QTableWidgetItem("") item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter) item.setToolTip( """<P>This is the plot style used for the currently selected sources.</P>""" ) self.table.setItem(irow, self.ColApply, item) # for the rest, a combobox with custom priorities else: cb = QComboBox() cb.addItems(["default"] + ["custom %d" % p for p in range(1, 10)]) index = max(0, min(group.style.apply, 9)) # dprint(0,group.name,"apply",index) cb.setCurrentIndex(index) cb.activated[int].connect( self._currier.xcurry(self._valueChanged, (irow, self.ColApply))) self.table.setCellWidget(irow, self.ColApply, cb) cb.setToolTip( """<P>This controls whether sources within this group are plotted with a customized plot style. Customized styles have numeric priority; if a source belongs to multiple groups, then the style with the lowest priority takes precedence.<P>""") # attribute comboboxes for icol, attr in self.AttrByCol.items(): # get list of options for this style attribute. If dealing with first grouping (i==0), which is # the "all sources" grouping, then remove the "default" option (which is always first in the list) options = PlotStyles.StyleAttributeOptions[attr] if irow == 0: options = options[1:] # make combobox cb = QComboBox() cb.addItems(list(map(str, options))) # the "label" option is also editable if attr == "label": cb.setEditable(True) try: index = options.index(getattr(group.style, attr)) cb.setCurrentIndex(index) except ValueError: cb.setEditText(str(getattr(group.style, attr))) slot = self._currier.xcurry(self._valueChanged, (irow, icol)) cb.activated[int].connect(slot) cb.editTextChanged['QString'].connect(slot) cb.setEnabled(group is model.defgroup or group.style.apply) self.table.setCellWidget(irow, icol, cb) label = attr if irow: cb.setToolTip( """<P>This is the %s used to plot sources in this group, when a "custom" style for the group is enabled via the style control.<P>""" % label) else: cb.setToolTip( "<P>This is the default %s used for all sources for which a custom style is not specified below.<P>" % label) self.table.resizeColumnsToContents() # re-enable processing of cellChanged() signals self._setting_model = False
class BookmarksToolbar(QWidget): def __init__(self, window, parent=None): ''' @param: window BrowserWindow @param: parent QWidget ''' super().__init__(parent) self._window = window self._bookmarks = gVar.app.bookmarks() # Bookmarks self._clickedBookmark = None # BookmarkItem self._layout = None # QHBoxLayout self._updateTimer = None # QTimer self._actShowOnlyIcons = None # QAction self._actShowOnlyText = None # QAction self._dropRow = -1 self._dropPos = QPoint() self.setObjectName('bookmarksbar') self.setAcceptDrops(True) self.setContextMenuPolicy(Qt.CustomContextMenu) self._layout = QHBoxLayout(self) margin = self.style().pixelMetric(QStyle.PM_ToolBarItemMargin, None, self) + \ self.style().pixelMetric(QStyle.PM_ToolBarFrameWidth, None, self) self._layout.setContentsMargins(margin, margin, margin, margin) self._layout.setSpacing(self.style().pixelMetric( QStyle.PM_ToolBarItemSpacing, None, self)) self.setLayout(self._layout) self._updateTimer = QTimer(self) self._updateTimer.setInterval(300) self._updateTimer.setSingleShot(True) self._updateTimer.timeout.connect(self._refresh) self._bookmarks.bookmarkAdded.connect(self._bookmarksChanged) self._bookmarks.bookmarkRemoved.connect(self._bookmarksChanged) self._bookmarks.bookmarkChanged.connect(self._bookmarksChanged) self._bookmarks.showOnlyIconsInToolbarChanged.connect( self._showOnlyIconsChanged) self._bookmarks.showOnlyTextInToolbarChanged.connect( self._showOnlyTextChanged) self.customContextMenuRequested.connect(self._contextMenuRequested) self._refresh() # private Q_SLOTS: def _contextMenuRequested(self, pos): ''' @param: pos QPoint ''' # BookmarksToolbarButton button = self._buttonAt(pos) if button: self._clickedBookmark = button.bookmark() else: self._clickedBookmark = None menu = QMenu() actNewTab = menu.addAction(IconProvider.newTabIcon(), _('Open in new tab')) actNewWindow = menu.addAction(IconProvider.newWindowIcon(), _('Open in new window')) actNewPrivateWindow = menu.addAction( IconProvider.privateBrowsingIcon(), _('Open in new private window')) menu.addSeparator() actEdit = menu.addAction(_('Edit')) actDelete = menu.addAction(QIcon.fromTheme('edit-delete'), _('Delete')) menu.addSeparator() self._actShowOnlyIcons = menu.addAction(_('Show Only Icons')) self._actShowOnlyIcons.setCheckable(True) self._actShowOnlyIcons.setChecked( self._bookmarks.showOnlyIconsInToolbar()) self._actShowOnlyIcons.toggled.connect(self._showOnlyIconsChanged) self._actShowOnlyText = menu.addAction(_('Show Only Text')) self._actShowOnlyText.setCheckable(True) self._actShowOnlyText.setChecked( self._bookmarks.showOnlyTextInToolbar()) self._actShowOnlyText.toggled.connect(self._showOnlyTextChanged) actNewTab.triggered.connect(self._openBookmarkInNewTab) actNewWindow.triggered.connect(self._openBookmarkInNewWindow) actNewPrivateWindow.triggered.connect( self._openBookmarkInNewPrivateWindow) actEdit.triggered.connect(self._editBookmark) actDelete.triggered.connect(self._deleteBookmark) canBeModify = self._clickedBookmark and self._bookmarks.canBeModified( self._clickedBookmark) actEdit.setEnabled(canBeModify) actDelete.setEnabled(canBeModify) canOpen = self._clickedBookmark and self._clickedBookmark.isUrl() actNewTab.setEnabled(canOpen) actNewWindow.setEnabled(canOpen) actNewPrivateWindow.setEnabled(canOpen) menu.exec_(self.mapToGlobal(pos)) if button: # Clear mouse over state after closing menu button.update() self._clickedBookmark = None self._actShowOnlyIcons = None self._actShowOnlyText = None def _refresh(self): self._clear() folder = gVar.app.bookmarks().toolbarFolder() for child in folder.children(): self._addItem(child) self._layout.addStretch() def _bookmarksChanged(self): self._updateTimer.start() def _showOnlyIconsChanged(self, state): if state and self._actShowOnlyText: self._actShowOnlyText.setChecked(False) for idx in range(self._layout.count()): # BookmarksToolbarButton btn = self._layout.itemAt(idx).widget() if isinstance(btn, BookmarksToolbarButton): btn.setShowOnlyIcon(state) def _showOnlyTextChanged(self, state): if state and self._actShowOnlyIcons: self._actShowOnlyIcons.setChecked(False) for idx in range(self._layout.count()): # BookmarksToolbarButton btn = self._layout.itemAt(idx).widget() if isinstance(btn, BookmarksToolbarButton): btn.setShowOnlyText(state) def _openBookmarkInNewTab(self): if self._clickedBookmark: BookmarksTools.openBookmarkInNewTab(self._window, self._clickedBookmark) def _openBookmarkInNewWindow(self): if self._clickedBookmark: BookmarksTools.openBookmarkInNewWindow(self._clickedBookmark) def _openBookmarkInNewPrivateWindow(self): if self._clickedBookmark: BookmarksTools.openBookmarkInNewPrivateWindow( self._clickedBookmark) def _editBookmark(self): if self._clickedBookmark: BookmarksTools.editBookmarkDialog(self, self._clickedBookmark) self._bookmarks.changeBookmark(self._clickedBookmark) def _deleteBookmark(self): if self._clickedBookmark: self._bookmarks.removeBookmark(self._clickedBookmark) # private: def _clear(self): for idx in range(self._layout.count()): item = self._layout.takeAt(0) widget = item.widget() if widget: widget.setParent(None) widget.deleteLater() assert (self._layout.isEmpty()) def _addItem(self, item): ''' @param: BookmarkItem ''' assert (item) button = BookmarksToolbarButton(item, self) button.setMainWindow(self._window) button.setShowOnlyIcon(self._bookmarks.showOnlyIconsInToolbar()) button.setShowOnlyText(self._bookmarks.showOnlyTextInToolbar()) self._layout.addWidget(button) def _buttonAt(self, pos): ''' @param: pos QPoint @return: BookmarksToolbarButton ''' button = QApplication.widgetAt(self.mapToGlobal(pos)) if not isinstance(button, BookmarksToolbarButton): button = None return button # override def minimumSizeHint(self): size = super().minimumSizeHint() size.setHeight(max(20, size.height())) return size # override def dropEvent(self, event): ''' @param: event QDropEvent ''' row = self._dropRow self._clearDropIndicator() mime = event.mimeData() if not mime.hasUrls() and not mime.hasFormat( BookmarksButtonMimeData.mimeType()): super().dropEvent(event) return # BookmarkItem parent = self._bookmarks.toolbarFolder() bookmark = None if mime.hasFormat(BookmarksButtonMimeData.mimeType()): bookmarkMime = mime assert (isinstance(bookmarkMime, BookmarksButtonMimeData)) bookmark = bookmarkMime.item() initialIndex = bookmark.parent().children().index(bookmark) current = self._buttonAt(self._dropPos) if initialIndex < self._layout.indexOf(current): row -= 1 else: url = mime.urls()[0] if mime.hasText(): title = mime.text() else: title = url.toEncoded(QUrl.RemoveScheme) bookmark = BookmarkItem(BookmarkItem.Url) bookmark.setTitle(title) bookmark.setUrl(url) if row >= 0: self._bookmarks.insertBookmark(parent, row, bookmark) else: self._bookmarks.addBookmark(parent, bookmark) # override def dragEnterEvent(self, event): ''' @param: event QDragEnterEvent ''' mime = event.mimeData() if (mime.hasUrls() and mime.hasText()) or mime.hasFormat( BookmarksButtonMimeData.mimeType()): event.acceptProposedAction() return super().dragEnterEvent(event) # override def dragMoveEvent(self, event): ''' @param: event QDragMoveEvent ''' eventX = event.pos().x() # BoomarksToolbarButton button = self._buttonAt(event.pos()) self._dropPos = event.pos() self._dropRow = self._layout.indexOf(button) if button: if eventX - button.x() >= button.x() + button.width() - eventX: self._dropRow + 1 else: self._dropRow = -1 self.update() # override def dragLeaveEvent(self, event): ''' @param: event QDragLeaveEvent ''' self._clearDropIndicator() # override def paintEvent(self, event): ''' @param: event QPaintEvent ''' super().paintEvent(event) # Draw drop indicator if self._dropRow != -1: # BookmarksToolbarButton button = self._buttonAt(self._dropPos) if button: if button.bookmark().isFolder(): return tmpRect = QRect(button.x(), 0, button.width(), self.height()) rect = QRect() if self._dropRow == self._layout.indexOf(button): rect = QRect(max(0, tmpRect.left() - 2), tmpRect.top(), 3, tmpRect.height()) else: rect = QRect(tmpRect.right() + 0, tmpRect.top(), 3, tmpRect.height()) gVar.appTools.paintDropIndicator(self, rect) def _clearDropIndicator(self): self._dropRow = -1 self.update()
def _set_common_top_ui(self): top_frame = QFrame() top_frame.setMaximumHeight(60) top_layout = QVBoxLayout(top_frame) self.layout.addWidget(top_frame) common_top_frame = QFrame() common_top_frame.setMinimumHeight(50) common_top_layout = QHBoxLayout(common_top_frame) top_layout.addWidget(common_top_frame) label_1 = QLabel(i18n[self.lang]['Connected'] + ':') self.label_connected = QLabel() img = QImage() self.label_connected.setMaximumHeight(20) self.label_connected.setMaximumWidth(20) self.label_connected.setScaledContents(True) if img.load(disconnect_icon_path): self.label_connected.setPixmap(QPixmap.fromImage(img)) label_2 = QLabel(i18n[self.lang]['Reported'] + ':') self.label_reported = QLabel() img = QImage() self.label_reported.setMaximumHeight(20) self.label_reported.setMaximumWidth(20) self.label_reported.setScaledContents(True) if img.load(disconnect_icon_path): self.label_reported.setPixmap(QPixmap.fromImage(img)) self.lnt_addr = QLineEdit('192.168.1.182') self.lnt_addr.setMaximumWidth(100) self.lnt_addr.setMinimumWidth(60) self.btn_connect = QPushButton(i18n[self.lang]['Connect']) # self.btn_connect.setMaximumWidth(50) # common_top_layout.addStretch(0) common_top_layout.setSpacing(10) common_top_layout.addWidget(label_1) common_top_layout.addWidget(self.label_connected) common_top_layout.addWidget(label_2) common_top_layout.addWidget(self.label_reported) common_top_layout.addWidget(self.lnt_addr) common_top_layout.addWidget(self.btn_connect) # common_down_frame = QFrame() # common_down_layout = QHBoxLayout(common_down_frame) # common_down_layout.setSpacing(0) # top_layout.addWidget(common_down_frame) common_down_layout = common_top_layout label = QLabel(i18n[self.lang]['WarnCode'] + ':') self.label_warn_code = QLabel('0') self.label_warn_code.setStyleSheet('''color: gray;font:bold;''') common_down_layout.addWidget(label) common_down_layout.addWidget(self.label_warn_code) label = QLabel(i18n[self.lang]['ErrorCode'] + ':') self.label_error_code = QLabel('0') self.label_error_code.setStyleSheet('''color: gray;font:bold;''') common_down_layout.addWidget(label) common_down_layout.addWidget(self.label_error_code) label = QLabel(i18n[self.lang]['CmdCount'] + ':') self.label_cmd_count = QLabel('0') self.label_cmd_count.setStyleSheet('''color: gray;font:bold;''') common_down_layout.addWidget(label) common_down_layout.addWidget(self.label_cmd_count) label = QLabel(i18n[self.lang]['State'] + ':') self.label_state = QLabel('4') self.label_state.setStyleSheet('''color: gray;font:bold;''') common_down_layout.addWidget(label) common_down_layout.addWidget(self.label_state) label = QLabel(i18n[self.lang]['Maable'] + ':') self.label_maable = QLabel('128') self.label_maable.setStyleSheet('''color: gray;font:bold;''') common_down_layout.addWidget(label) common_down_layout.addWidget(self.label_maable) label = QLabel(i18n[self.lang]['Mtbrake'] + ':') self.label_mtbrake = QLabel('128') self.label_mtbrake.setStyleSheet('''color: gray;font:bold;''') common_down_layout.addWidget(label) common_down_layout.addWidget(self.label_mtbrake)
def __init__(self, parent, rc, imgman): """An ImageControlDialog is initialized with a parent widget, a RenderControl object, and an ImageManager object""" QDialog.__init__(self, parent) image = rc.image self.setWindowTitle("%s: Colour Controls" % image.name) self.setWindowIcon(pixmaps.colours.icon()) self.setModal(False) self.image = image self._rc = rc self._imgman = imgman self._currier = PersistentCurrier() # init internal state self._prev_range = self._display_range = None, None self._hist = None self._geometry = None # create layouts lo0 = QVBoxLayout(self) # lo0.setContentsMargins(0,0,0,0) # histogram plot whide = self.makeButton("Hide", self.hide, width=128) whide.setShortcut(Qt.Key_F9) lo0.addWidget(Separator(self, "Histogram and ITF", extra_widgets=[whide])) lo1 = QHBoxLayout() lo1.setContentsMargins(0, 0, 0, 0) self._histplot = QwtPlot(self) self._histplot.setAutoDelete(False) lo1.addWidget(self._histplot, 1) lo2 = QHBoxLayout() lo2.setContentsMargins(0, 0, 0, 0) lo2.setSpacing(2) lo0.addLayout(lo2) lo0.addLayout(lo1) self._wautozoom = QCheckBox("autozoom", self) self._wautozoom.setChecked(True) self._wautozoom.setToolTip("""<P>If checked, then the histrogram plot will zoom in automatically when you narrow the current intensity range.</P>""") self._wlogy = QCheckBox("log Y", self) self._wlogy.setChecked(True) self._ylogscale = True self._wlogy.setToolTip( """<P>If checked, a log-scale Y axis is used for the histogram plot instead of a linear one.""") self._wlogy.toggled[bool].connect(self._setHistLogScale) self._whistunzoom = self.makeButton("", self._unzoomHistogram, icon=pixmaps.full_range.icon()) self._whistzoomout = self.makeButton("-", self._currier.curry(self._zoomHistogramByFactor, math.sqrt(.1))) self._whistzoomin = self.makeButton("+", self._currier.curry(self._zoomHistogramByFactor, math.sqrt(10))) self._whistzoomin.setToolTip("""<P>Click to zoom into the histogram plot by one step. This does not change the current intensity range.</P>""") self._whistzoomout.setToolTip("""<P>Click to zoom out of the histogram plot by one step. This does not change the current intensity range.</P>""") self._whistunzoom.setToolTip("""<P>Click to reset the histogram plot back to its full extent. This does not change the current intensity range.</P>""") self._whistzoom = QwtWheel(self) self._whistzoom.setMass(0.5) self._whistzoom.setOrientation(Qt.Horizontal) self._whistzoom.setMaximumWidth(80) self._whistzoom.setRange(0, 10) self._whistzoom.setSingleStep(0.1) self._whistzoom.setPageStepCount(1) self._whistzoom.setTickCount(30) self._whistzoom.setTracking(False) self._whistzoom.valueChanged['double'].connect(self._zoomHistogramFinalize) self._whistzoom.wheelMoved['double'].connect(self._zoomHistogramPreview) self._whistzoom.setToolTip("""<P>Use this wheel control to zoom in/out of the histogram plot. This does not change the current intensity range. Note that the zoom wheel should also respond to your mouse wheel, if you have one.</P>""") # This works around a stupid bug in QwtSliders -- when using the mousewheel, only sliderMoved() signals are emitted, # with no final valueChanged(). If we want to do a fast preview of something on sliderMoved(), and a "slow" final # step on valueChanged(), we're in trouble. So we start a timer on sliderMoved(), and if the timer expires without # anything else happening, do a valueChanged(). # Here we use a timer to call zoomHistogramFinalize() w/o an argument. self._whistzoom_timer = QTimer(self) self._whistzoom_timer.setSingleShot(True) self._whistzoom_timer.setInterval(500) self._whistzoom_timer.timeout.connect(self._zoomHistogramFinalize) # set same size for all buttons and controls width = 24 for w in self._whistunzoom, self._whistzoomin, self._whistzoomout: w.setMinimumSize(width, width) w.setMaximumSize(width, width) self._whistzoom.setMinimumSize(80, width) self._wlab_histpos_text = "(hover for help)" self._wlab_histpos = QLabel(self._wlab_histpos_text, self) help_font = QFont() help_font.setPointSize(8) self._wlab_histpos.setFont(help_font) self._wlab_histpos.setToolTip(""" <P>The plot shows a histogram of either the full image or its selected subset (as per the "Data subset" section below).</P> <P>The current intensity range is indicated by the grey box in the plot.</P> <P>Use the left mouse button to change the low intensity limit, and the right button (on Macs, use Ctrl-click) to change the high limit.</P> <P>Use Shift with the left mouse button to zoom into an area of the histogram, or else use the "zoom wheel" control or the plus/minus toolbuttons above the histogram to zoom in or out. To zoom back out to the full extent of the histogram, click on the rightmost button above the histogram.</P> """) lo2.addWidget(self._wlab_histpos, 1) lo2.addWidget(self._wautozoom) lo2.addWidget(self._wlogy, 0) lo2.addWidget(self._whistzoomin, 0) lo2.addWidget(self._whistzoom, 0) lo2.addWidget(self._whistzoomout, 0) lo2.addWidget(self._whistunzoom, 0) self._zooming_histogram = False sliced_axes = rc.slicedAxes() dprint(1, "sliced axes are", sliced_axes) self._stokes_axis = None # subset indication lo0.addWidget(Separator(self, "Data subset")) # sliced axis selectors self._wslicers = [] if sliced_axes: lo1 = QHBoxLayout() lo1.setContentsMargins(0, 0, 0, 0) lo1.setSpacing(2) lo0.addLayout(lo1) lo1.addWidget(QLabel("Current slice: ", self)) for i, (iextra, name, labels) in enumerate(sliced_axes): lo1.addWidget(QLabel("%s:" % name, self)) if name == "STOKES": self._stokes_axis = iextra # add controls wslicer = QComboBox(self) self._wslicers.append(wslicer) wslicer.addItems(labels) wslicer.setToolTip("""<P>Selects current slice along the %s axis.</P>""" % name) wslicer.setCurrentIndex(self._rc.currentSlice()[iextra]) wslicer.activated[int].connect(self._currier.curry(self._rc.changeSlice, iextra)) lo2 = QVBoxLayout() lo1.addLayout(lo2) lo2.setContentsMargins(0, 0, 0, 0) lo2.setSpacing(0) wminus = QToolButton(self) wminus.setArrowType(Qt.UpArrow) wminus.clicked.connect(self._currier.curry(self._rc.incrementSlice, iextra, 1)) if i == 0: wminus.setShortcut(Qt.SHIFT + Qt.Key_F7) elif i == 1: wminus.setShortcut(Qt.SHIFT + Qt.Key_F8) wplus = QToolButton(self) wplus.setArrowType(Qt.DownArrow) wplus.clicked.connect(self._currier.curry(self._rc.incrementSlice, iextra, -1)) if i == 0: wplus.setShortcut(Qt.Key_F7) elif i == 1: wplus.setShortcut(Qt.Key_F8) wminus.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) wplus.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) sz = QSize(12, 8) wminus.setMinimumSize(sz) wplus.setMinimumSize(sz) wminus.resize(sz) wplus.resize(sz) lo2.addWidget(wminus) lo2.addWidget(wplus) lo1.addWidget(wslicer) lo1.addSpacing(5) lo1.addStretch(1) # subset indicator lo1 = QHBoxLayout() lo1.setContentsMargins(0, 0, 0, 0) lo1.setSpacing(2) lo0.addLayout(lo1) self._wlab_subset = QLabel("Subset: xxx", self) self._wlab_subset.setToolTip("""<P>This indicates the current data subset to which the histogram and the stats given here apply. Use the "Reset to" control on the right to change the current subset and recompute the histogram and stats.</P>""") lo1.addWidget(self._wlab_subset, 1) self._wreset_full = self.makeButton("\u2192 full", self._rc.setFullSubset) lo1.addWidget(self._wreset_full) if sliced_axes: # if self._stokes_axis is not None and len(sliced_axes)>1: # self._wreset_stokes = self.makeButton(u"\u21920Stokes",self._rc.setFullSubset) self._wreset_slice = self.makeButton("\u2192 slice", self._rc.setSliceSubset) lo1.addWidget(self._wreset_slice) else: self._wreset_slice = None # min/max controls lo1 = QHBoxLayout() lo1.setContentsMargins(0, 0, 0, 0) lo0.addLayout(lo1, 0) self._wlab_stats = QLabel(self) self._wlab_stats.setWordWrap(True) self._wlab_stats.setMinimumWidth(384) lo1.addWidget(self._wlab_stats, 0) self._wmore_stats = self.makeButton("more...", self._showMeanStd) self._wlab_stats.setMinimumHeight(self._wmore_stats.height()) lo1.addWidget(self._wmore_stats, 0) lo1.addStretch(1) # intensity controls lo0.addWidget(Separator(self, "Intensity mapping")) lo1 = QHBoxLayout() lo1.setContentsMargins(0, 0, 0, 0) lo1.setSpacing(2) lo0.addLayout(lo1, 0) self._range_validator = FloatValidator(self) self._wrange = QLineEdit(self), QLineEdit(self) self._wrange[0].setToolTip("""<P>This is the low end of the intensity range.</P>""") self._wrange[1].setToolTip("""<P>This is the high end of the intensity range.</P>""") for w in self._wrange: w.setValidator(self._range_validator) w.editingFinished.connect(self._changeDisplayRange) lo1.addWidget(QLabel("low:", self), 0) lo1.addWidget(self._wrange[0], 1) self._wrangeleft0 = self.makeButton("\u21920", self._setZeroLeftLimit, width=32) self._wrangeleft0.setToolTip("""<P>Click this to set the low end of the intensity range to 0.</P>""") lo1.addWidget(self._wrangeleft0, 0) lo1.addSpacing(8) lo1.addWidget(QLabel("high:", self), 0) lo1.addWidget(self._wrange[1], 1) lo1.addSpacing(8) self._wrange_full = self.makeButton(None, self._setHistDisplayRange, icon=pixmaps.intensity_graph.icon()) lo1.addWidget(self._wrange_full) self._wrange_full.setToolTip( """<P>Click this to reset the intensity range to the current extent of the histogram plot.</P>""") # add menu for display range range_menu = QMenu(self) wrange_menu = QToolButton(self) wrange_menu.setText("Reset to") wrange_menu.setToolTip("""<P>Use this to reset the intensity range to various pre-defined settings.</P>""") lo1.addWidget(wrange_menu) self._qa_range_full = range_menu.addAction(pixmaps.full_range.icon(), "Full subset", self._rc.resetSubsetDisplayRange) self._qa_range_hist = range_menu.addAction(pixmaps.intensity_graph.icon(), "Current histogram limits", self._setHistDisplayRange) for percent in (99.99, 99.9, 99.5, 99, 98, 95): range_menu.addAction("%g%%" % percent, self._currier.curry(self._changeDisplayRangeToPercent, percent)) wrange_menu.setMenu(range_menu) wrange_menu.setPopupMode(QToolButton.InstantPopup) lo1 = QGridLayout() lo1.setContentsMargins(0, 0, 0, 0) lo0.addLayout(lo1, 0) self._wimap = QComboBox(self) lo1.addWidget(QLabel("Intensity policy:", self), 0, 0) lo1.addWidget(self._wimap, 1, 0) self._wimap.addItems(rc.getIntensityMapNames()) self._wimap.currentIndexChanged[int].connect(self._rc.setIntensityMapNumber) self._wimap.setToolTip("""<P>Use this to change the type of the intensity transfer function (ITF).</P>""") # log cycles control lo1.setColumnStretch(1, 1) self._wlogcycles_label = QLabel("Log cycles: ", self) lo1.addWidget(self._wlogcycles_label, 0, 1) # self._wlogcycles = QwtWheel(self) # self._wlogcycles.setTotalAngle(360) self._wlogcycles = QwtSlider(self) self._wlogcycles.setToolTip( """<P>Use this to change the log-base for the logarithmic intensity transfer function (ITF).</P>""") # This works around a stupid bug in QwtSliders -- see comments on histogram zoom wheel above self._wlogcycles_timer = QTimer(self) self._wlogcycles_timer.setSingleShot(True) self._wlogcycles_timer.setInterval(500) self._wlogcycles_timer.timeout.connect(self._setIntensityLogCycles) lo1.addWidget(self._wlogcycles, 1, 1) # self._wlogcycles.setRange(1., 10) # need to find 6.1.5 change from v5 self._wlogcycles.setScale(1., 10) # self._wlogcycles.setStep(0.1) # need to find 6.1.5 change from v5 # self._wlogcycles.setScaleStepSize(0.1) self._wlogcycles.setTracking(False) self._wlogcycles.valueChanged.connect(self._setIntensityLogCycles) self._wlogcycles.sliderMoved.connect(self._previewIntensityLogCycles) self._updating_imap = False # lock intensity map lo1 = QHBoxLayout() lo1.setContentsMargins(0, 0, 0, 0) lo0.addLayout(lo1, 0) # lo1.addWidget(QLabel("Lock range accross",self)) wlock = QCheckBox("Lock display range", self) wlock.setMinimumWidth(192) wlock.setToolTip("""<P>If checked, then the intensity range will be locked. The ranges of all locked images change simultaneously.</P>""") lo1.addWidget(wlock) wlockall = QToolButton(self) wlockall.setIcon(pixmaps.locked.icon()) wlockall.setText("Lock all to this") wlockall.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) wlockall.setAutoRaise(True) wlockall.setToolTip("""<P>Click this to lock together the intensity ranges of all images.</P>""") lo1.addWidget(wlockall) wunlockall = QToolButton(self) wunlockall.setIcon(pixmaps.unlocked.icon()) wunlockall.setText("Unlock all") wunlockall.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) wunlockall.setAutoRaise(True) wunlockall.setToolTip("""<P>Click this to unlock the intensity ranges of all images.</P>""") lo1.addWidget(wunlockall) wlock.setChecked(self._rc.isDisplayRangeLocked()) wlock.clicked[bool].connect(self._rc.lockDisplayRange) wlockall.clicked.connect(self._currier.curry(self._imgman.lockAllDisplayRanges, self._rc)) wunlockall.clicked.connect(self._imgman.unlockAllDisplayRanges) self._rc.displayRangeLocked.connect(wlock.setChecked) # self._wlock_imap_axis = [ QCheckBox(name,self) for iaxis,name,labels in sliced_axes ] # for iw,w in enumerate(self._wlock_imap_axis): # QObject.connect(w,pyqtSignal("toggled(bool)"),self._currier.curry(self._rc.lockDisplayRangeForAxis,iw)) # lo1.addWidget(w,0) lo1.addStretch(1) # lo0.addWidget(Separator(self,"Colourmap")) # color bar self._colorbar = QwtPlot(self) lo0.addWidget(self._colorbar) self._colorbar.setAutoDelete(False) self._colorbar.setMinimumHeight(32) self._colorbar.enableAxis(QwtPlot.yLeft, False) self._colorbar.enableAxis(QwtPlot.xBottom, False) # color plot self._colorplot = QwtPlot(self) lo0.addWidget(self._colorplot) self._colorplot.setAutoDelete(False) self._colorplot.setMinimumHeight(64) self._colorplot.enableAxis(QwtPlot.yLeft, False) self._colorplot.enableAxis(QwtPlot.xBottom, False) # self._colorplot.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Preferred) self._colorbar.hide() self._colorplot.hide() # color controls lo1 = QHBoxLayout() lo1.setContentsMargins(0, 0, 0, 0) lo0.addLayout(lo1, 1) lo1.addWidget(QLabel("Colourmap:", self)) # colormap list ### NB: use setIconSize() and icons in QComboBox!!! self._wcolmaps = QComboBox(self) self._wcolmaps.setIconSize(QSize(128, 16)) self._wcolmaps.setToolTip("""<P>Use this to select a different colourmap.</P>""") for cmap in self._rc.getColormapList(): self._wcolmaps.addItem(QIcon(cmap.makeQPixmap(128, 16)), cmap.name) lo1.addWidget(self._wcolmaps) self._wcolmaps.activated[int].connect(self._rc.setColorMapNumber) # add widgetstack for colormap controls self._wcolmap_control_stack = QStackedWidget(self) self._wcolmap_control_blank = QWidget(self._wcolmap_control_stack) self._wcolmap_control_stack.addWidget(self._wcolmap_control_blank) lo0.addWidget(self._wcolmap_control_stack) self._colmap_controls = [] # add controls to stack for index, cmap in enumerate(self._rc.getColormapList()): if isinstance(cmap, Colormaps.ColormapWithControls): controls = cmap.makeControlWidgets(self._wcolmap_control_stack) self._wcolmap_control_stack.addWidget(controls) cmap.colormapChanged.connect(self._currier.curry(self._previewColormapParameters, index, cmap)) cmap.colormapPreviewed.connect(self._currier.curry(self._previewColormapParameters, index, cmap)) self._colmap_controls.append(controls) else: self._colmap_controls.append(self._wcolmap_control_blank) # connect updates from renderControl and image self.image.signalSlice.connect(self._updateImageSlice) self._rc.intensityMapChanged.connect(self._updateIntensityMap) self._rc.colorMapChanged.connect(self._updateColorMap) self._rc.dataSubsetChanged.connect(self._updateDataSubset) self._rc.displayRangeChanged.connect(self._updateDisplayRange) # update widgets self._setupHistogramPlot() self._updateDataSubset(*self._rc.currentSubset()) self._updateColorMap(image.colorMap()) self._updateIntensityMap(rc.currentIntensityMap(), rc.currentIntensityMapNumber()) self._updateDisplayRange(*self._rc.displayRange())
class TDockWidget(QDockWidget): def __init__(self, title="", parent=None, flags=Qt.WindowFlags(), bind_widget=None, close_slot=None, toggle_slot=None): QDockWidget.__init__(self, title, parent, flags) self.installEventFilter(self) self.main_win = parent # default stlyesheets for title bars self.title_stylesheet = "QWidget {background: rgb(68,68,68);}" self.button_style = "QPushButton:hover:!pressed {background: grey;}" from TigGUI.Images.ControlDialog import ImageControlDialog from TigGUI.Plot.SkyModelPlot import ToolDialog from TigGUI.Plot.SkyModelPlot import LiveImageZoom if bind_widget is not None: self.bind_widget = bind_widget if bind_widget is not None: if isinstance(bind_widget, ToolDialog): self.tdock_style = "ToolDialog {border: 1.5px solid rgb(68,68,68);}" elif isinstance(bind_widget, ImageControlDialog): self.tdock_style = "ImageControlDialog {border: 1.5px solid rgb(68,68,68);}" # set default sizes for QDockWidgets self.btn_w = 28 self.btn_h = 28 self.icon_size = QSize(20, 20) self.font_size = 8 # setup custom title bar for profiles dockable self.dock_title_bar = QWidget() self.dock_title_bar.setContentsMargins(0, 0, 0, 0) self.dock_title_bar.setStyleSheet(self.title_stylesheet) self.dock_title_bar.setBaseSize(0, 0) self.dock_title_layout = QHBoxLayout() self.dock_title_layout.setContentsMargins(0, 0, 0, 0) self.dock_title_layout.setSpacing(0) self.dock_title_bar.setLayout(self.dock_title_layout) # custom close button self.close_button = QPushButton() self.close_button.setStyleSheet(self.button_style) self.close_button.setMaximumWidth(self.btn_w) self.close_button.setMaximumHeight(self.btn_h) self.close_button.setContentsMargins(0, 0, 0, 0) self.close_button.setBaseSize(0, 0) self.close_icon = self.dock_title_bar.style().standardIcon(QStyle.SP_TitleBarCloseButton) self.close_button.setIcon(self.close_icon) self.close_button.setToolTip("Close") # custom toggle button self.toggle_button = QPushButton() self.toggle_button.setStyleSheet(self.button_style) self.toggle_button.setMaximumWidth(self.btn_w) self.toggle_button.setMaximumHeight(self.btn_h) self.toggle_button.setContentsMargins(0, 0, 0, 0) self.toggle_button.setBaseSize(0, 0) self.toggle_icon = self.dock_title_bar.style().standardIcon(QStyle.SP_TitleBarShadeButton) self.toggle_button.setIcon(self.toggle_icon) self.toggle_button.setToolTip("Dock/float widget") # tigger logo self.image0 = pixmaps.tigger_logo.pm() self.title_icon = QLabel() self.title_icon.setContentsMargins(0, 0, 0, 0) self.title_icon.setBaseSize(0, 0) self.title_icon.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.title_icon.setScaledContents(True) self.title_icon.setPixmap(self.image0) self.title_icon.setAlignment(Qt.AlignCenter) self.title_icon.setMaximumSize(self.icon_size) # set dock widget title self.title_font = QFont() self.title_font.setBold(True) self.title_font.setPointSize(self.font_size) if bind_widget is not None: if isinstance(bind_widget, ImageControlDialog): self.dock_title = QLabel(f"{title}: Control Dialog") else: self.dock_title = QLabel(title) self.dock_title.setFont(self.title_font) self.dock_title.setAlignment(Qt.AlignCenter) self.dock_title.setContentsMargins(0, 0, 0, 0) self.dock_title.setBaseSize(0, 0) self.dock_title.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Minimum) # add dock widget title items to layout self.dock_title_layout.addWidget(self.title_icon) self.dock_title_layout.addWidget(self.dock_title) self.dock_title_layout.addWidget(self.toggle_button) self.dock_title_layout.addWidget(self.close_button) # set up profiles as dockable self.setStyleSheet(self.tdock_style) self.setWidget(bind_widget) self.setFeatures(QDockWidget.AllDockWidgetFeatures) if bind_widget is not None: if isinstance(bind_widget, ToolDialog): self.setAllowedAreas(Qt.AllDockWidgetAreas) elif isinstance(bind_widget, ImageControlDialog): self.setAllowedAreas(Qt.RightDockWidgetArea | Qt.LeftDockWidgetArea) self.setTitleBarWidget(self.dock_title_bar) self.setFloating(False) # get current sizeHints() if bind_widget is not None: self.setBaseSize(bind_widget.sizeHint()) if isinstance(bind_widget, LiveImageZoom): bind_widget.livezoom_resize_signal.connect(self._resizeDockWidget) if close_slot is not None: self.close_button.clicked.connect(close_slot) if toggle_slot is not None: self.toggle_button.clicked.connect(toggle_slot) def _resizeDockWidget(self, qsize): # live zoom signal slot to resize dockwidget and dock areas self.setMinimumSize(qsize) self.main_win.resizeDocks([self], [qsize.width()], Qt.Horizontal) self.main_win.resizeDocks([self], [qsize.height()], Qt.Vertical) # hack to stop QDockWidget responding to drag events for undocking - work around for Qt bug def eventFilter(self, source, event): # event seq 2, 5, 3 - mouse press, mouse move, mouse release if event.type() == QEvent.MouseButtonPress: label = self.childAt(event.pos()) if not label: return super(TDockWidget, self).eventFilter(source, event) if isinstance(label, QLabel): if not self.isFloating(): fake_mouse_event = QMouseEvent(QEvent.MouseButtonRelease, event.pos(), event.button(), event.buttons(), event.modifiers()) super(TDockWidget, self).event(fake_mouse_event) return True return super(TDockWidget, self).eventFilter(source, event)
def createPcCalibrationControls(): gb = QGroupBox("PC Calibration") #------------------------------------------- layout = QHBoxLayout() label = QLabel("Calibration offset for 180:") global offAt180_sb offAt180_sb = QDoubleSpinBox() offAt180_sb.setRange(-4.0, 0.0) offAt180_sb.setSingleStep(0.5) offAt180_sb.setValue(-3.5) offAt180_sb.setMaximumWidth(60) layout.addWidget(label) layout.addWidget(offAt180_sb) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(0) upper = QWidget() upper.setLayout(layout) #------------------------------------------- layout = QHBoxLayout() btn2p5 = QPushButton("2.5") btn2p5.clicked.connect(lambda: offAt180_sb.setValue(-2.5)) btn3 = QPushButton("3.0") btn3.clicked.connect(lambda: offAt180_sb.setValue(-3.0)) btn3p5 = QPushButton("3.5") btn3p5.clicked.connect(lambda: offAt180_sb.setValue(-3.5)) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(0) layout.addWidget(btn2p5) layout.addWidget(btn3) layout.addWidget(btn3p5) middle = QWidget() middle.setLayout(layout) #------------------------------------------- layout = QHBoxLayout() label = QLabel("Running Angle offset:") global runningAngleOffset_sb runningAngleOffset_sb = QSpinBox() runningAngleOffset_sb.setToolTip( "offset in degrees to add to the angle reported by arduino") runningAngleOffset_sb.setRange(0, 5) runningAngleOffset_sb.setValue(2) runningAngleOffset_sb.setMaximumWidth(60) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(0) layout.addWidget(label) layout.addWidget(runningAngleOffset_sb) lower = QWidget() lower.setLayout(layout) #------------------------------------------- vbox = QVBoxLayout() vbox.addWidget(upper) vbox.addWidget(middle) vbox.addWidget(lower) vbox.addStretch(1) vbox.setContentsMargins(0, 0, 0, 0) vbox.setSpacing(0) gb.setLayout(vbox) return gb
class InformationWindow(QWidget): def __init__(self): QWidget.__init__(self, ctx.mainScreen) self.setObjectName("InformationWindow") self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.setFixedHeight(50) self.setMaximumWidth(800) self.setStyleSheet(""" QFrame#frame { border: 1px solid rgba(255,255,255,30); /*border-radius: 4px;*/ background-color: rgba(0,0,0,100);} QLabel { border:none; color:#FFFFFF;} QProgressBar { border: 1px solid white;} QProgressBar::chunk { background-color: #F1610D; width: 0.5px;} """) self.gridlayout = QGridLayout(self) self.frame = QFrame(self) self.frame.setObjectName("frame") self.horizontalLayout = QHBoxLayout(self.frame) self.horizontalLayout.setContentsMargins(10, 0, 10, 0) # Spinner self.spinner = QLabel(self.frame) self.spinner.setMinimumSize(QSize(16, 16)) self.spinner.setMaximumSize(QSize(16, 16)) self.spinner.setIndent(6) self.movie = QMovie(':/images/working.mng') self.spinner.setMovie(self.movie) self.movie.start() self.horizontalLayout.addWidget(self.spinner) # Message self.label = QLabel(self.frame) self.label.setAlignment(Qt.AlignCenter) self.label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.icon = QLabel(self.frame) self.icon.setFixedWidth(16) self.icon.setFixedHeight(16) self.horizontalLayout.setSpacing(10) self.horizontalLayout.addWidget(self.icon) self.horizontalLayout.addWidget(self.label) self.gridlayout.addWidget(self.frame, 0, 0, 1, 1) def update(self, message, type=None, spinner=False): fontMetric = self.label.fontMetrics() textWidth = fontMetric.width(message) if type: self.icon.show() if type == "error": self.icon.setPixmap(QPixmap(":/gui/pics/dialog-error.png")) self.setStyleSheet( " QFrame#frame {background-color: rgba(255,0,0,100);} ") elif type == "warning": self.icon.setPixmap(QPixmap(":/gui/pics/dialog-warning.png")) self.setStyleSheet( " QFrame#frame {background-color: rgba(0,0,0,100);} ") self.setFixedWidth(textWidth + self.icon.width() + 50) self.label.setText(message) else: self.icon.hide() self.setStyleSheet( " QFrame#frame {background-color: rgba(0,0,0,100);} ") self.setFixedWidth(textWidth + self.icon.width() + 100) self.label.setText(message) self.spinner.setVisible(spinner) self.move(ctx.mainScreen.width() / 2 - self.width() / 2, ctx.mainScreen.height() - self.height() / 2 - 50) self.show() def refresh(self): ctx.mainScreen.processEvents() def show(self): QWidget.show(self) self.refresh() def hide(self): QWidget.hide(self) self.refresh()
def createGotoControls(): gb = QGroupBox("Goto Controls") #------------------------------------------- layout = QHBoxLayout() label = QLabel("Goto angle:") lineEdit = QLineEdit() go_btn = QPushButton("Go") lineEdit.setMaximumWidth(30) go_btn.clicked.connect(lambda: send_cmd(["g" + lineEdit.displayText()])) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(0) layout.addWidget(label) layout.addWidget(lineEdit) layout.addSpacing(10) layout.addWidget(go_btn) upper = QWidget() upper.setLayout(layout) #------------------------------------------ layout = QHBoxLayout() btn0 = QPushButton("0") btn90 = QPushButton("90") btn180 = QPushButton("180") btn270 = QPushButton("270") btn0.clicked.connect(lambda: send_cmd(["g0"])) btn90.clicked.connect(lambda: send_cmd(["g90"])) btn180.clicked.connect( lambda: send_cmd(["g" + str(180 + float(offAt180_sb.value()))])) btn270.clicked.connect(lambda: send_cmd(["g270"])) btn0.setMaximumWidth(40) btn90.setMaximumWidth(40) btn180.setMaximumWidth(40) btn270.setMaximumWidth(40) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(0) layout.addWidget(btn0) layout.addWidget(btn90) layout.addWidget(btn180) layout.addWidget(btn270) lower = QWidget() lower.setLayout(layout) #------------------------------------------ vbox = QVBoxLayout() vbox.addWidget(upper) vbox.addWidget(lower) vbox.addStretch(1) vbox.setContentsMargins(0, 0, 0, 0) vbox.setSpacing(0) gb.setLayout(vbox) return gb
def __init__(self, parent = None): super(MainWidget, self).__init__(parent) # member variables self._lTheorySpd = 0 self._rTheorySpd = 0 self._serialSend = SerialSend() # mainWindow properties self.setObjectName('MainWidget') self.setWindowIcon(QIcon(':/image/default/app.icon')) self.setWindowTitle('%s V%s' % ( qApp.applicationDisplayName(), qApp.applicationVersion())) self.resize(800, 480) # mainWindow layout # top self.groupBoxTop = QGroupBox(self) self.groupBoxTop.setObjectName('groupBoxTop') # command dashboard buttonLeftPower = JSwitchButton(parent = self.groupBoxTop) buttonRightPower = JSwitchButton(parent = self.groupBoxTop) buttonSettings = QPushButton(self.groupBoxTop) buttonHistory = QPushButton(self.groupBoxTop) buttonQuit = QPushButton(self.groupBoxTop) buttonLeftPower.setObjectName('buttonLeftPower') buttonRightPower.setObjectName('buttonRightPower') buttonSettings.setObjectName('buttonSettings') buttonHistory.setObjectName('buttonHistory') buttonQuit.setObjectName('buttonQuit') areaPortState = QWidget(self) areaPortState.setObjectName('areaPortState') areaPortState.setStyleSheet('QWidget#areaPortState{border-radius:3px;' 'border:1px solid #505050;' 'background-color:rgba(64,64,64,50);}') vertLayoutPortState = QVBoxLayout(areaPortState) vertLayoutPortState.setContentsMargins(50, 2, 50, 2) vertLayoutPortState.setSpacing(3) buttonPortState = JSwitchButton(pixmap = QPixmap(':/carmonitor/image/button-port-state.png'), parent = areaPortState) buttonPortState.setObjectName('buttonPortState') vertLayoutPortState.addWidget(QLabel('串口', areaPortState), 0, Qt.AlignHCenter) vertLayoutPortState.addWidget(buttonPortState) # horiLayoutTop = QHBoxLayout(self.groupBoxTop) horiLayoutTop.setContentsMargins(0, 0, 0, 0) horiLayoutTop.addSpacing(25) horiLayoutTop.addWidget(buttonSettings, 0, Qt.AlignLeft) horiLayoutTop.addSpacing(20) horiLayoutTop.addWidget(buttonHistory, 0, Qt.AlignLeft) horiLayoutTop.addSpacing(65) horiLayoutTop.addWidget(buttonLeftPower) horiLayoutTop.addWidget(QLabel('左电源开关', self.groupBoxTop)) horiLayoutTop.addStretch() horiLayoutTop.addWidget(areaPortState, 0, Qt.AlignTop) horiLayoutTop.addStretch() horiLayoutTop.addWidget(QLabel('右电源开关', self.groupBoxTop)) horiLayoutTop.addWidget(buttonRightPower) horiLayoutTop.addSpacing(150) horiLayoutTop.addWidget(buttonQuit, 0, Qt.AlignRight) horiLayoutTop.addSpacing(25) # middle # curves self.curveLBP = CurveWidget(title = '左刹车压力(MPa)', parent = self) self.curveLRP = CurveWidget(title = '左转速(r/min)', parent = self) self.curveRBP = CurveWidget(title = '右刹车压力(MPa)', parent = self) self.curveRRP = CurveWidget(title = '右转速(r/min)', parent = self) self.curveLBP.setObjectName('curveLBP') self.curveLRP.setObjectName('curveLRP') self.curveRBP.setObjectName('curveRBP') self.curveRRP.setObjectName('curveRRP') # self.curveLBP.setAxisScale(QwtPlot.yLeft, 0, 30, 5) # areaMiddle self.areaMiddle = QWidget(self) self.areaMiddle.setObjectName('areaMiddle') self.areaMiddle.setFixedWidth(280) # groupBoxStatus = QGroupBox(self) groupBoxStatus.setObjectName('groupBoxStatus') # status-view gridLayoutStatus = QGridLayout(groupBoxStatus) gridLayoutStatus.setContentsMargins(5, 5, 5, 5) gridLayoutStatus.setHorizontalSpacing(8) gridLayoutStatus.setVerticalSpacing(3) # Brake-Command editLeftBrakeCmd = QLineEdit(groupBoxStatus) editRightBrakeCmd = QLineEdit(groupBoxStatus) editLeftBrakeCmd.setObjectName('editLeftBrakeCmd') editRightBrakeCmd.setObjectName('editRightBrakeCmd') editLeftBrakeCmd.setReadOnly(True) editRightBrakeCmd.setReadOnly(True) gridLayoutStatus.addWidget(QLabel('刹车指令:', groupBoxStatus), 0, 0, 1, 2, Qt.AlignCenter) gridLayoutStatus.addWidget(editLeftBrakeCmd, 1, 0, 1, 1) gridLayoutStatus.addWidget(editRightBrakeCmd, 1, 1, 1, 1) # Major Brake Pressure self.editMLeftBrakeP = QLineEdit(groupBoxStatus) self.editMRightBrakeP = QLineEdit(groupBoxStatus) self.editMLeftBrakeP.setObjectName('editMLeftBrakeP') self.editMRightBrakeP.setObjectName('editMRightBrakeP') self.editMLeftBrakeP.setReadOnly(True) self.editMRightBrakeP.setReadOnly(True) gridLayoutStatus.addWidget(QLabel('主刹车压力:', groupBoxStatus), 2, 0, 1, 2, Qt.AlignCenter) gridLayoutStatus.addWidget(self.editMLeftBrakeP, 3, 0, 1, 1) gridLayoutStatus.addWidget(self.editMRightBrakeP, 3, 1, 1, 1) # Assistant Brake Pressure self.editALeftBrakeP = QLineEdit(groupBoxStatus) self.editARightBrakeP = QLineEdit(groupBoxStatus) self.editALeftBrakeP.setObjectName('editALeftBrakeP') self.editARightBrakeP.setObjectName('editARightBrakeP') self.editALeftBrakeP.setReadOnly(True) self.editARightBrakeP.setReadOnly(True) gridLayoutStatus.addWidget(QLabel('副刹车压力:', groupBoxStatus), 4, 0, 1, 2, Qt.AlignCenter) gridLayoutStatus.addWidget(self.editALeftBrakeP, 5, 0, 1, 1) gridLayoutStatus.addWidget(self.editARightBrakeP, 5, 1, 1, 1) # Rotation Rate self.editLeftRotateRate = QLineEdit(groupBoxStatus) self.editRightRotateRate = QLineEdit(groupBoxStatus) self.editLeftRotateRate.setObjectName('editLeftRotateRate') self.editRightRotateRate.setObjectName('editRightRotateRate') gridLayoutStatus.addWidget(QLabel('实际转速:', groupBoxStatus), 6, 0, 1, 2, Qt.AlignCenter) gridLayoutStatus.addWidget(self.editLeftRotateRate, 7, 0, 1, 1) gridLayoutStatus.addWidget(self.editRightRotateRate, 7, 1, 1, 1) # Theory Rotation Rate self.editTheoryLeftRotateRate = QLineEdit(groupBoxStatus) self.editTheoryRightRotateRate = QLineEdit(groupBoxStatus) self.editTheoryLeftRotateRate.setObjectName('editTheoryLeftRotateRate') self.editTheoryRightRotateRate.setObjectName('editTheoryRightRotateRate') gridLayoutStatus.addWidget(QLabel('理论转速:', groupBoxStatus), 8, 0, 1, 2, Qt.AlignCenter) gridLayoutStatus.addWidget(self.editTheoryLeftRotateRate, 9, 0, 1, 1) gridLayoutStatus.addWidget(self.editTheoryRightRotateRate, 9, 1, 1, 1) # groupBoxCtrl = QGroupBox(self) groupBoxCtrl.setObjectName('groupBoxCtrl') # status-view gridLayoutCtrl = QGridLayout(groupBoxCtrl) gridLayoutCtrl.setContentsMargins(5, 5, 5, 5) gridLayoutCtrl.setSpacing(20) # left-button buttonLeftDashboard = JDashButton('左指令旋钮', groupBoxCtrl) buttonLeftSpeedGain = JDashButton('左转速增益', groupBoxCtrl) buttonLeftSpeedKnob = JDashButton('左转速增益', groupBoxCtrl) buttonLeftTracksip = JTracksipButton(parent = groupBoxCtrl) buttonLeftDashboard.setObjectName('buttonLeftDashboard') buttonLeftSpeedGain.setObjectName('buttonLeftSpeedGain') buttonLeftSpeedKnob.setObjectName('buttonLeftSpeedKnob') buttonLeftTracksip.setObjectName('buttonLeftTracksip') buttonLeftTracksip.setFixedSize(110, 45) # right-button buttonRightDashboard = JDashButton('右指令旋钮', groupBoxCtrl) buttonRightSpeedGain = JDashButton('右转速增益', groupBoxCtrl) buttonRightSpeedKnob = JDashButton('右转速增益', groupBoxCtrl) buttonRightTracksip = JTracksipButton(parent = groupBoxCtrl) buttonRightDashboard.setObjectName('buttonRightDashboard') buttonRightSpeedGain.setObjectName('buttonRightSpeedGain') buttonRightSpeedKnob.setObjectName('buttonRightSpeedKnob') buttonRightTracksip.setObjectName('buttonRightTracksip') buttonRightTracksip.setFixedSize(110, 45) horiLayoutTracksip = QHBoxLayout() horiLayoutTracksip.setContentsMargins(0, 0, 0, 0) horiLayoutTracksip.setSpacing(5) horiLayoutTracksip.addWidget(buttonLeftTracksip) horiLayoutTracksip.addWidget(QLabel('打滑', self), 0, Qt.AlignHCenter) horiLayoutTracksip.addWidget(buttonRightTracksip) gridLayoutCtrl.addLayout(horiLayoutTracksip, 0, 0, 1, 2) horiLayoutDashboard = QHBoxLayout() horiLayoutDashboard.setContentsMargins(0, 0, 0, 0) horiLayoutDashboard.setSpacing(5) horiLayoutDashboard.addWidget(buttonLeftDashboard) horiLayoutDashboard.addWidget(QLabel(' ', self), 0, Qt.AlignHCenter) horiLayoutDashboard.addWidget(buttonRightDashboard) gridLayoutCtrl.addLayout(horiLayoutDashboard, 1, 0, 1, 2) horiLayoutSpeedGain = QHBoxLayout() horiLayoutSpeedGain.setContentsMargins(0, 0, 0, 0) horiLayoutSpeedGain.setSpacing(5) horiLayoutSpeedGain.addWidget(buttonLeftSpeedGain) horiLayoutSpeedGain.addWidget(QLabel('(粗调)', self), 0, Qt.AlignHCenter) horiLayoutSpeedGain.addWidget(buttonRightSpeedGain) gridLayoutCtrl.addLayout(horiLayoutSpeedGain, 2, 0, 1, 2) horiLayoutSpeedKnob = QHBoxLayout() horiLayoutSpeedKnob.setContentsMargins(0, 0, 0, 0) horiLayoutSpeedKnob.setSpacing(5) horiLayoutSpeedKnob.addWidget(buttonLeftSpeedKnob) horiLayoutSpeedKnob.addWidget(QLabel('(细调)', self), 0, Qt.AlignHCenter) horiLayoutSpeedKnob.addWidget(buttonRightSpeedKnob) gridLayoutCtrl.addLayout(horiLayoutSpeedKnob, 3, 0, 1, 2) # vertLayoutMid = QVBoxLayout(self.areaMiddle) vertLayoutMid.setContentsMargins(0, 0, 0, 0) vertLayoutMid.setSpacing(0) vertLayoutMid.addWidget(groupBoxStatus) vertLayoutMid.addWidget(groupBoxCtrl) vertLayoutMid.addSpacing(20) # gridLayoutBottom = QGridLayout() gridLayoutBottom.setContentsMargins(0, 0, 0, 0) gridLayoutBottom.setSpacing(1) gridLayoutBottom.addWidget(self.curveLBP, 0, 0, 1, 1) gridLayoutBottom.addWidget(self.curveLRP, 1, 0, 1, 1) gridLayoutBottom.addWidget(self.areaMiddle, 0, 1, 2, 1) gridLayoutBottom.addWidget(self.curveRBP, 0, 2, 1, 1) gridLayoutBottom.addWidget(self.curveRRP, 1, 2, 1, 1) # main-layout vertLayoutMain = QVBoxLayout(self) vertLayoutMain.setContentsMargins(5, 5, 5, 5) vertLayoutMain.addWidget(self.groupBoxTop) vertLayoutMain.addLayout(gridLayoutBottom) # global properties qApp.setProperty('MainWidget', self) self._serialProxy = SerialPortProxy(self) self._serialProxy._serialSimulate = SerialSimulate(self._serialProxy) # qApp.setProperty('SerialProxy', self._serialProxy) # buttonSettings.clicked.connect(self.onButtonSettingsClicked) buttonHistory.clicked.connect(self.onButtonHistoryClicked) buttonPortState.clicked.connect(self.onButtonPortStateClicked) buttonQuit.clicked.connect(self.onButtonQuitClicked) # curves self.curveLBP.doubleClicked.connect(self.onCurveDoubleClicked) self.curveLRP.doubleClicked.connect(self.onCurveDoubleClicked) self.curveRBP.doubleClicked.connect(self.onCurveDoubleClicked) self.curveRRP.doubleClicked.connect(self.onCurveDoubleClicked) # switch-power buttonLeftPower.stateChanged.connect(self.onButtonLeftPowerStateChanged) buttonRightPower.stateChanged.connect(self.onButtonRightPowerStateChanged) # switch-tracksip buttonLeftTracksip.stateChanged.connect(self.onButtonLeftTracksipStateChanged) buttonRightTracksip.stateChanged.connect(self.onButtonRightTracksipStateChanged) self._serialProxy.stateChanged.connect(self.onSerialStateChanged) self._serialProxy.serialPortError.connect(self.onSerialPortError) self._serialProxy.displayRespond.connect(self.onSerialDisplayRespond) # buttonLeftSpeedGain.clicked.connect(self.execSliderWidget) buttonLeftSpeedKnob.clicked.connect(self.execSliderWidget) buttonRightSpeedGain.clicked.connect(self.execSliderWidget) buttonRightSpeedKnob.clicked.connect(self.execSliderWidget) # final initialization self.editMLeftBrakeP.setText('0 MPa') self.editMRightBrakeP.setText('0 MPa') self.editALeftBrakeP.setText('0 MPa') self.editARightBrakeP.setText('0 MPa') self.editLeftRotateRate.setText('0 r/min') self.editRightRotateRate.setText('0 r/min') self.editTheoryLeftRotateRate.setText('0 r/min') self.editTheoryRightRotateRate.setText('0 r/min') # c_memset(self._serialSend, 0, ctypes.sizeof(self._serialSend)) # SQL sqlName = applicationDirPath() \ + '/../data/cm-' \ + QDateTime.currentDateTime().toLocalTime().toString('yyyy-MM-dd-HH-mm-ss') \ + '.db' if not DatabaseMgr().create(sqlName): assert(False) # start serialport self._serialProxy.start() # buttonLeftTracksip.setState(self._serialSend.ctrlWord.lTracksip) buttonRightTracksip.setState(self._serialSend.ctrlWord.lTracksip)