def __init__(self, citylist, accurate_url, appid, parent=None): super(CityListDlg, self).__init__(parent) self.citylist = citylist self.accurate_url = accurate_url self.appid = appid self.listWidget = QListWidget() self.listWidget.addItems(self.citylist) buttonLayout = QVBoxLayout() self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.buttonBox.rejected.connect(self.reject) self.buttonBox.accepted.connect(self.accept) layoutT = QVBoxLayout() layout = QHBoxLayout() layout.addWidget(self.listWidget) layout.addLayout(buttonLayout) for text, slot in ((self.tr("&Add..."), self.add), (self.tr("&Remove..."), self.remove), (self.tr("&Up"), self.up), (self.tr("&Down"), self.down), (self.tr("De&fault"), self.default), (self.tr("&Sort"), self.listWidget.sortItems)): button = QPushButton(text) buttonLayout.addWidget(button) button.clicked.connect(slot) buttonLayout.addWidget(self.buttonBox) self.status = QLabel() layoutT.addLayout(layout) layoutT.addWidget(self.status) self.setLayout(layoutT) self.checklength()
def _create_layout(self, main_window): wrapper = QHBoxLayout() self.layout.addWidget(utils.get_scrollable(wrapper)) rows = 8 cols = 3 vboxes = [QVBoxLayout() for _ in range(cols)] widgets = ((TemplateWidgetInOptions(main_window, self.items, self), 'Шаблоны'), (UsersAndGroupsWidget(main_window, self), 'Пользователи и группы'), (self._switch_user, 'Сменить пользователя'), (self._get_template_export_func(main_window), 'Экспортировать шаблоны'), (self._get_template_import_func(main_window), 'Импортировать шаблоны')) for i, widget in enumerate(widgets): b = QPushButton(widget[1]) if callable(widget[0]): b.clicked.connect(widget[0]) else: b.clicked.connect(functools.partial(self.layout.setCurrentIndex, i + 1)) self.layout.addWidget(widget[0]) b.setGraphicsEffect(utils.get_shadow()) vboxes[(i // rows) % cols].addWidget(b) for each in vboxes: each.addStretch() wrapper.addLayout(each, stretch=int(100 / cols))
def initUI(self): stock_button = QPushButton("Stock") parts_button = QPushButton("Parts List") order_button = QPushButton("Start Order") clear_button = QPushButton("Clear") next_button = QPushButton("тедтед") stock_button.setAccessibleName("Stock") stock_button.clicked.connect(self.parent().stockButtonClicked) parts_button.clicked.connect(self.parent().partsButtonClicked) order_button.clicked.connect(self.parent().orderButtonClicked) clear_button.clicked.connect(self.parent().clearButtonClicked) next_button.clicked.connect(self.parent().nextButtonClicked) hbox = QHBoxLayout() vbox = QVBoxLayout() vbox.addWidget(stock_button) vbox.addWidget(parts_button) vbox.addWidget(order_button) vbox.addWidget(clear_button) vbox.addWidget(next_button) vbox.addStretch(1) hbox.addLayout(vbox) self.setLayout(hbox)
def __init__(self, win): QWidget.__init__(self) self.win = win self.setWindowTitle('Electrum - '+_('Payment Request')) self.setMinimumSize(800, 250) self.address = '' self.label = '' self.amount = 0 self.setFocusPolicy(QtCore.Qt.NoFocus) main_box = QHBoxLayout() self.qrw = QRCodeWidget() main_box.addWidget(self.qrw, 1) vbox = QVBoxLayout() main_box.addLayout(vbox) self.address_label = QLabel("") #self.address_label.setFont(QFont(MONOSPACE_FONT)) vbox.addWidget(self.address_label) self.label_label = QLabel("") vbox.addWidget(self.label_label) self.amount_label = QLabel("") vbox.addWidget(self.amount_label) vbox.addStretch(1) self.setLayout(main_box)
def createChartView( self, _x2idx: dict, _idx2x: list ) -> QHBoxLayout: chart = QChart() # assign y range self.calcRangeY() self.setAxisY(self.begin_y, self.end_y) value_layout = QFormLayout() # add each series for v in self.series_table.values(): v.addSeries(_x2idx, _idx2x, chart, self.axis_x, self.axis_y) if v.show_value: value_layout.addWidget(v.show_group) # create chartview and layout for view and value chartview = ChartView(chart, self.wizard) chartview.setRenderHint(QPainter.Antialiasing) global_layout = QHBoxLayout() global_layout.addWidget(chartview, self.chart_stretch) global_layout.addLayout(value_layout) return global_layout
def _show_templates(self): """ Update templates on shoeEvent. """ cols = 3 templates = template_module.Template.get_all() for j, item in enumerate(self.visible_items): if not templates[item.id]: l = QLabel("Нет шаблонов для данного объекта\nУправлять шаблонами можно на вкладке настроек") l.setAlignment(Qt.AlignCenter) self.templates_layout.addWidget(l) continue layouts = [QVBoxLayout() for _ in range(cols)] for i, each in enumerate(templates[item.id]): b = QRadioButton(each.name) b.setChecked(item.template == each) b.clicked.connect(functools.partial(self._template_clicked, j, each)) b.mouseDoubleClickEvent = functools.partial(self.open_template_edit_widget, j, each) layouts[i % cols].addWidget(b) wrapper = QHBoxLayout() for each in layouts: each.addStretch() wrapper.addLayout(each, stretch=int(100 / cols)) self.templates_layout.addWidget(utils.get_scrollable(wrapper))
def initUI(self): """Create User Interface. """ sourcePath = self.widgetSourcePath() parameters = self.widgetParameters() scroll = self.widgetImage() debug = self.widgetDebug() vbox1 = QVBoxLayout() vbox1.addLayout(sourcePath) hbox = QHBoxLayout() hbox.addLayout(parameters, 1) hbox.addLayout(scroll, 10) vbox1.addLayout(hbox) upSide = QWidget() upSide.setLayout(vbox1) vbox2 = QVBoxLayout() vbox2.addLayout(debug) downSide = QWidget() downSide.setLayout(vbox2) splitter = QSplitter(QtCore.Qt.Vertical) splitter.addWidget(upSide) splitter.addWidget(downSide) splitter.splitterMoved.connect(self.splitterMoved) mainLayout = QHBoxLayout() mainLayout.addWidget(splitter) self.setLayout(mainLayout) self.setGeometry(300, 300, 300, 150) self.show()
def _multipleChildLayout(self, formation, top): ''' A tree-like, indented layout/widget. name ------ | (recursion) | ''' if not top: # display formation name in the layout label = QLabel(formation.role + formation.name) self.addWidget(label) # else display name in window title indentedLayout = QHBoxLayout() indentedLayout.addSpacing(20) # Apparently pixels # Create lower right quadrant via recursion vLayout = QVBoxLayout() formation.displayContentsInLayout(vLayout) indentedLayout.addLayout(vLayout) self.addLayout(indentedLayout)
def init_ui(self): path = os.getcwd() url = path + HTM_FILE self.webView.setUrl(QtCore.QUrl(url)) self.webView.page().loadFinished.connect(self.load_finished) # for test self.inputText.setEnabled(False) self.inputText.setAcceptRichText(False) self.inputText.setToolTip("每行一组经纬度,纬度lat在前\n" + "以空格、逗号或制表符分隔") self.runButton.clicked.connect(self.add_points) # show all points in input text window self.clrButton.clicked.connect(self.clr_points) buttonBox = QHBoxLayout() # button box buttonBox.addStretch() buttonBox.addWidget(self.runButton) buttonBox.addWidget(self.clrButton) rightBox = QVBoxLayout() # right box rightBox.addWidget(self.sourceType) rightBox.addWidget(self.inputText) rightBox.addLayout(buttonBox) rightBox.addWidget(self.statusBar) layout = QHBoxLayout() # main box layout.addWidget(self.webView) layout.addLayout(rightBox) self.setLayout(layout) self.setWindowTitle('经纬度地图显示') self.show()
def __init__(self): super(self.__class__, self).__init__() self.name_label = QLabel("Name (optional):") self.name_line_edit = QLineEdit() self.introducer_label = QLabel("Introducer fURL:") self.introducer_text_edit = QPlainTextEdit() self.introducer_text_edit.setMaximumHeight(70) self.introducer_text_edit.setTabChangesFocus(True) self.description_label = QLabel("Description (optional):") self.description_text_edit = QPlainTextEdit() self.description_text_edit.setMaximumHeight(70) self.description_text_edit.setTabChangesFocus(True) self.push_button = QPushButton("Save") form = QFormLayout() form.setWidget(0, QFormLayout.LabelRole, self.name_label) form.setWidget(0, QFormLayout.FieldRole, self.name_line_edit) form.setWidget(1, QFormLayout.LabelRole, self.introducer_label) form.setWidget(1, QFormLayout.FieldRole, self.introducer_text_edit) #form.setWidget(2, QFormLayout.LabelRole, self.description_label) #form.setWidget(2, QFormLayout.FieldRole, self.description_text_edit) form.setWidget(3, QFormLayout.FieldRole, self.push_button) hbox = QHBoxLayout(self) #hbox.addItem(QSpacerItem(100, 0, QSizePolicy.Preferred, 0)) hbox.addLayout(form)
class QCustomQWidget (QWidget): def __init__(self, parent=None): super(QCustomQWidget, self).__init__(parent) self.textQVBoxLayout = QVBoxLayout() self.textQVBoxLayout.setContentsMargins(0, 0, 0, 0) self.textQVBoxLayout.setSpacing(0) self.textUpQLabel = QLabel() self.textDownQLabel = QLabel() self.textQVBoxLayout.addWidget(self.textUpQLabel) self.textQVBoxLayout.addWidget(self.textDownQLabel) self.allQHBoxLayout = QHBoxLayout() self.allQHBoxLayout.setContentsMargins(0, 0, 0, 0) self.allQHBoxLayout.setSpacing(3) self.iconQLabel = QLabel() self.allQHBoxLayout.addWidget(self.iconQLabel, 0) self.allQHBoxLayout.addLayout(self.textQVBoxLayout, 1) self.setLayout(self.allQHBoxLayout) # setStyleSheet self.textUpQLabel.setStyleSheet('''color: rgb(0, 0, 255);''') self.textDownQLabel.setStyleSheet('''color: rgb(0, 0, 0);''') def setTextUp(self, text): self.textUpQLabel.setText(text) def setTextDown(self, text): self.textDownQLabel.setText(text) def setIcon(self, imagePath): self.iconQLabel.setPixmap(QPixmap(imagePath))
def __init__(self, parent=None): super(CentralWidget, self).__init__(parent) self.parent = parent main_container = QHBoxLayout(self) main_container.setContentsMargins(0, 0, 0, 0) main_container.setSpacing(0) # This variables are used to save the spliiter sizes self.lateral_panel = LateralPanel() self._add_functions = { "central": self._insert_widget_inside, "lateral": self._insert_widget_base } self._items = {} # Toolbar self._toolbar = ntoolbar.NToolBar(self) main_container.addWidget(self._toolbar) # Create Splitters to divide the UI 3 regions self._splitter_base = dynamic_splitter.DynamicSplitter(Qt.Horizontal) self._splitter_inside = dynamic_splitter.DynamicSplitter(Qt.Vertical) self._splitter_base.addWidget(self._splitter_inside) vbox = QVBoxLayout() vbox.setContentsMargins(0, 0, 0, 0) vbox.setSpacing(0) vbox.addWidget(self._splitter_base) tools_dock = IDE.get_service("tools_dock") vbox.addWidget(tools_dock.buttons_widget) main_container.addLayout(vbox) # main_container.addWidget(self._splitter_base) IDE.register_service("central_container", self)
class AboutDialog(QDialog): def __init__(self, parent=None): super(AboutDialog, self).__init__(parent) self.setFixedSize(QtCore.QSize(250, 150)) self.setWindowTitle(i18n( "AboutDialog", 'About Gamelog')) self.widgetlayout = QHBoxLayout(self) self.iconlabel = QLabel(self) self.iconlabel.setMaximumSize(75, 75) self.iconlabel.setScaledContents(True) self.iconlabel.setPixmap(QtGui.QPixmap('icons/cards.png')) self.widgetlayout.addWidget(self.iconlabel) self.contentlayout = QVBoxLayout() self.widgetlayout.addLayout(self.contentlayout) self.title = QLabel("Gamelog") self.title.setStyleSheet("QLabel{font-size:18px; font-weight:bold}") self.title.setAlignment(QtCore.Qt.AlignLeft) self.contentlayout.addWidget(self.title) self.content = QLabel(i18n( "AboutDialog", 'Gamelog is a utility to keep track of the score in board games.')) self.content.setWordWrap(True) self.content.setAlignment(QtCore.Qt.AlignTop) self.contentlayout.addWidget(self.content) self.content = QLabel('Xavi Abellan 2012') self.content.setWordWrap(True) self.content.setAlignment(QtCore.Qt.AlignLeft) self.contentlayout.addWidget(self.content)
def inut_ui(self, name, args): vl = QVBoxLayout() lbl = QLabel(self) lbl.setAlignment(QtCore.Qt.AlignCenter) lbl.setText(name) vl.addWidget(lbl) hl = QHBoxLayout() il = QVBoxLayout() il.setAlignment(QtCore.Qt.AlignTop) for arg in args: if arg['io'] == 'i': inp_lbl = QLabel(self) self._inputs[arg['name']] = inp_lbl inp_lbl.setText(arg['name']) il.addWidget(inp_lbl) ol = QVBoxLayout() ol.setAlignment(QtCore.Qt.AlignTop) for arg in args: if arg['io'] == 'o': out_lbl = QLabel(self) self._outputs[arg['name']] = out_lbl out_lbl.setAlignment(QtCore.Qt.AlignRight) out_lbl.setText(arg['name']) ol.addWidget(out_lbl) hl.addLayout(il) hl.addLayout(ol) vl.addLayout(hl) self.setLayout(vl)
def __init__(self, options): super(GraphTab, self).__init__() self.options = options self.options.reset.connect(self.reset) self.options.redraw.connect(self.redraw) self.commodities = CommodityBox(options) self.commodities.changed.connect(self.redraw) self.fig = Figure() self.ax = self.fig.add_subplot(111) self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self) self.mpl_toolbar = NavigationToolbar(self.canvas, self) self.cmap = get_cmap('gist_ncar') graphLayout = QVBoxLayout() graphLayout.addWidget(self.canvas) graphLayout.addWidget(self.mpl_toolbar) layout = QHBoxLayout(self) layout.addWidget(self.commodities) layout.addLayout(graphLayout) self.running_total = None
def __init__(self, persepolis_setting): super().__init__() # defining UI self.persepolis_setting = persepolis_setting icons = ':/' + \ str(self.persepolis_setting.value('settings/icons')) + '/' self.setWindowIcon(QIcon.fromTheme('persepolis', QIcon(':/persepolis.svg'))) self.setWindowTitle('Checking for newer version') # installed version self.client_version = self.persepolis_setting.value('version/version') # first line text self.update_label = QLabel("The newest is the best , We recommend to update Persepolis") self.update_label.setTextFormat(QtCore.Qt.RichText) self.update_label.setAlignment(QtCore.Qt.AlignCenter) # second line text self.version_label = QLabel('This is Persepolis Download Manager version 2.5a0') self.version_label.setAlignment(QtCore.Qt.AlignCenter) # release link self.link_label = QLabel('<a href=https://github.com/persepolisdm/persepolis/releases>https://github.com/persepolisdm/persepolis/releases</a>') self.link_label.setAlignment(QtCore.Qt.AlignCenter) self.link_label.setOpenExternalLinks(True) # version status self.status_label = QLabel() self.status_label.setTextFormat(QtCore.Qt.RichText) self.status_label.setAlignment(QtCore.Qt.AlignCenter) # update button self.check_button = QPushButton("Check for new update") self.check_button.clicked.connect(self.updateCheck) # verticalLayout vbox = QVBoxLayout() vbox.addWidget(self.update_label) vbox.addWidget(self.version_label) vbox.addWidget(self.link_label) vbox.addWidget(self.check_button) vbox.addWidget(self.status_label) # horizontalLayout hbox = QHBoxLayout() hbox.addLayout(vbox) # window layout self.setLayout(hbox) # window size and position size = self.persepolis_setting.value( 'checkupdate/size', QSize(360, 250)) position = self.persepolis_setting.value( 'checkupdate/position', QPoint(300, 300)) self.resize(size) self.move(position)
class CustomWidget(QWidget): def __init__ (self, parent = None): super(CustomWidget, self).__init__(parent) self.textQVBoxLayout = QVBoxLayout() self.textUpQLabel = QLabel() self.textDownQLabel = QLabel() self.textQVBoxLayout.addWidget(self.textUpQLabel) self.textQVBoxLayout.addWidget(self.textDownQLabel) self.allQHBoxLayout = QHBoxLayout() self.progressBar = QProgressBar() self.allQHBoxLayout.addWidget(self.progressBar, 0) self.allQHBoxLayout.addLayout(self.textQVBoxLayout, 1) self.setLayout(self.allQHBoxLayout) # setStyleSheet self.textUpQLabel.setStyleSheet(''' color: rgb(0, 0, 255); ''') self.textDownQLabel.setStyleSheet(''' color: rgb(255, 0, 0); ''') def setTextUp (self, text): self.textUpQLabel.setText(text) def setTextDown (self, text): self.textDownQLabel.setText(text)
def __init__(self, options): super(BarTab, self).__init__() self.options = options self.options.reset.connect(self.reset) self.options.redraw.connect(self.redraw) self.classifiers = self.monthly self.fig = Figure() self.ax = self.fig.add_subplot(111) self.canvas = FigureCanvas(self.fig) self.canvas.setParent(self) self.mpl_toolbar = NavigationToolbar(self.canvas, self) self.cmap = get_cmap('gist_ncar') graphLayout = QVBoxLayout() graphLayout.addWidget(self.canvas) graphLayout.addWidget(self.mpl_toolbar) #optionLayout = QVBoxLayout(self) #optionLayout.addWidget(self.classifiers) layout = QHBoxLayout(self) layout.addLayout(graphLayout) self.series = None self.commodity = None
def __init__(self,parent=None): super().__init__(parent) label = QLabel(self.tr("Find &what:")) self.lineEdit = QLineEdit() label.setBuddy(self.lineEdit) self.caseCheckBox=QCheckBox(self.tr("Match &case")) self.backwardCheckBox=QCheckBox(self.tr("Search &backward")) self.findButton = QPushButton(self.tr("&Find")) self.findButton.setDefault(True) self.findButton.setEnabled(False) closeButton=QPushButton(self.tr("Close")) self.lineEdit.textChanged.connect(self.enableFindButton) self.findButton.clicked.connect(self.findClicked) closeButton.clicked.connect(self.close) topLeftLayout=QHBoxLayout() topLeftLayout.addWidget(label) topLeftLayout.addWidget(self.lineEdit) leftLayout=QVBoxLayout() leftLayout.addLayout(topLeftLayout) leftLayout.addWidget(self.caseCheckBox) leftLayout.addWidget(self.backwardCheckBox) rightLayout = QVBoxLayout() rightLayout.addWidget(self.findButton) rightLayout.addWidget(closeButton) rightLayout.addStretch() mainLayout=QHBoxLayout() mainLayout.addLayout(leftLayout) mainLayout.addLayout(rightLayout) self.setLayout(mainLayout) self.setWindowTitle(self.tr("Find")) self.setFixedHeight(self.sizeHint().height())
def setCanvasWidgetLayout(self): self.codeWidget = CodeWidget(self) self.mapWidget = MemoryMappingWidget(self) self.emuWidget = EmulatorWidget(self) self.logWidget = LogWidget(self) self.commandWidget = CommandWidget(self) self.registerWidget = RegistersWidget(self) self.memoryViewerWidget = MemoryWidget(self) self.runtimeTabWidget = QTabWidget() self.runtimeTabWidget.addTab(self.emuWidget, "Emulator") self.runtimeTabWidget.addTab(self.logWidget, "Log") self.runtimeTabWidget.addTab(self.mapWidget, "Mappings") self.AddPluginsToTab(self.runtimeTabWidget) # load additional modules runtimeVBoxLayout = QVBoxLayout() runtimeVBoxLayout.addWidget(self.memoryViewerWidget) runtimeVBoxLayout.addWidget(self.commandWidget) runtimeVBoxLayout.addWidget(self.runtimeTabWidget) rootLayout = QHBoxLayout() rootLayout.addWidget(self.registerWidget, 20) rootLayout.addWidget(self.codeWidget, 33) rootLayout.addLayout(runtimeVBoxLayout, 47) self.setLayout(rootLayout) return
def __init__(self): """The constructor initializes the class AboutDialog.""" super().__init__() self.setAttribute(Qt.WA_DeleteOnClose) # initialize class constants self._BUTTON_MIN_WIDTH = 110 self._OXYGEN_PATH_48 = os.path.join("resources", "icons", "oxygen", "48") # fonts and margins settings hlFont = QFont() hlFont.setBold(True) hlFont.setPointSize(14) # scientific logo logo = QLabel(pixmap=QPixmap(os.path.join(self._OXYGEN_PATH_48, "applications-science.png"))) logoLayout = QVBoxLayout() logoLayout.addWidget(logo) logoLayout.addStretch() # begin the content # headline and description text self.headline = QLabel() self.headline.setFont(hlFont) self.description = QLabel(wordWrap=True) # the list with the open button self.listWidget = QListWidget() self.listWidget.setMinimumWidth(420) self.createArticles() self.openButton = QPushButton() self.openButton.clicked.connect(self.openAction) listLayout = QHBoxLayout() listLayout.addWidget(self.listWidget) listLayout.addWidget(self.openButton, alignment=Qt.AlignTop) # create a close button line = QFrame(frameShadow=QFrame.Sunken, frameShape=QFrame.HLine) self.closeButton = QPushButton() self.closeButton.setFixedWidth(self._BUTTON_MIN_WIDTH) self.closeButton.clicked.connect(self.close) # content layout contentLayout = QVBoxLayout() contentLayout.addWidget(self.headline) contentLayout.addWidget(self.description) contentLayout.addLayout(listLayout) contentLayout.addWidget(line) contentLayout.addWidget(self.closeButton, alignment=Qt.AlignRight) # main layout layout = QHBoxLayout(self) layout.addLayout(logoLayout) layout.addLayout(contentLayout) # translate the graphical user interface self.retranslateUi()
def __init__(self, parent, app): super().__init__() layout1 = QHBoxLayout() layout2 = QVBoxLayout() layout1.addStretch() layout1.addLayout(layout2) layout1.addStretch() label = QLabel(self) label.setText("Simple Project: <b>Display Environment Measurements on LCD</b>. Simply displays all measured values on LCD. Sources in all programming languages can be found <a href=\"http://www.tinkerforge.com/en/doc/Kits/WeatherStation/WeatherStation.html#display-environment-measurements-on-lcd\">here</a>.<br>") label.setTextFormat(Qt.RichText) label.setTextInteractionFlags(Qt.TextBrowserInteraction) label.setOpenExternalLinks(True) label.setWordWrap(True) label.setAlignment(Qt.AlignJustify) layout2.addSpacing(10) layout2.addWidget(label) layout2.addSpacing(10) self.lcdwidget = LCDWidget(self, app) layout2.addWidget(self.lcdwidget) layout2.addStretch() self.setLayout(layout1) self.qtcb_update_illuminance.connect(self.update_illuminance_data_slot) self.qtcb_update_air_pressure.connect(self.update_air_pressure_data_slot) self.qtcb_update_temperature.connect(self.update_temperature_data_slot) self.qtcb_update_humidity.connect(self.update_humidity_data_slot) self.qtcb_button_pressed.connect(self.button_pressed_slot)
def __init__(self, name, stringlist=None, parent=None): super(StringListDlg, self).__init__(parent) self.name = name self.listWidget = QListWidget() if stringlist is not None: self.listWidget.addItems(stringlist) self.listWidget.setCurrentRow(0) buttonLayout = QVBoxLayout() for text, slot in (("&Add...", self.add), ("&Edit...", self.edit), ("&Remove...", self.remove), ("&Up", self.up), ("&Down", self.down), ("&Sort", self.listWidget.sortItems), ("Close", self.accept)): button = QPushButton(text) if not MAC: button.setFocusPolicy(Qt.NoFocus) if text == "Close": buttonLayout.addStretch() buttonLayout.addWidget(button) button.clicked.connect(slot) # self.connect(button, SIGNAL("clicked()"), slot) layout = QHBoxLayout() layout.addWidget(self.listWidget) layout.addLayout(buttonLayout) self.setLayout(layout) self.setWindowTitle("Edit {0} List".format(self.name))
def createDesktopOption(self, layout): hlayout = QHBoxLayout() layout.addLayout(hlayout) vlayout1 = QVBoxLayout() vlayout2 = QVBoxLayout() hlayout.addLayout(vlayout1) hlayout.addLayout(vlayout2) label1 = QLabel() label1.setText(self.tr("Desktop Type")) vlayout1.addWidget(label1) label2 = QLabel() label2.setText(self.tr("Number of Desktops")) vlayout2.addWidget(label2) comboBox = QComboBox() comboBox.addItem(self.tr("Desktop View")) comboBox.addItem(self.tr("Folder View")) comboBox.currentIndexChanged.connect(self.desktopTypeCreate) vlayout1.addWidget(comboBox) spinBox = QSpinBox() spinBox.setMinimum(1) spinBox.setMaximum(20) spinBox.valueChanged.connect(self.desktopCreate) vlayout2.addWidget(spinBox)
def __init__(self, parent=None): """Initialize the preferences dialog with a list box and a content layout.""" super(PreferencesDialog, self).__init__(parent) self.setWindowTitle('Preferences') settings_icon = utilities.resource_filename('mosaic.images', 'md_settings.png') self.setWindowIcon(QIcon(settings_icon)) self.resize(600, 450) self.contents = QListWidget() self.contents.setFixedWidth(175) self.pages = QStackedWidget() self.button_box = QDialogButtonBox(QDialogButtonBox.Ok) self.dialog_media_library = MediaLibrary() self.dialog_playback = Playback() self.dialog_view_options = ViewOptions() self.pages.addWidget(self.dialog_media_library) self.pages.addWidget(self.dialog_playback) self.pages.addWidget(self.dialog_view_options) self.list_items() stack_layout = QVBoxLayout() stack_layout.addWidget(self.pages) stack_layout.addWidget(self.button_box) layout = QHBoxLayout() layout.addWidget(self.contents) layout.addLayout(stack_layout) self.setLayout(layout) self.contents.currentItemChanged.connect(self.change_page) self.button_box.accepted.connect(self.accept)
def setupUi(self, Widget): # widgety rysujące kształty, instancje klasy Ksztalt self.ksztalt1 = Ksztalt(self, Ksztalty.Polygon) self.ksztalt2 = Ksztalt(self, Ksztalty.Ellipse) self.ksztaltAktywny = self.ksztalt1 # przyciski CheckBox ### uklad = QVBoxLayout() # układ pionowy self.grupaChk = QButtonGroup() for i, v in enumerate(('Kwadrat', 'Koło', 'Trójkąt', 'Linia')): self.chk = QCheckBox(v) self.grupaChk.addButton(self.chk, i) uklad.addWidget(self.chk) self.grupaChk.buttons()[self.ksztaltAktywny.ksztalt].setChecked(True) # CheckBox do wyboru aktywnego kształtu self.ksztaltChk = QCheckBox('<=') self.ksztaltChk.setChecked(True) uklad.addWidget(self.ksztaltChk) # układ poziomy dla kształtów oraz przycisków CheckBox ukladH1 = QHBoxLayout() ukladH1.addWidget(self.ksztalt1) ukladH1.addLayout(uklad) ukladH1.addWidget(self.ksztalt2) # koniec CheckBox ### self.setLayout(ukladH1) # przypisanie układu do okna głównego self.setWindowTitle('Widżety')
def init_ui(self): """Initialize the Edit Widget""" plot_window_button = QPushButton('Select Plot Window', self) plot_window_button.clicked.connect(self.select_plot) plot_button = QPushButton('Plot Data', self) plot_button.clicked.connect(self.plot) color_button = QPushButton('Change Color', self) color_button.clicked.connect(lambda: self.plot_window.color_change(self.line_box)) style_button = QPushButton('Change Style', self) style_button.clicked.connect(lambda: self.plot_window.line_style_change(self.line_box)) remove_button = QPushButton('Remove Plot', self) remove_button.clicked.connect(lambda: self.plot_window.remove_plot(self.line_box)) button_vertical_box = QVBoxLayout() button_vertical_box.addWidget(self.line_box) button_vertical_box.addStretch(1) button_vertical_box.addWidget(plot_window_button) button_vertical_box.addWidget(color_button) button_vertical_box.addWidget(style_button) button_vertical_box.addWidget(plot_button) button_vertical_box.addWidget(remove_button) main_horizontal_box = QHBoxLayout() main_horizontal_box.addLayout(button_vertical_box) self.setLayout(main_horizontal_box) self.setGeometry(self.left, self.top, self.width, self.height)
def initUI(self): main_layout = QVBoxLayout(self) sub_layout = QHBoxLayout() # Left Panel left_panel = QListWidget() left_panel.setViewMode(left_panel.ListMode) #left_panel.setIconSize(QSize(40,40)) left_panel.setTextElideMode(Qt.ElideRight) left_panel.setMaximumWidth(200) left_panel.itemClicked.connect(self.change) #web.setText('Web') self.application = QListWidgetItem() self.application.setText('Application') self.web = QListWidgetItem() self.web.setText('Web') self.visual = QListWidgetItem() self.visual.setText('Visual') self.advanced = QListWidgetItem() self.advanced.setText('Advanced') self.about = QListWidgetItem() self.about.setText('About') #main.setIcon(QIcon(os.path.join(app_constants.static_dir, 'plus2.png'))) left_panel.addItem(self.application) left_panel.addItem(self.web) left_panel.addItem(self.visual) left_panel.addItem(self.advanced) left_panel.addItem(self.about) left_panel.setMaximumWidth(100) # right panel self.right_panel = QStackedLayout() self.init_right_panel() # bottom bottom_layout = QHBoxLayout() ok_btn = QPushButton('Ok') ok_btn.clicked.connect(self.accept) cancel_btn = QPushButton('Cancel') cancel_btn.clicked.connect(self.close) info_lbl = QLabel() info_lbl.setText('<a href="https://github.com/Pewpews/happypanda">'+ 'Visit GitHub Repo</a> | Options marked with * requires application restart.') info_lbl.setTextFormat(Qt.RichText) info_lbl.setTextInteractionFlags(Qt.TextBrowserInteraction) info_lbl.setOpenExternalLinks(True) self.spacer = QWidget() self.spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) bottom_layout.addWidget(info_lbl, 0, Qt.AlignLeft) bottom_layout.addWidget(self.spacer) bottom_layout.addWidget(ok_btn, 0, Qt.AlignRight) bottom_layout.addWidget(cancel_btn, 0, Qt.AlignRight) sub_layout.addWidget(left_panel) sub_layout.addLayout(self.right_panel) main_layout.addLayout(sub_layout) main_layout.addLayout(bottom_layout) self.restore_options()
class PreviewWidgetColor(QGroupBox): def __init__(self, parent=None): super().__init__(parent) self.setTitle(self.tr("Preview")) self.setMaximumHeight(120) self.parent = parent vboxLayout = QVBoxLayout(self) self.previewGroupBox = QGroupBox(self) self.previewGroupBox.setObjectName("previewGroupBox") vboxLayout.addWidget(self.previewGroupBox) self.horizontalLayout = QHBoxLayout(self.previewGroupBox) self.verticalLayout = QVBoxLayout() self.horizontalLayout.addLayout(self.verticalLayout) self.previewLabel = QLabel(self.previewGroupBox) self.previewLabel.setText(self.tr("Window Text")) self.previewLabel.setObjectName("previewLabel") self.verticalLayout.addWidget(self.previewLabel) self.previewPushButton = QPushButton(self.previewGroupBox) self.previewPushButton.setText(self.tr("Button")) self.previewPushButton.setObjectName("previewPushButton") self.verticalLayout.addWidget(self.previewPushButton) self.previewTextBrowser = QTextBrowser(self.previewGroupBox) self.previewTextBrowser.setObjectName("previewTextBrowser") css = iniToCss(os.path.join("/usr/share/color-schemes", self.parent.children()[1].currentItem().colorSchemeName)) self.previewTextBrowser.setHtml("""<style>#unclicked {color : rgb(%s);} #clicked {color : rgb(%s);}</style>"""%(css[1][0],css[1][1]) + self.tr("""<p>Normal text <a id='unclicked' href='#'>link</a> <a id='clicked' href='#'>visited</a></p>""")) self.horizontalLayout.addWidget(self.previewTextBrowser) self.previewPushButton.installEventFilter(self.previewGroupBox) self.previewPushButton.setFocusPolicy(Qt.NoFocus) self.previewTextBrowser.installEventFilter(self.previewGroupBox) self.previewTextBrowser.setFocusPolicy(Qt.NoFocus) self.previewTextBrowser.setTextInteractionFlags(Qt.NoTextInteraction) def eventFilter(self, obj, event): if self.previewPushButton: if event.type() == QEvent.MouseButtonRelease: return True elif event.type() == QEvent.MouseButtonPress: return True elif event.type() == QEvent.MouseButtonDblClick: return True else: return False else: super().eventFilter(obj, event)
def initUI(self): btn1 = QPushButton("Player") btn2 = QPushButton("Bank") for btn in [btn1, btn2]: btn.setMinimumWidth(100) btn.setMinimumHeight(70) self.lbl = QLabel('$0') self.lbl.setFrameShape(QFrame.WinPanel) self.lbl.setFrameShadow(QFrame.Sunken) # self.lbl.setContentsMargins(15, 15, 15, 15) self.lbl.setMinimumHeight(30) self.lbl.setMinimumWidth(100) self.lbl.setStyleSheet(""" .QLabel { color: red } """) lbl2 = QLabel('Bet: ') hlabels = ['partner', 'level', 'index', 'play', 'bet', 'result', 'net'] vlabels = [gambler.name for gambler in self.game.gamblers] self.tbl = QTableWidget(len(vlabels), len(hlabels)) self.tbl.setHorizontalHeaderLabels(hlabels) self.tbl.setVerticalHeaderLabels(vlabels) lbl_box = QHBoxLayout() lbl_box.addWidget(lbl2) lbl_box.addWidget(self.lbl) lbl_box.addStretch(1) # lbl_box.setContentsMargins(10, 10, 10, 10) btn_box = QHBoxLayout() btn_box.addWidget(btn1) btn_box.addWidget(btn2) btn_box.addLayout(lbl_box) btn_box.addStretch(1) tbl_box = QHBoxLayout() tbl_box.addWidget(self.tbl) layout = QVBoxLayout() layout.addLayout(btn_box) # layout.addLayout(lbl_box) layout.addLayout(tbl_box) layout.addStretch(1) # tbl.resizeColumnsToContents() # tbl.resizeRowsToContents() btn1.clicked.connect(self.buttonClicked) btn2.clicked.connect(self.buttonClicked) self.setLayout(layout) self.setGeometry(300, 300, 800, 400) self.setWindowTitle('Event Sender') self.show()
class RPNCalcUi(QWidget): def __init__(self): super().__init__() self.setWindowTitle("RPN Calculator") self.masterLayout = QHBoxLayout() #Master layout for the program self.leftLayout = QVBoxLayout( ) #Layout for the keyboard and the input screen self.rightLayout = QVBoxLayout() #Layout for the stack display #Create buttons and displays self.criaWidgetEntrada() self.criaBotoes() self.criaDisplayPilha() self._setUpLayouts() self.setLayout(self.masterLayout) def criaWidgetEntrada(self): self.inputWidget = QLineEdit() self.leftLayout.addWidget(self.inputWidget) def criaBotoes(self): self.buttons = {} buttonsLayout = QGridLayout() #We will use a map to declare the buttons #The index is the button text and the tuple value indicates the position #of the button on the app keyboard self.buttons = { '^': (0, 0), 'Switch': (0, 1), 'Backspace': (0, 2), 'Enter': (0, 3), '7': (1, 0), '8': (1, 1), '9': (1, 2), '/': (1, 3), '4': (2, 0), '5': (2, 1), '6': (2, 2), '*': (2, 3), '1': (3, 0), '2': (3, 1), '3': (3, 2), '-': (3, 3), '0': (4, 0), '.': (4, 1), 'Space': (4, 2), '+': (4, 3), } #Creating the buttons based on the map for text, pos in self.buttons.items(): self.buttons[text] = QPushButton(text) buttonsLayout.addWidget(self.buttons[text], pos[0], pos[1]) self.leftLayout.addLayout(buttonsLayout) def criaDisplayPilha(self): self.stackLabels = [] for x in range(0, 5): self.stackLabels.append(QLabel(text=str(x) + ': ')) self.rightLayout.addWidget(self.stackLabels[x]) def _setUpLayouts(self): self.masterLayout.addLayout(self.leftLayout) self.masterLayout.addLayout(self.rightLayout) def setDisplaytext(self, message): self.inputWidget.setText(message) self.inputWidget.setFocus() def getDisplayText(self): return self.inputWidget.text() def clearDisplay(self): self.inputWidget.setText('') def showInputPopUpErrorMessage(self, listaStringsErrados): mensagemDeErro = self.compoeMensagemDeErroDeEntrada( listaStringsErrados) msg = QMessageBox() msg.setWindowTitle("Error") msg.setText(mensagemDeErro) msg.setIcon(QMessageBox.Warning) x = msg.exec_() def compoeMensagemDeErroDeEntrada(self, listaStringsErrados): mensagemDeErro = "Error - The following entries are invalid:\n" for item in listaStringsErrados: mensagemDeErro += item mensagemDeErro += " " return mensagemDeErro
def init_ui(self): hlay_addr = QHBoxLayout() hlay_addr.addWidget(QLabel('画廊地址')) hlay_addr.addWidget(self.ledit_addr) hlay_addr.setStretch(0, 0) hlay_cbox = QHBoxLayout() hlay_cbox.addWidget(self.cbox_rename) hlay_cbox.addWidget(self.cbox_rewrite) hlay_cbox.addStretch(1) hlay_cbox.addWidget(QLabel('从')) hlay_cbox.addWidget(self.sbox_begin_page) hlay_cbox.addWidget(QLabel('下载至')) hlay_cbox.addWidget(self.sbox_end_page) hlay_cbox.addWidget(QLabel('页')) hlay_cbox.setAlignment(Qt.AlignLeft) hlay_acts = QHBoxLayout() hlay_acts.addStretch(1) hlay_acts.addWidget(self.btn_get) hlay_acts.addWidget(self.btn_add) hlay_acts.addWidget(self.btn_remove) hlay_acts.addWidget(self.btn_start) hlay_acts.addStretch(1) vlay_left = QVBoxLayout() vlay_left.addLayout(hlay_addr) vlay_left.addLayout(hlay_cbox) vlay_left.addLayout(hlay_acts) left_wid = QWidget() left_wid.setLayout(vlay_left) vlay_right = QVBoxLayout() vlay_right.addWidget(self.user_info, alignment=Qt.AlignHCenter) vlay_right.addWidget(self.btn_refresh) vlay_right.addWidget(self.btn_logout) right_wid = QWidget() right_wid.setLayout(vlay_right) splitter = QSplitter(Qt.Horizontal) splitter.setHandleWidth(3) splitter.addWidget(left_wid) splitter.addWidget(right_wid) splitter.setStretchFactor(0, 1) splitter.setStretchFactor(1, 0) splitter.handle(1).setDisabled(True) vlay_info = QVBoxLayout() vlay_info.addWidget(self.thumbnail) vlay_info.addWidget(self.info) hlay_down = QHBoxLayout() hlay_down.addLayout(vlay_info) hlay_down.addWidget(self.que) vlay_main = QVBoxLayout() vlay_main.addWidget(splitter) vlay_main.addLayout(hlay_down) self.setLayout(vlay_main) self.thumbnail.setFixedHeight(left_wid.sizeHint().height()) self.thumbnail.setFixedWidth(250) self.thumbnail.setFixedHeight(360) self.thumbnail.setPixmap(self.thumb_default) if self.show_thumb_flag: # Cannot put code after show(), or flick self.thumbnail.show() else: self.thumbnail.hide()
def __init__(self, hbox_control): super(MyGridWidget, self).__init__() self.hbox_image_list = [] self.label_list = [] self.layout = QVBoxLayout() self.setLayout(self.layout) ############################################### # ---------- left & right init ---------------- ############################################### self.right_layout_width = 200 window_layouts = QHBoxLayout(self) window_layouts.setContentsMargins(0, 0, 0, 0) window_layouts.setSpacing(0) window_layouts.setAlignment(QtCore.Qt.AlignCenter) self.left_layout = QVBoxLayout(self) self.left_layout.setContentsMargins(0, 0, 0, 0) self.left_layout.setSpacing(0) self.left_layout.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop) self.right_layout = QVBoxLayout(self) self.right_layout.setContentsMargins(0, 0, 0, 0) self.right_layout.setSpacing(0) self.right_layout.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop) window_layouts.addLayout(self.left_layout) window_layouts.addLayout(self.right_layout) self.layout.addLayout(window_layouts) ############################################### # --------- elements initializing ------------- ############################################### self.label_layout = QVBoxLayout(self) self.label_layout.setContentsMargins(0, 0, 0, 0) self.label_layout.setSpacing(0) self.label_layout.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop) from screeninfo import get_monitors m = get_monitors()[0] self.max_width = m.width self.max_height = m.height - 100 self.groubBox = QGroupBox() self.left_scroll_area = MyScrollArea() self.groubBox.setLayout(self.label_layout) self.left_scroll_area.setWidget(self.groubBox) self.left_layout.addWidget(self.left_scroll_area) self.left_layout.addLayout(self.label_layout) self.hbox_control = hbox_control self.layout.addLayout(self.hbox_control) self.layout.setContentsMargins(0, 0, 0, 0) self.layout.setSpacing(0) self.left_scroll_area.setWidgetResizable(True) self.left_scroll_area.setFixedWidth(self.max_width) self.left_scroll_area.setFixedHeight(self.max_height)
def __init__(self): super(Config, self).__init__() config_group = QtWidgets.QGroupBox(u"参数配置") lineconfig_group = QtWidgets.QGroupBox(u"线条风格配置") axisconfig_group = QtWidgets.QGroupBox(u"坐标轴风格配置") lineshow_group = QtWidgets.QGroupBox(u"线条风格预览") result_group = QtWidgets.QGroupBox(u"结果展示") # 当前绘图结果 self.fig = None # 当前绘图总数据保存 # 坐标轴信息 self.min_x = 0. self.max_x = 1. self.min_y = 0. self.max_y = 1. self.x_text = u'The number of retrived samples' self.y_text = u'precision @ 256 bins' self.x_tick_list = [0., 0.5, 1.] self.x_label_list = ['0', '0.5', '1.0'] self.y_tick_list = [0., 0.5, 1.] self.y_label_list = ['0', '0.5', '1.0'] # 已有曲线信息 self.formula_list = [] self.ls_list = [] self.lc_list = [] self.lt_list = [] self.mark_list = [] self.mark_density_list = [] # 当前绘图曲线元数据保存 self.ls = '-' self.mark = 'o' self.formula = 'y=x**2' self.lc = '#00ff00' self.lt = 'Our Method' self.md = 5 # 状态栏 self.statusBar = QStatusBar() self.statusBar.setFont(QFont(u'华文楷体', 10)) self.statusBar.showMessage(u"准备就绪") # 编辑公式 self.math = QLineEdit() self.math.setPlaceholderText(u'y=x**2') self.math.setClearButtonEnabled(True) # 线条风格 self.linestyle = QComboBox() self.line_list = ["-", "--", "-.", ":"] for each in self.line_list: self.linestyle.addItem(each) # 标记风格 self.markerstyle = QComboBox() self.marker_list = [ ".", ",", "o", "v", "^", "<", ">", "1", "2", "3", "4" "s", "p", "*", "h", "H", "+", "x", "D", "d", "|", "_" ] for each in self.marker_list: self.markerstyle.addItem(each) # 设置线条标签名称 self.label = QLineEdit() self.label.setPlaceholderText(u'Our Method') self.label.setClearButtonEnabled(True) # 设置线条颜色 self.lineColor = QPushButton('更改线条颜色') self.lineColor.setToolTip("点击此按钮将更改线条颜色!") self.lineColor.setStatusTip("点击此按钮将更改线条颜色!") self.lineColor.clicked.connect(self.changeColor) self.lineColor.resize(self.lineColor.sizeHint()) self.lineColor.installEventFilter(self) # 设置标记密集程度 self.markDensity = QSlider(Qt.Horizontal) self.markDensity.setMinimum(1) self.markDensity.setMaximum(50) self.markDensity.setValue(5) self.markDensity.installEventFilter(self) # 横坐标轴范围 self.x_scale = QLineEdit() self.x_scale.setPlaceholderText(u'0,1') self.x_scale.setClearButtonEnabled(True) # 纵坐标轴范围 self.y_scale = QLineEdit() self.y_scale.setPlaceholderText(u'0,1') self.y_scale.setClearButtonEnabled(True) # 横坐标轴标签名称 self.x_label = QLineEdit() self.x_label.setPlaceholderText(u'The number of retrived samples') self.x_label.setClearButtonEnabled(True) # 纵坐标轴标签名称 self.y_label = QLineEdit() self.y_label.setPlaceholderText(u'precision @ 256 bins') self.y_label.setClearButtonEnabled(True) # 横坐标刻度数量 self.x_ticks = QLineEdit() self.x_ticks.setPlaceholderText(u'100') self.x_ticks.setClearButtonEnabled(True) # 纵坐标刻度数量 self.y_ticks = QLineEdit() self.y_ticks.setPlaceholderText(u'100') self.y_ticks.setClearButtonEnabled(True) # 线条风格预览按钮 self.lineview = QPushButton(u'预览') self.lineview.setToolTip("线条预览!") self.lineview.setStatusTip("线条预览!") self.lineview.clicked.connect(self.showLine) self.lineview.installEventFilter(self) # 布局设置 main_layout = QVBoxLayout() # 参数外层布局 config_outer_layout = QVBoxLayout() # 参数内层布局配置 config_inner_layout = QHBoxLayout() config_inner_layout.addWidget(lineconfig_group) config_inner_layout.setStretchFactor(lineconfig_group, 1) config_inner_layout.addWidget(axisconfig_group) config_inner_layout.setStretchFactor(axisconfig_group, 1) config_inner_layout.addWidget(lineshow_group) config_inner_layout.setStretchFactor(lineshow_group, 1) # 线条布局 line_layout = QFormLayout() line_layout.addRow(u'编辑公式', self.math) line_layout.addRow(u'线条风格', self.linestyle) line_layout.addRow(u'标记风格', self.markerstyle) line_layout.addRow(u'标签名称', self.label) line_layout.addRow(u'颜色配置', self.lineColor) line_layout.addRow(u'标记密度', self.markDensity) lineconfig_group.setLayout(line_layout) # 坐标轴布局 tick_layout = QFormLayout() tick_layout.addRow(u'横坐标轴范围', self.x_scale) tick_layout.addRow(u'纵坐标轴范围', self.y_scale) tick_layout.addRow(u'横坐标轴标签名称', self.x_label) tick_layout.addRow(u'纵坐标轴标签名称', self.y_label) tick_layout.addRow(u'横坐标刻度数量', self.x_ticks) tick_layout.addRow(u'纵坐标刻度数量', self.y_ticks) axisconfig_group.setLayout(tick_layout) # 预览布局 view = QVBoxLayout() # 预览显示 self.view_face = QMainWindow() view.addWidget(self.view_face) # 预览按钮 view.addWidget(self.lineview) lineshow_group.setLayout(view) # 中层按钮定义 # 按钮一:显示最终结果 # 按钮二:添加新的线条 # 按钮三:删除最近一条线条 # 按钮四:保存图像 self.showresult = QPushButton(u'刷新视图') self.showresult.setToolTip(u'刷新视图!') self.showresult.clicked.connect(self.resultShow) self.showresult.installEventFilter(self) self.addline = QPushButton(u'新增线条') self.addline.setToolTip(u'新增一条曲线!') self.addline.clicked.connect(self.addLine) self.addline.installEventFilter(self) self.removeline = QPushButton(u'删除线条') self.removeline.setToolTip(u'删除最近一条曲线!') self.removeline.clicked.connect(self.removeLine) self.removeline.installEventFilter(self) self.savefig = QPushButton(u'保存结果') self.savefig.setToolTip(u'将当前结果保存为高清图片!') self.savefig.clicked.connect(self.saveFig) self.savefig.installEventFilter(self) # 中层按钮布局 center_layout = QHBoxLayout() center_layout.addWidget(self.showresult) center_layout.addWidget(self.addline) center_layout.addWidget(self.removeline) center_layout.addWidget(self.savefig) # 第三层按钮定义 file_layout = QHBoxLayout() left_layout = QHBoxLayout() leftl_layout = QFormLayout() self.x_file_path = QLineEdit() self.x_file_path.setFixedHeight(20) leftl_layout.addRow(u"X轴:", self.x_file_path) leftr_layout = QVBoxLayout() x_file_option = QPushButton("选择") x_file_option.setFixedWidth(35) x_file_option.setFixedHeight(20) x_file_option.clicked.connect(self.xFile) leftr_layout.addWidget(x_file_option) left_layout.addLayout(leftl_layout) left_layout.addLayout(leftr_layout) right_layout = QHBoxLayout() rightl_layout = QFormLayout() self.y_file_path = QLineEdit() self.y_file_path.setFixedHeight(20) rightl_layout.addRow(u"Y轴:", self.y_file_path) rightr_layout = QVBoxLayout() y_file_option = QPushButton("选择") y_file_option.setFixedWidth(35) y_file_option.setFixedHeight(20) y_file_option.clicked.connect(self.yFile) rightr_layout.addWidget(y_file_option) right_layout.addLayout(rightl_layout) right_layout.addLayout(rightr_layout) self.selection = QCheckBox(u"自适应") okbt = QPushButton(u"确定") okbt.clicked.connect(self.xyPlot) file_layout.addLayout(left_layout) file_layout.addLayout(right_layout) file_layout.addWidget(self.selection) file_layout.addWidget(okbt) # 设置布局中控件的间距 left_layout.setSpacing(3) right_layout.setSpacing(3) file_layout.setSpacing(20) # 下层状态栏 bottom_layout = QVBoxLayout() bottom_layout.addWidget(self.statusBar) config_outer_layout.addItem(config_inner_layout) config_outer_layout.addItem(center_layout) config_outer_layout.addItem(file_layout) config_outer_layout.addItem(bottom_layout) config_group.setLayout(config_outer_layout) # 结果展示栏,设置为mainWindow result = QVBoxLayout() self.result = QMainWindow() result.addWidget(self.result) result_group.setLayout(result) main_layout.addWidget(config_group) main_layout.setStretchFactor(config_group, 1) main_layout.addWidget(result_group) main_layout.setStretchFactor(result_group, 2) self.setLayout(main_layout) cp = QDesktopWidget().availableGeometry().center() window_width = int(cp.x() * 2 * 0.7) window_height = int(cp.y() * 2 * 0.7) self.setGeometry(cp.x() - window_width // 2, cp.y() - window_height // 2, window_width, window_height)
def __InitView(self): ''' 初始化界面 ''' #新建一个水平布局作为本窗体的主布局 main_layout = QHBoxLayout(self) #设置主布局内边距以及控件间距为10px main_layout.setSpacing(10) #在主界面左侧放置画板 main_layout.addWidget(self.__paintBoard) #新建垂直子布局用于放置按键 sub_layout = QVBoxLayout() #设置此子布局和内部控件的间距为10px sub_layout.setContentsMargins(10, 10, 10, 10) self.__btn_Clear = QPushButton("清空画板") self.__btn_Clear.setParent(self) #设置父对象为本界面 #将按键按下信号与画板清空函数相关联 self.__btn_Clear.clicked.connect(self.__paintBoard.Clear) sub_layout.addWidget(self.__btn_Clear) self.setFixedSize(660,480) self.setWindowTitle("手写数字识别") ''' ''' ''' self.label_name = QLabel('江西理工大学', self) self.label_name.setGeometry(500,200,120,35) self.label_name = QLabel('信息工程学院', self) self.label_name.setGeometry(500,230,100,35) self.label_name = QLabel('电信172', self) self.label_name.setGeometry(500,260,100,35) self.label_name = QLabel('夏奥', self) self.label_name.setGeometry(500,290,100,35) ''' self.label_name=QLabel('识别结果',self) self.label_name.setGeometry(500,200,100,35) self.__btn_Recognize=QPushButton("开始识别") self.__btn_Recognize.setParent(self) self.__btn_Recognize.clicked.connect(self.on_btn_Recognize_Clicked) sub_layout.addWidget(self.__btn_Recognize) self.__btn_Quit = QPushButton("退出") self.__btn_Quit.setParent(self) #设置父对象为本界面 self.__btn_Quit.clicked.connect(self.Quit) sub_layout.addWidget(self.__btn_Quit) self.lcd_num=QLCDNumber(13,self) #self.lcd_num.resize(100,100) self.lcd_num.setDigitCount(1) self.lcd_num.move(500,400) sub_layout.addWidget(self.lcd_num) ''' self.__btn_Save = QPushButton("保存作品") self.__btn_Save.setParent(self) self.__btn_Save.clicked.connect(self.on_btn_Save_Clicked) sub_layout.addWidget(self.__btn_Save) ''' ''' self.__cbtn_Eraser = QCheckBox(" 使用橡皮擦") self.__cbtn_Eraser.setParent(self) self.__cbtn_Eraser.clicked.connect(self.on_cbtn_Eraser_clicked) sub_layout.addWidget(self.__cbtn_Eraser) ''' splitter = QSplitter(self) #占位符 sub_layout.addWidget(splitter) self.__label_penThickness = QLabel(self) self.__label_penThickness.setText("画笔粗细") self.__label_penThickness.setFixedHeight(20) sub_layout.addWidget(self.__label_penThickness) self.__spinBox_penThickness = QSpinBox(self) self.__spinBox_penThickness.setMaximum(60) self.__spinBox_penThickness.setMinimum(2) self.__spinBox_penThickness.setValue(30) #默认粗细为10 self.__spinBox_penThickness.setSingleStep(2) #最小变化值为2 self.__spinBox_penThickness.valueChanged.connect(self.on_PenThicknessChange)#关联spinBox值变化信号和函数on_PenThicknessChange sub_layout.addWidget(self.__spinBox_penThickness) self.__label_penColor = QLabel(self) self.__label_penColor.setText("画笔颜色") self.__label_penColor.setFixedHeight(20) sub_layout.addWidget(self.__label_penColor) self.__comboBox_penColor = QComboBox(self) self.__fillColorList(self.__comboBox_penColor) #用各种颜色填充下拉列表 self.__comboBox_penColor.currentIndexChanged.connect(self.on_PenColorChange) #关联下拉列表的当前索引变更信号与函数on_PenColorChange sub_layout.addWidget(self.__comboBox_penColor) main_layout.addLayout(sub_layout) #将子布局加入主布局
def __init__(self, name, env_config, instr_params, gui=True, dummy=False, vr_name=''): QWidget.__init__(self, env_config=env_config, instr_params=instr_params) self.gui = gui self.dummy = dummy self.vr_name = vr_name self.progress_dialog = None self.timer = None self.time_passed = 0. self.steps_passed = 0 self.log_scale_y = False self.sq_scale_x = False self.sim_status = '1/2 Подготовка' self.timer_p_int = self.configuration['Simulation poll timer'] # mcsec if not gui: return # setting up the figure and its canvas for plots self.figure = Figure() self.canvas = FigureCanvas(self.figure) self.toolbar = NavigationToolbar(self.canvas, self) self.canvas.setFixedWidth(self.configuration['Plot Width']) self.canvas.setFixedHeight(self.configuration['Plot Height']) # setting up plot axes if ('1D detector file name' in self.configuration) and ('2D detector file name' in self.configuration): self.axes_1d_detector, self.axes_2d_detector = self.canvas.figure.subplots( nrows=1, ncols=2) elif '1D detector file name' in self.configuration: self.axes_1d_detector = self.canvas.figure.subplots() self.axes_2d_detector = None elif '2D detector file name' in self.configuration: self.axes_1d_detector = None self.axes_2d_detector = self.canvas.figure.subplots() self.figure.tight_layout() # adding plot scale button and registering click callback self.log_by = QPushButton('Лог. интенсивность') self.log_by.setFixedWidth(0.2 * self.configuration['Plot Width']) self.log_by.clicked.connect(self.on_btn_log_y) self.sq_bx = QPushButton('Кв. ось x') self.sq_bx.setFixedWidth(0.2 * self.configuration['Plot Width']) self.sq_bx.clicked.connect(self.on_btn_sq_x) # adding the button to run the fit app self.fit_b = QPushButton('Анализ результатов') self.fit_b.setFixedWidth(0.2 * self.configuration['Plot Width']) self.fit_b.clicked.connect(self.on_btn_fit) self.save_b = QPushButton('Сохранить результаты') self.save_b.setFixedWidth(0.2 * self.configuration['Plot Width']) self.save_b.clicked.connect(self.on_btn_save) # adding simulation parameters buttons and labels self.param_buttons, self.param_labels = [], [] for i, param in enumerate(self.instr_params): self.param_buttons.append(QPushButton(param.gui_name)) self.param_labels.append(QLabel(str(param))) self.param_labels[i].setFrameStyle(QFrame.Sunken | QFrame.Panel) self.param_buttons[i].clicked.connect(self.make_callback(i)) # adding "Simulate" button and registering click callback self.run_b = QPushButton('Запуск эксперимента') self.run_b.clicked.connect(self.on_btn_run) # adding instrument scheme picture p_map = QPixmap(self.configuration['instrument scheme']) p_map = p_map.scaledToHeight(200, Qt.SmoothTransformation) scheme_label = QLabel() scheme_label.setPixmap(p_map) # setting up Qt window layout main_layout = QHBoxLayout() param_layout = QGridLayout() plot_layout = QVBoxLayout() tbr_layout = QHBoxLayout() log_layout = QVBoxLayout() u_plot_layout = QHBoxLayout() tbr_layout.addWidget(self.toolbar, 0) log_layout.addWidget(self.log_by, 0) log_layout.addWidget(self.sq_bx, 1) tbr_layout.addLayout(log_layout, 1) plot_layout.addLayout(tbr_layout, 0) plot_layout.addWidget(self.canvas, 1) u_plot_layout.addWidget(self.fit_b, 0, Qt.AlignRight) u_plot_layout.addWidget(self.save_b, 1, Qt.AlignLeft) plot_layout.addLayout(u_plot_layout, 3) plot_layout.addWidget(scheme_label, 4, Qt.AlignCenter) for i, param in enumerate(self.instr_params): param_layout.addWidget(self.param_buttons[i], i, 0) param_layout.addWidget(self.param_labels[i], i, 1) param_layout.addWidget(self.run_b, len(self.instr_params), 1) main_layout.addLayout(param_layout, 0) main_layout.addLayout(plot_layout, 1) self.setLayout(main_layout) self.setWindowTitle(name)
def createpreferencesPanel(self): self.labelV2raycoreVersion = QLabel( self.translate("bridgepreferencesPanel", "v2ray core version is: ")) self.labelv2raycorecurrentVersion = QLabel() self.labelV2raycoreFilePath = QLabel( self.translate("bridgepreferencesPanel", "v2ray core File Path: ")) self.lineEditFilePath = QLineEdit() self.buttonOpenV2raycoreFile = QPushButton( self.translate("bridgepreferencesPanel", "Open")) self.buttonpreferenceApply = QPushButton( self.translate("bridgepreferencesPanel", "Apply and Close")) self.buttonpreferenceCancel = QPushButton( self.translate("bridgepreferencesPanel", "Cancel")) hboxbutton = QHBoxLayout() hboxbutton.addStretch() hboxbutton.addWidget(self.buttonpreferenceApply) hboxbutton.addWidget(self.buttonpreferenceCancel) gridBox = QGridLayout() gridBox.addWidget(self.labelV2raycoreVersion, 0, 0, 1, 1) gridBox.addWidget(self.labelv2raycorecurrentVersion, 0, 1, 1, 1) gridBox.addWidget(self.labelV2raycoreFilePath, 1, 0, 1, 1) gridBox.addWidget(self.lineEditFilePath, 2, 0, 1, 5) gridBox.addWidget(self.buttonOpenV2raycoreFile, 2, 5, 1, 1) self.grouBoxConnection = QGroupBox( self.translate("bridgepreferencesPanel", "Configure Connection settings."), self) self.grouBoxConnection.setCheckable(True) self.grouBoxConnection.setChecked(False) self.radioButtonSwitch = QRadioButton( self.translate("bridgepreferencesPanel", "Switch to the next server")) self.radioButtonSwitch.setChecked(True) self.radioButtonReconnect = QRadioButton( self.translate("bridgepreferencesPanel", "Reconnect the server")) hboxRadioButton = QHBoxLayout() hboxRadioButton.addWidget(self.radioButtonSwitch) hboxRadioButton.addWidget(self.radioButtonReconnect) hboxRadioButton.addStretch() labelInterval = QLabel( self.translate("bridgepreferencesPanel", "Check the Interval: ")) self.spinBoxInterval = QSpinBox() self.spinBoxInterval.setRange(60, 360) self.spinBoxInterval.setValue(60) labelMinandMaxInterval = QLabel( self.translate("bridgepreferencesPanel", "Interval time value is 60 to 360")) labelCheckProxyTimeout = QLabel( self.translate("bridgepreferencesPanel", "Check Proxy Timeout: ")) self.spinBoxCheckProxyTimeout = QSpinBox() self.spinBoxCheckProxyTimeout.setRange(0, 15) self.spinBoxCheckProxyTimeout.setValue(3) labelCheckProxyTimeoutWarning = QLabel( self.translate("bridgepreferencesPanel", "Set 0 to disable timeout.")) labeltrytimes = QLabel( self.translate("bridgepreferencesPanel", "Try Times: ")) self.spinboxTrytimes = QSpinBox() self.spinboxTrytimes.setRange(0, 12) self.spinboxTrytimes.setValue(3) labelMaxtrytimes = QLabel( self.translate( "bridgepreferencesPanel", "0 means immediately connect, \nthe maximum value of try times is 12" )) gridBoxConnection = QGridLayout() gridBoxConnection.addWidget(labelInterval, 0, 0, Qt.AlignLeft) gridBoxConnection.addWidget(self.spinBoxInterval, 0, 1, Qt.AlignLeft) gridBoxConnection.addWidget(labelMinandMaxInterval, 0, 2, Qt.AlignLeft) gridBoxConnection.addWidget(labelCheckProxyTimeout, 1, 0, Qt.AlignLeft) gridBoxConnection.addWidget(self.spinBoxCheckProxyTimeout, 1, 1, Qt.AlignLeft) gridBoxConnection.addWidget(labelCheckProxyTimeoutWarning, 1, 2, Qt.AlignLeft) gridBoxConnection.addWidget(labeltrytimes, 2, 0, Qt.AlignLeft) gridBoxConnection.addWidget(self.spinboxTrytimes, 2, 1, Qt.AlignLeft) gridBoxConnection.addWidget(labelMaxtrytimes, 2, 2, Qt.AlignLeft) hboxConnection = QHBoxLayout() hboxConnection.addLayout(gridBoxConnection) hboxConnection.addStretch() vboxConnection = QVBoxLayout() vboxConnection.addLayout(hboxRadioButton) vboxConnection.addLayout(hboxConnection) self.grouBoxConnection.setLayout(vboxConnection) labelLanguageSetting = QLabel( self.translate("bridgepreferencesPanel", "Language: ")) self.comboBoxLanguage = QComboBox() hboxLanguage = QHBoxLayout() hboxLanguage.addWidget(labelLanguageSetting) hboxLanguage.addWidget(self.comboBoxLanguage) hboxLanguage.addStretch() self.comboxStarup = QCheckBox( self.translate("bridgepreferencesPanel", "Starting Script Automatically on System Boot")) self.comboxStarup.setChecked(False) vboxpreferences = QVBoxLayout() vboxpreferences.addLayout(gridBox) vboxpreferences.addWidget(self.grouBoxConnection) vboxpreferences.addLayout(hboxLanguage) vboxpreferences.addWidget(self.comboxStarup) vboxpreferences.addStretch() vboxpreferences.addLayout(hboxbutton) self.setLayout(vboxpreferences) self.setWindowTitle( self.translate("bridgepreferencesPanel", "Preferences")) self.resize(QSize(680, 320)) self.createpreferencePanelSignals() self.settingv2rayshellpreferencesPanel() if v2rayshellDebug: self.starupTest = startUp() hbox = QHBoxLayout() self.__testBtn = QPushButton("__testBtn") hbox.addWidget(self.__testBtn) vboxpreferences.addLayout(hbox) self.__testBtn.clicked.connect( lambda: self.starupTest.setStartUp(True))
def __init__(self): super().__init__() self.sampling_rate=200 #Ne pas monter au dessus de 1E3 self.n_points=301 self.f_min=2.8 self.f_max=2.95 #GHz self.level=-5 #dBm self.n_glissant=10 self.refresh_rate=0.1 self.freq_list=np.linspace(self.f_min,self.f_max,self.n_points) ##Creation of the graphical interface## self.setWindowTitle("AM ESR") self.main = QWidget() self.setCentralWidget(self.main) layout= QHBoxLayout() Vbox = QVBoxLayout() Vbox_droite=QVBoxLayout() Vbox_gauche=QVBoxLayout() layout.addLayout(Vbox_gauche) layout.addLayout(Vbox) layout.addLayout(Vbox_droite) self.main.setLayout(layout) #Fields on the left self.labelsampling_rate=QLabel("sampling_rate (Hz)") self.lectsampling_rate=QLineEdit(str(self.sampling_rate)) Vbox_gauche.addWidget(self.labelsampling_rate) Vbox_gauche.addWidget(self.lectsampling_rate) Vbox_gauche.addStretch(1) self.labelf_min=QLabel("f_min (GHz)") self.lectf_min=QLineEdit(str(self.f_min)) Vbox_gauche.addWidget(self.labelf_min) Vbox_gauche.addWidget(self.lectf_min) Vbox_gauche.addStretch(1) self.labelf_max=QLabel("f_max (GHz)") self.lectf_max=QLineEdit(str(self.f_max)) Vbox_gauche.addWidget(self.labelf_max) Vbox_gauche.addWidget(self.lectf_max) Vbox_gauche.addStretch(1) self.labellevel=QLabel("level (dBm)") self.lectlevel=QLineEdit(str(self.level)) Vbox_gauche.addWidget(self.labellevel) Vbox_gauche.addWidget(self.lectlevel) Vbox_gauche.addStretch(1) self.labeln_points=QLabel("n_points") self.lectn_points=QLineEdit(str(self.n_points)) Vbox_gauche.addWidget(self.labeln_points) Vbox_gauche.addWidget(self.lectn_points) self.labeln_glissant=QLabel("n_glissant") self.lectn_glissant=QLineEdit(str(self.n_glissant)) Vbox_gauche.addWidget(self.labeln_glissant) Vbox_gauche.addWidget(self.lectn_glissant) #Buttons on the right self.stop=QPushButton('Stop') self.start=QPushButton('Start') self.one_shot_button=QPushButton('One shot') self.keep_button=QPushButton('Keep trace') self.clear_button=QPushButton('Clear Last Trace') self.normalize_cb=QCheckBox('Normalize') self.labelIter=QLabel("iter # 0") Vbox_droite.addWidget(self.normalize_cb) Vbox_droite.addStretch(1) Vbox_droite.addWidget(self.start) Vbox_droite.addWidget(self.stop) Vbox_droite.addStretch(1) Vbox_droite.addWidget(self.one_shot_button) Vbox_droite.addStretch(1) Vbox_droite.addWidget(self.keep_button) Vbox_droite.addWidget(self.clear_button) Vbox_droite.addStretch(1) Vbox_droite.addWidget(self.labelIter) self.stop.setEnabled(False) #Plot in the middle dynamic_canvas = FigureCanvas(Figure(figsize=(30, 10))) Vbox.addStretch(1) Vbox.addWidget(dynamic_canvas) self.addToolBar(Qt.BottomToolBarArea, MyToolbar(dynamic_canvas, self)) self.dynamic_ax= dynamic_canvas.figure.subplots() self.x=self.freq_list[:-1] self.y=np.zeros(self.n_points-1) self.dynamic_line,=self.dynamic_ax.plot(self.x, self.y) #Define the buttons' action self.start.clicked.connect(self.start_measure) self.stop.clicked.connect(self.stop_measure) self.one_shot_button.clicked.connect(self.one_shot) self.keep_button.clicked.connect(self.keep_trace) self.clear_button.clicked.connect(self.clear_trace)
RadioGroup = QButtonGroup( ) # это для группировки переключателей, чтобы управлять их поведением RadioGroup.addButton(rbtn_1) RadioGroup.addButton(rbtn_2) RadioGroup.addButton(rbtn_3) RadioGroup.addButton(rbtn_4) layout_ans1 = QHBoxLayout() layout_ans2 = QVBoxLayout() # вертикальные будут внутри горизонтального layout_ans3 = QVBoxLayout() layout_ans2.addWidget(rbtn_1) # два ответа в первый столбец layout_ans2.addWidget(rbtn_2) layout_ans3.addWidget(rbtn_3) # два ответа во второй столбец layout_ans3.addWidget(rbtn_4) layout_ans1.addLayout(layout_ans2) layout_ans1.addLayout(layout_ans3) # разместили столбцы в одной строке RadioGroupBox.setLayout(layout_ans1) # готова "панель" с вариантами ответов AnsGroupBox = QGroupBox("Результат теста") lb_Result = QLabel('прав ты или нет?' ) # здесь размещается надпись "правильно" или "неправильно" lb_Correct = QLabel( 'ответ будет тут!') # здесь будет написан текст правильного ответа layout_res = QVBoxLayout() layout_res.addWidget(lb_Result, alignment=(Qt.AlignLeft | Qt.AlignTop)) layout_res.addWidget(lb_Correct, alignment=Qt.AlignHCenter, stretch=2) AnsGroupBox.setLayout(layout_res)
def init_ui(self) -> None: # Left side of screen self._signage_list.setHeaderLabel(self._res['signageListLabel']) self._signage_list.addTopLevelItems(self.signage_to_tree_item()) self._signage_list.expandAll() self._signage_list.itemSelectionChanged.connect( self.update_ui_component) # Buttons self._btn_up.clicked.connect(self.move_button_clicked) self._btn_down.clicked.connect(self.move_button_clicked) # Disable at first self._btn_up.setEnabled(False) self._btn_down.setEnabled(False) hbox_buttons = QHBoxLayout() hbox_buttons.addWidget(self._btn_up) hbox_buttons.addWidget(self._btn_down) vbox_left = QVBoxLayout() vbox_left.addWidget(self._signage_list) vbox_left.addLayout(hbox_buttons) # Right side of screen def signage_change_handler(change_type: utils.ChangeType, sgn_text: str = '') -> None: # Get selected signage item get_selected = self._signage_list.selectedItems() if get_selected: item = get_selected[0] if change_type == utils.ChangeType.SAVE: # Update QTreeWidgetItem item.setText(0, sgn_text) elif change_type == utils.ChangeType.DELETE: self._signage_list.removeItemWidget(item) signage_widget = SignageWidget(self._sgn_mng, signage_change_handler) self._widget_idx['signage'] = self._stacked_widget.addWidget( signage_widget) def frame_change_handler(change_type: utils.ChangeType, frame_text: str = '') -> None: # Get selected signage item get_selected = self._signage_list.selectedItems() if get_selected: item = get_selected[0] if change_type == utils.ChangeType.SAVE: # Update QTreeWidgetItem item.setText(0, "F:" + frame_text) frame_widget = FrameWidget(self._tpl_mng, self._obj_mng, self._mtm_mng, frame_change_handler) self._widget_idx['frame'] = self._stacked_widget.addWidget( frame_widget) def scene_change_handler(change_type: utils.ChangeType, scene_text: str = '') -> None: # Get selected scene item get_selected = self._signage_list.selectedItems() if get_selected: item = get_selected[0] if change_type == utils.ChangeType.SAVE: # Update QTreeWidgetItem idx = item.text(0).split(':')[0] item.setText(0, idx + ':' + scene_text) elif change_type == utils.ChangeType.DELETE: scene_idx = int(scene_text) parent = item.parent() parent.removeChild(parent.child(parent.childCount() - 1)) for i in range(parent.childCount()): if i > scene_idx + 1: it = parent.child(i) it_text = ':'.join(it.text(0).split(':')[1:]) it.setText(0, str(i - 1) + ':' + it_text) parent.removeChild(item) parent.addChild(QTreeWidgetItem(['+'])) scene_widget = SceneWidget(self._tpl_mng, self._obj_mng, self._mtm_mng, scene_change_handler) self._widget_idx['scene'] = self._stacked_widget.addWidget( scene_widget) # Gather altogether hbox_outmost = QHBoxLayout() hbox_outmost.addLayout(vbox_left, 1) hbox_outmost.addWidget(self._stacked_widget, 5) self.setLayout(hbox_outmost)
def __init__(self, parent, data, dark_mode): super().__init__(parent) # set the default save directory to the users desktop. plat = platform.system() if plat == 'Windows': self.save_directory = os.path.join(os.path.expanduser('~'), 'Desktop') elif plat == 'Linux': self.save_directory = os.path.join(os.path.expanduser('~')) elif plat == 'Darwin': self.save_directory = os.path.join(os.path.expanduser('~')) self.json_filename = 'networks_data.json' self.wpa_supplicant_filename = 'wpa_supplicant.conf' # Get current windows locale self.detected_country_code = locale.getdefaultlocale()[0].split('_')[1] self.current_country_code = self.detected_country_code #https: // en.wikipedia.org/wiki/ISO_3166-1_alpha-2 # all 249 (242 original and 7 reasigned) currently in ISO standard. self.iso_country_codes_alpha2 = [ 'AD', 'AE', 'AF', 'AG', 'AI', 'AL', 'AM', 'AO', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AW', 'AX', 'AZ', 'BA', 'BB', 'BD', 'BE', 'BF', 'BG', 'BH', 'BI', 'BJ', 'BL', 'BM', 'BN', 'BO', 'BQ', 'BR', 'BS', 'BT', 'BV', 'BW', 'BY', 'BZ', 'CA', 'CC', 'CD', 'CF', 'CG', 'CH', 'CI', 'CK', 'CL', 'CM', 'CN', 'CO', 'CR', 'CU', 'CV', 'CW', 'CX', 'CY', 'CZ', 'DE', 'DJ', 'DK', 'DM', 'DO', 'DZ', 'EC', 'EE', 'EG', 'EH', 'ER', 'ES', 'ET', 'FI', 'FJ', 'FK', 'FM', 'FO', 'FR', 'GA', 'GB', 'GD', 'GE', 'GF', 'GG', 'GH', 'GI', 'GL', 'GM', 'GN', 'GP', 'GQ', 'GR', 'GS', 'GT', 'GU', 'GW', 'GY', 'HK', 'HM', 'HN', 'HR', 'HT', 'HU', 'ID', 'IE', 'IL', 'IM', 'IN', 'IO', 'IQ', 'IR', 'IS', 'IT', 'JE', 'JM', 'JO', 'JP', 'KE', 'KG', 'KH', 'KI', 'KM', 'KN', 'KP', 'KR', 'KW', 'KY', 'KZ', 'LA', 'LB', 'LC', 'LI', 'LK', 'LR', 'LS', 'LT', 'LU', 'LV', 'LY', 'MA', 'MC', 'MD', 'ME', 'MF', 'MG', 'MH', 'MK', 'ML', 'MM', 'MN', 'MO', 'MP', 'MQ', 'MR', 'MS', 'MT', 'MU', 'MV', 'MW', 'MX', 'MY', 'MZ', 'NA', 'NC', 'NE', 'NF', 'NG', 'NI', 'NL', 'NO', 'NP', 'NR', 'NU', 'NZ', 'OM', 'PA', 'PE', 'PF', 'PG', 'PH', 'PK', 'PL', 'PM', 'PN', 'PR', 'PS', 'PT', 'PW', 'PY', 'QA', 'RE', 'RO', 'RS', 'RU', 'RW', 'SA', 'SB', 'SC', 'SD', 'SE', 'SG', 'SH', 'SI', 'SJ', 'SK', 'SL', 'SM', 'SN', 'SO', 'SR', 'SS', 'ST', 'SV', 'SX', 'SY', 'SZ', 'TC', 'TD', 'TF', 'TG', 'TH', 'TJ', 'TK', 'TL', 'TM', 'TN', 'TO', 'TR', 'TT', 'TV', 'TW', 'TZ', 'UA', 'UG', 'UM', 'US', 'UY', 'UZ', 'VA', 'VC', 'VE', 'VG', 'VI', 'VN', 'VU', 'WF', 'WS', 'YE', 'YT', 'ZA', 'ZM', 'ZW' ] self.data = data self.dark_mode = dark_mode self.resize(600, 100) self.setWindowTitle('Save') file_path_label = QLabel('Select save directory:') self.file_path_textbox = QLineEdit() self.file_path_textbox.setText(self.save_directory) self.file_path_textbox.textChanged.connect(self.save_path_changed) file_path_selector_button = QPushButton('..') file_path_selector_button.setMaximumWidth(40) file_path_selector_button.clicked.connect(self.select_directory) self.save_open_networks_checkbox = QCheckBox("Save open networks?") self.save_open_networks_checkbox.setChecked(True) save_json_button = QPushButton('Save as JSON') save_json_button.clicked.connect(self.save_json_on_click) save_wpa_supplicant = QPushButton('Save as WPA Supplicant') save_wpa_supplicant.clicked.connect(self.save_wpa_supplicant_on_click) locale_combo_label = QLabel('Locale:') self.locale_combo = QComboBox() self.locale_combo.addItems(self.iso_country_codes_alpha2) self.locale_combo.setCurrentText(self.current_country_code) self.locale_combo.currentTextChanged.connect(self.locale_change) #dummy button for spacing, is hidden dummy_button = QPushButton() dummy_button.setFlat(True) dummy_button.setDisabled(True) close_button = QPushButton('Close') close_button.clicked.connect(self.accept) head_layout = QHBoxLayout() head_layout.addWidget(file_path_label) top_layout = QHBoxLayout() top_layout.addWidget(self.file_path_textbox) top_layout.addWidget(file_path_selector_button) mid_layout = QHBoxLayout() mid_layout.addWidget(self.save_open_networks_checkbox) mid_layout.addWidget(save_json_button) mid_layout.addWidget(save_wpa_supplicant) bottom_left_layout = QHBoxLayout() bottom_left_layout.addWidget(locale_combo_label) bottom_left_layout.addWidget(self.locale_combo) bottom_left_layout.addSpacing(100) bottom_layout = QHBoxLayout() bottom_layout.addLayout(bottom_left_layout) bottom_layout.addWidget(dummy_button) bottom_layout.addWidget(close_button) layout = QVBoxLayout() layout.addLayout(head_layout) layout.addSpacing(5) layout.addLayout(top_layout) layout.addSpacing(10) layout.addLayout(mid_layout) layout.addSpacing(10) layout.addLayout(bottom_layout) self.setLayout(layout)
class ComposantUI: def __init__(self,name,pin): self.visible = True self.defaultHourStart = Hour(6,0) self.defaultHourEnd = Hour(22,0) self.pin = pin self.startHour = HourCombo("Heure d'allumage") self.endHour = HourCombo("Heure de coupure") self.buttonValidate = QPushButton("Valider") self.buttonDefault = QPushButton("Default") self.label = QLabel(name) self.layout= QHBoxLayout() hoursLayout = QVBoxLayout() buttonLayout = QVBoxLayout() hoursLayout.addLayout(self.startHour.layout) hoursLayout.addLayout(self.endHour.layout) buttonLayout.addWidget(self.buttonValidate) buttonLayout.addWidget(self.buttonDefault) self.layout.addWidget(self.label) self.layout.addLayout(hoursLayout) self.layout.addLayout(buttonLayout) def blockButton(self): """ Bloque l'utilisation des boutons du composant """ self.buttonDefault.setEnabled(False) self.buttonValidate.setEnabled(False) def unblockButton(self): """ Débloque l'utilisation des boutons """ self.buttonDefault.setEnabled(True) self.buttonValidate.setEnabled(True) def getComboBoxStartHour(self): """ Retourne la valeur de l'heure d'allumage """ return self.startHour.hours.currentIndex() def getComboBoxStartMinute(self): """ Retourne la valeur de la minute d'allumage """ return self.startHour.minutes.currentIndex() def getComboBoxEndHour(self): """ Retourne la valeur de l'heure de coupure """ return self.endHour.hours.currentIndex() def getComboBoxEndMinute(self): """ Retourne la valeur de la minute de coupure """ return self.endHour.minutes.currentIndex() def hide(self): """ Cache tous les widgets """ self.label.hide() self.buttonDefault.hide() self.buttonValidate.hide() self.startHour.hours.hide() self.startHour.minutes.hide() self.endHour.hours.hide() self.endHour.minutes.hide() self.endHour.label.hide() self.startHour.label.hide() self.visible = False def show(self): """ Affiche tous les widgets """ self.label.show() self.buttonDefault.show() self.buttonValidate.show() self.startHour.hours.show() self.startHour.minutes.show() self.endHour.hours.show() self.endHour.minutes.show() self.endHour.label.show() self.startHour.label.show() self.visible = True
def __init__(self, variety_info, *args, **kwargs): super(CreateReportPopup, self).__init__(*args, **kwargs) self.setWindowTitle("新建报告") self.variety_info = variety_info # 总布局-左右 layout = QHBoxLayout() # 左侧上下布局 llayout = QVBoxLayout() # 左侧是品种树 self.left_tree = QTreeWidget(clicked=self.variety_tree_clicked) self.left_tree.header().hide() self.left_tree.setMaximumWidth(160) llayout.addWidget(self.left_tree) layout.addLayout(llayout) # 右侧上下布局 rlayout = QVBoxLayout(spacing=10) # 所属品种 attach_varieties_layout = QHBoxLayout() attach_varieties_layout.addWidget(QLabel('所属品种:')) self.attach_varieties = QLabel() self.attach_varieties.variety_ids = list() # id字符串 attach_varieties_layout.addWidget(self.attach_varieties) attach_varieties_layout.addStretch() attach_varieties_layout.addWidget(QPushButton( '清空', objectName='deleteBtn', cursor=Qt.PointingHandCursor, clicked=self.clear_attach_varieties), alignment=Qt.AlignRight) rlayout.addLayout(attach_varieties_layout) # 所属分类 attach_category_layout = QHBoxLayout() attach_category_layout.addWidget(QLabel('所属分类:')) self.category_combo = QComboBox() self.category_combo.setMinimumWidth(400) attach_category_layout.addWidget(self.category_combo) attach_category_layout.addStretch() rlayout.addLayout(attach_category_layout) date_layout = QHBoxLayout() date_layout.addWidget(QLabel("报告日期:", self)) self.date_edit = QDateEdit(QDate.currentDate()) self.date_edit.setCalendarPopup(True) self.date_edit.setDisplayFormat('yyyy-MM-dd') date_layout.addWidget(self.date_edit) date_layout.addStretch() rlayout.addLayout(date_layout) title_layout = QHBoxLayout() title_layout.addWidget(QLabel('报告标题:', self)) self.title_edit = QLineEdit(self) title_layout.addWidget(self.title_edit) rlayout.addLayout(title_layout) # 选择报告 select_report_layout = QHBoxLayout() select_report_layout.addWidget(QLabel('报告文件:', self)) self.report_file_edit = FileLineEdit() self.report_file_edit.setParent(self) select_report_layout.addWidget(self.report_file_edit) rlayout.addLayout(select_report_layout) # 提交按钮 self.commit_button = QPushButton('提交', clicked=self.commit_upload_report) rlayout.addWidget(self.commit_button, alignment=Qt.AlignRight) rlayout.addStretch() layout.addLayout(rlayout) self.setLayout(layout) self.setFixedSize(800, 500) self.setStyleSheet(""" #deleteBtn{ border: none; color:rgb(200,100,80) } #newCategoryBtn{ border:none; color:rgb(80,100,200) } """) self.geTreeVarieties() for category_item in [("日报", 1), ("周报", 2), ("月报", 3), ("年报", 4), ("专题报告", 5), ("其他", 0)]: self.category_combo.addItem(category_item[0], category_item[1])
class Control(Widgets): maxRange = {'x': (-90, 90), 'y': (-30, 30)} isConnected = False def __init__(self, pasp): super().__init__(pasp) self.createMenu() self.createControl() self.createConnecter() def createMenu(self): self.gb = QGroupBox() self.gbLayout = QHBoxLayout() self.gbLayout.addWidget(self.gb) self.gb.setTitle('Windows') self.menuLayout = QHBoxLayout() self.gb.setLayout(self.menuLayout) self.mainWidgetLayout.addLayout(self.gbLayout) self.setMaximumWidth(400) self.setMaximumHeight(400) self.lis = ('Camera', 'Map', 'Locator (atop)', 'locator (side)', 'Collisions') self.menu = [0] * 5 self.menuBoxMapper = QSignalMapper(self) for i in range(5): self.menu[i] = QCheckBox(self.lis[i]) self.menuBoxMapper.setMapping(self.menu[i], i) self.menu[i].stateChanged[int].connect(self.menuBoxMapper.map) self.menuLayout.addWidget(self.menu[i]) self.menuBoxMapper.mapped[int].connect(self.changeWindows) self.bLog = QPushButton('Log') self.bSettings = QPushButton('set') def changeWindows(self, i): state = self.menu[i].checkState() #self.changeWindSignal.emit(i, state) def createControl(self): #self.msg.emit("Hello") self.rotSliderLayout = QHBoxLayout() self.rotSlider = QSlider(Qt.Horizontal) self.rotSlider.setRange(*self.maxRange['x']) self.rotSlider.setMinimumWidth(300) self.rotSlider.setTickInterval(5) self.rotSlider.setTickPosition(QSlider().TicksBothSides) self.rotSlider.valueChanged[int].connect(self.rotSliderChanged) self.rotLabel = QLabel('Rotate') self.rotLine = QLineEdit('0') self.rotLine.setMaximumWidth(30) self.rotSliderLayout.addWidget(self.rotSlider) self.rotSliderLayout.addStretch(1) self.rotSliderLayout.addWidget(self.rotLabel) self.rotSliderLayout.addWidget(self.rotLine) self.controlLayout = QHBoxLayout() self.joystick = Joy(self.maxRange) self.joystick.setFocusPolicy(Qt.StrongFocus) self.joystick.setMinimumSize(300, 200) self.joystick.sender[int, int].connect(self.joystickMoved) self.gazSlider = QSlider(Qt.Vertical) self.gazSlider.setRange(*self.maxRange['y']) self.gazSlider.setMinimumWidth(80) self.gazSlider.setTickInterval(2) self.gazSlider.setTickPosition(QSlider().TicksBothSides) self.gazSlider.valueChanged[int].connect(self.gazSliderChanged) self.controlLayout.addStretch(1) self.controlLayout.addWidget(self.joystick) self.controlLayout.addStretch(1) self.controlLayout.addWidget(self.gazSlider) self.controlLayout.addStretch(1) self.bottomLayout = QHBoxLayout() self.bKey = QPushButton('key') self.bFix = QPushButton('Fix') self.bLog = QPushButton('Log') self.bLog.clicked.connect(self.p) self.bSettings = QPushButton('set') self.bKey.setMaximumWidth(40) self.bFix.setMaximumWidth(40) self.bLog.setMaximumWidth(40) self.bSettings.setMaximumWidth(40) self.labelSpeed = QLabel('Speed') self.lineSpeed = QLineEdit('0') self.gazLabel = QLabel('Gas') self.gazLine = QLineEdit('0') self.lineSpeed.setMaximumWidth(50) self.bottomLayout.addWidget(self.bKey) self.bottomLayout.addWidget(self.bFix) self.bottomLayout.addWidget(self.bLog) self.bottomLayout.addWidget(self.bSettings) self.bottomLayout.addStretch(1) self.bottomLayout.addWidget(self.labelSpeed) self.bottomLayout.addWidget(self.lineSpeed) self.bottomLayout.addWidget(self.gazLabel) self.bottomLayout.addWidget(self.gazLine) self.bottomLayout.addStretch(1) self.mainWidgetLayout.addLayout(self.rotSliderLayout) self.mainWidgetLayout.addLayout(self.controlLayout) self.mainWidgetLayout.addLayout(self.bottomLayout) def p(self): print('Ffffffff') def createConnecter(self): self.connectGB = QGroupBox(self) self.connectGBLayout = QHBoxLayout() self.choosePortBox = QFormLayout() self.cbPort = QComboBox() self.cbPort.setMaximumWidth(80) self.cbPort.addItems(d.portList) self.cbPort.activated[int].connect(self.connect) self.cbPort.setCurrentIndex(15) self.cbLabel = QLabel('<font color = "red">Disconnected</font>') self.choosePortBox.addRow("Port", self.cbPort) self.choosePortBox.addRow("State", self.cbLabel) self.connectGBLayout.addLayout(self.choosePortBox) self.chooseSpeedBox = QFormLayout() self.cbSpeed = QComboBox() self.cbSpeed.setMaximumWidth(80) self.cbSpeed.addItems(d.serialSpeedCases) self.cbSpeed.setCurrentIndex(0) self.chooseSpeedBox.addRow("Speed", self.cbSpeed) self.connectGBLayout.addLayout(self.chooseSpeedBox) self.connectGB.setLayout(self.connectGBLayout) self.mainWidgetLayout.addWidget(self.connectGB) self.pSending = QPixmap('pause.png') self.lSending = QLabel() self.lSending.setPixmap(self.pSending) self.pCheck = QPushButton('Check') self.connectGBLayout.addWidget(self.lSending) self.connectGBLayout.addWidget(self.pCheck) def rotSliderChanged(self, rot): global rotate rotate = rot self.updateControls() def gazSliderChanged(self, gaze): global gaz gaz = gaze self.updateControls() def updateControls(self): self.rotLine.setText(str(rotate)) self.gazLine.setText(str(gaz)) self.joystick.setPosition(rotate, gaz) self.rotSlider.setValue(rotate) self.gazSlider.setValue(gaz) self.send.emit('move' + str(rotate) + '/' + str(gaz), self.pasp) def joystickMoved(self, x, y): global gaz global rotate gaz = y rotate = x self.updateControls() def connect(self, port): global portList speed = self.cbSpeed.currentText() self.sendData('connect' + d.portList[port] + '/' + speed) def connectStateChanged(self, data): if data == True: self.cbLabel.setText('font color = "green">Connected</font>') else: self.cbLabel.setText('<font color = "red">Disconnected</font>')
def __init__(self): super().__init__() #Timing Parameter ## #The program aquires the total number of photons at a rate defined by real_sampling_rate, but will only display an average of it every dt self.dt=0.03 # value in s self.real_sampling_rate=10000 #Value in Hz (Should be a multiple of 1/dt) #Total number of points in the plot self.N=1000 ##Creation of the graphical interface## self.setWindowTitle("Photon Counter") self.main = QWidget() self.setCentralWidget(self.main) layout= QHBoxLayout() Vbox_gauche=QVBoxLayout() Vbox = QVBoxLayout() Vbox_droite=QVBoxLayout() layout.addLayout(Vbox_gauche) layout.addLayout(Vbox) layout.addLayout(Vbox_droite) self.main.setLayout(layout) #Buttons on the right self.stop=QPushButton('Stop') self.start=QPushButton('Start') Vbox_droite.addWidget(self.start) Vbox_droite.addWidget(self.stop) #Labels on the left gras=QFont( "Consolas", 40, QFont.Bold) self.textdt=QLineEdit(str(self.dt)) self.labeldt=QLabel("dt (s) ") self.labelPL=QLabel("photocounts (s-1)") self.PL=QLabel() self.PL.setFont(gras) Vbox_gauche.addWidget(self.labelPL) Vbox_gauche.addWidget(self.PL) Vbox_gauche.addStretch(1) Vbox_gauche.addWidget(self.labeldt) Vbox_gauche.addWidget(self.textdt) #Plot in the middle + toolbar dynamic_canvas = FigureCanvas(Figure(figsize=(30, 10))) Vbox.addStretch(1) Vbox.addWidget(dynamic_canvas) self.addToolBar(Qt.BottomToolBarArea, NavigationToolbar(dynamic_canvas, self)) ## Matplotlib Setup ## self.dynamic_ax = dynamic_canvas.figure.subplots() self.t=np.zeros(self.N) self.y=np.zeros(self.N) self.dynamic_line,=self.dynamic_ax.plot(self.t, self.y) #Define the buttons' action self.start.clicked.connect(self.start_measure) self.stop.clicked.connect(self.stop_measure) ## Timer Setup ## self.timer = QTimer(self,interval=0) self.timer.timeout.connect(self.update_canvas)
class CoreUI(QWidget): ''' Core Ui class ''' status_message = pyqtSignal(str) assets_path = "interface/rembot/assets/" def __init__(self, parent): super().__init__(parent) # Log class self.log = Log(self) self.log.log_data[str].connect(self.to_log) # Setup process self.bot_thread = QThread() self.linebot = LineBot() self.linebot.moveToThread(self.bot_thread) self.linebot.message[str].connect( self.linebot.log.info_log) # linebot stderr log self.linebot.log.log_data[str].connect( self.to_log) # display ability logger in ui self.linebot.end_FLAG.connect(self.bot_thread.quit) self.bot_thread.started.connect(self.linebot.run) self.bot_thread.finished.connect(self.bot_process_done) self.init_ui() def init_ui(self): ''' Rembot UI ''' self.setObjectName("CoreUI") # UI Contaier self.ui_container = QVBoxLayout(self) self.ui_container.setObjectName("ui_container") ## Header ### Box self.header_box = QHBoxLayout() self.header_box.setObjectName("header_box") self.header_box.setContentsMargins(10, 10, 10, 10) ### title font = QFont() font.setFamily("OCR A Extended") font.setPointSize(40) font.setBold(True) font.setItalic(False) font.setWeight(75) self.header_title = QLabel() self.header_title.setFont(font) self.header_title.setCursor(QCursor(Qt.ArrowCursor)) self.header_title.setLayoutDirection(Qt.LeftToRight) self.header_title.setStyleSheet("color: rgb(108, 204, 227);") self.header_title.setScaledContents(False) self.header_title.setAlignment(Qt.AlignLeading | Qt.AlignLeft | Qt.AlignVCenter) self.header_title.setContentsMargins(0, 0, 0, 0) self.header_title.setObjectName("header_title") self.header_box.addWidget(self.header_title) # add title to header ### version font = QFont() font.setFamily("Tahoma") font.setPointSize(10) font.setBold(True) font.setWeight(75) self.version_number = QLabel() self.version_number.setFont(font) self.version_number.setStyleSheet("color: rgb(85, 85, 85);") self.version_number.setAlignment(Qt.AlignRight | Qt.AlignTrailing | Qt.AlignVCenter) self.version_number.setObjectName("version_number") self.header_box.addWidget( self.version_number) # add version number to header # Add to UI Container self.ui_container.addLayout( self.header_box) # add header box to layout # Content self.content_box = QHBoxLayout() self.content_box.setSizeConstraint(QLayout.SetDefaultConstraint) self.content_box.setContentsMargins(10, 10, 10, 10) self.content_box.setObjectName("content_box") ## Left Box self.left_box = QVBoxLayout() self.left_box.setSizeConstraint(QLayout.SetFixedSize) self.left_box.setContentsMargins(10, 10, 10, 10) self.left_box.setObjectName("left_box") ### File box self.file_box = QHBoxLayout() self.file_box.setContentsMargins(10, 10, 10, 10) self.file_box.setObjectName("file_box") #### File label font = QFont() font.setPointSize(10) self.file_label = QLabel() self.file_label.setFont(font) size_policy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred) size_policy.setHorizontalStretch(0) size_policy.setVerticalStretch(0) size_policy.setHeightForWidth( self.file_label.sizePolicy().hasHeightForWidth()) self.file_label.setSizePolicy(size_policy) self.file_label.setObjectName("file_label") ### Add label to File box self.file_box.addWidget(self.file_label) #### File Input font = QFont() font.setPointSize(20) self.file_input = QLineEdit() self.file_input.setFont(font) self.file_input.setMinimumSize(QSize(0, 0)) self.file_input.setAcceptDrops(True) self.file_input.setLayoutDirection(Qt.LeftToRight) self.file_input.setText("") self.file_input.setFrame(True) self.file_input.setAlignment(Qt.AlignLeading | Qt.AlignLeft | Qt.AlignVCenter) self.file_input.setObjectName("file_input") #### Add File input to File box self.file_box.addWidget(self.file_input) ### Add File box to Left Box self.left_box.addLayout(self.file_box) #### Add Button box self.button_box = QGridLayout() self.button_box.setContentsMargins(10, 10, 10, 10) self.button_box.setObjectName("button_box") ##### Start Button self.start_button = QPushButton() self.start_button.setObjectName("start_button") ##### Stop Button self.stop_button = QPushButton() self.stop_button.setEnabled(False) self.stop_button.setObjectName("stop_button") ##### Test Button self.abort_button = QPushButton() self.abort_button.setEnabled(False) self.abort_button.setObjectName("abort_button") ##### Quit Button self.quit_button = QPushButton() self.quit_button.setObjectName("quit_button") #### Add Buttons to Button Box self.button_box.addWidget(self.start_button, 0, 0, 1, 1) self.button_box.addWidget(self.stop_button, 0, 1, 1, 1) self.button_box.addWidget(self.abort_button, 1, 0, 1, 1) self.button_box.addWidget(self.quit_button, 1, 1, 1, 1) ### Add Button box to Left box self.left_box.addLayout(self.button_box) #### Log Box and Layout self.log_box = QGroupBox() self.log_box.setFlat(True) self.log_box.setObjectName("log_box") self.log_layout = QVBoxLayout(self.log_box) self.log_layout.setContentsMargins(0, 10, 0, 0) self.log_layout.setObjectName("log_layout") ##### Log output self.log_output = QTextEdit(self.log_box) self.log_output.setMinimumSize(QSize(720, 600)) self.log_output.setReadOnly(True) self.log_output.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) self.log_output.setObjectName("log_output") #### Add Log Output to Log box | Log layout self.log_layout.addWidget(self.log_output) ### Add Log box to Left box self.left_box.addWidget(self.log_box) #### Left spacer self.spacer_item = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.MinimumExpanding) ### Add spacer to Log box self.left_box.addItem(self.spacer_item) ## Add Left box to Content box self.content_box.addLayout(self.left_box) ### Right Box self.right_box = QVBoxLayout() self.right_box.setSizeConstraint(QLayout.SetMinAndMaxSize) self.right_box.setContentsMargins(10, 10, 10, 10) self.right_box.setObjectName("right_box") #### Origninal image box self.original_img_box = QGroupBox() self.original_img_box.setFlat(True) self.original_img_box.setObjectName("original_img_box") self.original_img_layout = QVBoxLayout(self.original_img_box) self.original_img_layout.setContentsMargins(0, 0, 0, 0) self.original_img_layout.setObjectName("original_img_layout") ##### Original image self.original_img = QLabel(self.original_img_box) self.original_img.setMinimumSize(QSize(720, 400)) self.original_img.setText("") self.default_img = self.assets_path + "default.jpg" self.original_img.setPixmap(QPixmap(self.default_img)) # self.original_img.setScaledContents(True) self.original_img.setObjectName("original_img") #### Add Original image to Original image Layout self.original_img_layout.addWidget(self.original_img) ### Add Original image box to Right box self.right_box.addWidget(self.original_img_box) #### Output image box self.output_img_box = QGroupBox() self.output_img_box.setFlat(True) self.output_img_box.setObjectName("output_img_box") self.output_img_layout = QHBoxLayout(self.output_img_box) self.output_img_layout.setContentsMargins(0, 0, 0, 0) self.output_img_layout.setObjectName("output_img_layout") ##### Output image self.output_img = QLabel(self.output_img_box) # self.output_img.setMinimumSize(QSize(720, 400)) self.output_img.setText("") self.output_img.setPixmap(QPixmap(self.default_img)) self.output_img.setObjectName("output_img") #### Add Output img to output image layout self.output_img_layout.addWidget(self.output_img) ### Add Output image box to Right box self.right_box.addWidget(self.output_img_box) ## Add Right box to Content box self.content_box.addLayout(self.right_box) # Add Content box to UI Container self.ui_container.addLayout( self.content_box) # add content box to layout # Labelling self._translate = QCoreApplication.translate self.retranslate_ui() QMetaObject.connectSlotsByName(self) # Attach signals self.attach_events() def retranslate_ui(self): ''' UI Text ''' self.header_title.setText(self._translate("CoreUI", "REMBOT")) self.version_number.setText(self._translate("CoreUI", "")) self.file_label.setText(self._translate("CoreUI", "File name")) self.file_input.setPlaceholderText( self._translate("CoreUI", "image.ext")) self.start_button.setText(self._translate("CoreUI", "START")) self.stop_button.setText(self._translate("CoreUI", "STOP")) self.abort_button.setText(self._translate("CoreUI", "ABORT")) self.quit_button.setText(self._translate("CoreUI", "QUIT")) self.log_box.setTitle(self._translate("CoreUI", "Log")) self.original_img_box.setTitle( self._translate("CoreUI", "Original Image")) self.output_img_box.setTitle(self._translate("CoreUI", "Output Image")) # Default images self.default_img = self.assets_path + "default.jpg" self.original_img.setPixmap(QPixmap(self.default_img)) self.output_img.setPixmap(QPixmap(self.default_img)) def attach_events(self): ''' Attach signals to events ''' self.start_button.clicked.connect(self.start) self.stop_button.clicked.connect(self.stop) def update_status(self, msg): ''' Update the program statusbar string and log ''' self.status_message.emit(msg) def to_log(self, msg): ''' Output message in ui window ''' self.log_output.append(msg) # Abilities def start(self): ''' Start program ''' self.line_bot() def stop(self): ''' Stop Any running process ''' self.linebot.process_done(1) self.bot_thread.stop() self.bot_thread.wait() def bot_process_done(self): ''' Reset ui when a process is done ''' self.stop_button.setEnabled(False) # disable Stop self.abort_button.setEnabled(False) # disable abort self.start_button.setEnabled(True) # enable start # Reset images self.original_img.setPixmap(QPixmap(self.default_img)) self.original_img.setPixmap(QPixmap(self.default_img)) self.log.info_log("Process done!") # log self.update_status("Ready") def line_bot(self): ''' Start linebot program ''' # Get file from assets_path using user input file_path = self.assets_path + self.file_input.text( ) # specify filepath if os.path.exists(file_path) and file_path[-1] != '/': self.log.info_log("Loading File") # log self.original_img.setPixmap( QPixmap(file_path)) # update display image reply = QMessageBox.question(self, 'Run linebot program ?', "Contine to process ?", \ QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: self.stop_button.setEnabled(False) # enable stop button self.start_button.setEnabled(False) # disable start button # Run process self.linebot.imgpath = file_path self.bot_thread.start() self.update_status("Running ...") else: self.log.info_log("Aborting.") # log else: self.log.warning_log("File does not exist") # log
class planet(QWidget): def __init__(self, file_name): QWidget.__init__(self) self.lam = [] self.I_total = [] self.export_file_name = file_name self.enable_earthattr = False self.enable_mercuryattr = False self.enable_marsattr = False self.enable_venusattr = False self.enable_halleyattr = False self.enable_ceresattr = False self.enable_europaattr = False self.enable_plutoattr = False self.enable_orbitalpoint = False def export(self): dump = "#gpvdm\n" dump = dump + "#x 1\n" dump = dump + "#y " + str(len(self.lam)) + "\n" dump = dump + "#z 1\n" dump = dump + "#Psun " + str(self.irradiance) + " \n" dump = dump + "#begin\n" for i in range(0, len(self.lam)): dump = dump + str(self.lam[i]) + " " + str(self.I_total[i]) + "\n" dump = dump + "#end\n" f = open(self.export_file_name, mode='wb') lines = f.write(str.encode(dump)) f.close() def init(self): if self.enable_earthattr == True: userInput = earthModel('53', '-1', '1.42', '1013.25', '15/06/2014', '12:00', '0.27', '0') london = earthModel('51.5074', '-0.1278', '2.13', '1013', '15/06/2014', '12:00', '0.43', '0') beijing = earthModel('39.9042', '116.4074', '2.98', '1013', '15/06/2014', '12:00', '0.97', '+8') losangeles = earthModel('34.0522', '-118.2437', '1.54', '1013', '15/06/2014', '12:00', '0.10', '-8') newyork = earthModel('40.7128', '-74.0059', '2.74', '1013', '15/06/2014', '12:00', '0.15', '-5') freiburg = earthModel('47.9990', '7.8421', '1.91', '1013', '15/06/2014', '12:00', '0.13', '+1') sydney = earthModel('-33.8688', '151.2093', '1.72', '1013', '15/06/2014', '12:00', '0.04', '+10') self.models = { "User Input": userInput, "London": london, "Beijing": beijing, "Los Angeles": losangeles, "New York": newyork, "Freiburg": freiburg, "Sydney": sydney } self.selectedModel = userInput self.states = [True, True, True, True, True, True, True] #DEFINING EARTH WIDGETS if self.enable_earthattr == True: self.arbitraryWidget = QLabel(self) #Arbitrary self.arbitraryWidget.setText('') self.InstructionLabel = QLabel(self) self.InstructionLabel.setText('Please choose city or User Input.') # drop down menu self.DropDown = QComboBox(self) self.DropDown.addItem("User Input") self.DropDown.addItem("London") self.DropDown.addItem("Beijing") self.DropDown.addItem("Los Angeles") self.DropDown.addItem("New York") self.DropDown.addItem("Freiburg") self.DropDown.addItem("Sydney") self.DropDown.activated[str].connect(self.onActivated) # Latitude self.LatitudeLabel = QLabel(self) self.LatitudeLabel.setText('Latitude') self.LatitudeInput = QLineEdit(self) self.LatitudeUnit = QLabel(self) self.LatitudeUnit.setText(degree_sign) # Longitude self.LongitudeLabel = QLabel(self) self.LongitudeLabel.setText('Longitude') self.LongitudeInput = QLineEdit(self) self.LongitudeUnit = QLabel(self) self.LongitudeUnit.setText(degree_sign) # Date self.DateLabel = QLabel(self) self.DateLabel.setText('Date (dd/mm/yyyy)') self.DateInput = QLineEdit(self) # Time self.TimeLabel = QLabel(self) self.TimeLabel.setText('Local Time (hh:mm)') self.TimeInput = QLineEdit(self) # Timezone self.TimezoneLabel = QLabel(self) self.TimezoneLabel.setText('Timezone (UTC-11 - UTC+12)') self.TimezoneInput = QLineEdit(self) # Pressure self.pLabel = QLabel(self) self.pLabel.setText('Ground Pressure') self.pInput = QLineEdit(self) self.PressureUnit = QLabel(self) self.PressureUnit.setText('mb') # Precipitable Water Vapour self.WLabel = QLabel(self) self.WLabel.setText('Precipitable Water Vapour') self.WInput = QLineEdit(self) self.WaterUnit = QLabel(self) self.WaterUnit.setText('cm') # Aerosol Optical Depth self.AODLabel = QLabel(self) self.AODLabel.setText('Aerosol Optical Depth') self.AODInput = QLineEdit(self) # Input valid/not valid self.ValidityLabel = QLabel(self) self.ValidityLabel.setText('Please choose city or User Input.') #notes self.notesLabel = QLabel(self) self.notesLabel.setWordWrap(True) self.notesLabel.setText( 'Note: Data for the different cities is consistent with average conditions in June 2014.\n\n' 'Please verify Timezone is consistent with Latitude and Longitude or the results will be invalid.' ) #mars Widgets if self.enable_marsattr == True: # Aerosol Optical Depth self.AODLabel = QLabel(self) self.AODLabel.setText('Aerosol Optical Depth') self.AODInput = QLineEdit(self) self.AODInput.setText('0.2') self.arbitraryWidget = QLabel(self) # Arbitrary self.arbitraryWidget.setText('(0-1)') # setting canvas for plot self.fig = Figure(figsize=(2.5, 2), dpi=100) self.canvas = FigureCanvas(self.fig) self.canvas.figure.patch.set_facecolor('white') self.axes = self.fig.add_subplot(111) self.axes.set_xlabel('Wavelength ($\mu m$)') self.axes.set_ylabel('Irradiance ($W/m^2/\mu m$)') self.axes.set_xlim(0.3, 3) self.axes.set_ylim(0, 2200) self.axes.legend() if self.enable_earthattr == True: self.LatitudeInput.setText(self.selectedModel.Latitude) self.LongitudeInput.setText(self.selectedModel.Longitude) self.DateInput.setText(self.selectedModel.Date) self.TimeInput.setText(self.selectedModel.Time) self.pInput.setText(self.selectedModel.p) self.WInput.setText(self.selectedModel.W) self.AODInput.setText(self.selectedModel.AOD) self.TimezoneInput.setText(self.selectedModel.Timezone) #Orbital Point widgets and plot if self.enable_orbitalpoint == True: self.OrbitalPointLabel = QLabel(self) self.OrbitalPointLabel.setText('Orbital Point') self.OrbitalPointInput = QLineEdit(self) self.OrbitalPointInput.setText("0") self.OrbitalPointUnit = QLabel(self) self.OrbitalPointUnit.setText('(0-1)') self.notesLabel = QLabel(self) self.notesLabel.setWordWrap(True) self.notesLabel.setText( 'Note: Orbital Point is Perihelion = 0, Aphelion = 0.5, and back to Perihelion = 1.' ) fig_orbit_size = 4 self.fig_orbit = Figure(figsize=(fig_orbit_size, fig_orbit_size), dpi=100) self.canvas_orbit = FigureCanvas(self.fig_orbit) self.canvas_orbit.figure.patch.set_facecolor('white') self.fig_orbit_axes = self.fig.add_subplot(111, projection='polar') #Solar Constant widgets self.solar_const_label = QLabel() self.solar_const_label.setText('') self.solar_const = QLabel() self.solar_const.setText('') self.hbox = QHBoxLayout() self.hbox.addWidget(self.solar_const_label) self.hbox.addWidget(self.solar_const) #LAYOUT self.inputsLayout = QHBoxLayout() self.vbox = QVBoxLayout() if self.enable_earthattr == True: self.vbox.addWidget(self.InstructionLabel) self.vbox.addWidget(self.LatitudeLabel) self.vbox.addWidget(self.LongitudeLabel) self.vbox.addWidget(self.DateLabel) self.vbox.addWidget(self.TimeLabel) self.vbox.addWidget(self.TimezoneLabel) self.vbox.addWidget(self.pLabel) self.vbox.addWidget(self.WLabel) self.vbox.addWidget(self.AODLabel) if self.enable_marsattr == True: self.vbox.addWidget(self.AODLabel) if self.enable_orbitalpoint == True: self.vbox.addWidget(self.OrbitalPointLabel) self.inputsLayout.addLayout(self.vbox) self.vbox = QVBoxLayout() if self.enable_earthattr == True: self.vbox.addWidget(self.DropDown) self.vbox.addWidget(self.LatitudeInput) self.vbox.addWidget(self.LongitudeInput) self.vbox.addWidget(self.DateInput) self.vbox.addWidget(self.TimeInput) self.vbox.addWidget(self.TimezoneInput) self.vbox.addWidget(self.pInput) self.vbox.addWidget(self.WInput) self.vbox.addWidget(self.AODInput) if self.enable_marsattr == True: self.vbox.addWidget(self.AODInput) if self.enable_orbitalpoint == True: self.vbox.addWidget(self.OrbitalPointInput) self.inputsLayout.addLayout(self.vbox) self.vbox = QVBoxLayout() if self.enable_earthattr == True: self.vbox.addWidget(self.arbitraryWidget) self.vbox.addWidget(self.LatitudeUnit) self.vbox.addWidget(self.LongitudeUnit) self.vbox.addWidget(self.arbitraryWidget) self.vbox.addWidget(self.arbitraryWidget) self.vbox.addWidget(self.arbitraryWidget) self.vbox.addWidget(self.PressureUnit) self.vbox.addWidget(self.WaterUnit) self.vbox.addWidget(self.arbitraryWidget) if self.enable_marsattr == True: self.vbox.addWidget(self.arbitraryWidget) if self.enable_orbitalpoint == True: self.vbox.addWidget(self.OrbitalPointUnit) self.inputsLayout.addLayout(self.vbox) self.grid = QGridLayout(self) # self.grid.addWidget() self.grid.addLayout(self.inputsLayout, 1, 0) if self.enable_earthattr == True: self.grid.addWidget(self.ValidityLabel, 2, 0) self.grid.addWidget(self.notesLabel, 3, 0) if self.enable_orbitalpoint == True: self.grid.addWidget(self.canvas_orbit, 4, 0) self.grid.addLayout(self.hbox, 5, 0) self.grid.addWidget(self.canvas, 0, 1, 7, 1) self.setLayout(self.grid) self.update() def calculate_earth(self): Latitude = float(self.LatitudeInput.text()) Longitude = float(self.LongitudeInput.text()) W = float(self.WInput.text()) p = float(self.pInput.text()) Date = self.DateInput.text() Time = self.TimeInput.text() timezone = float(self.TimezoneInput.text()) AOD = float(self.AODInput.text()) self.lam, I_direct, I_diffuse, self.I_total, lam_bb, sol, ext_ter_spec, self.irradiance = earth_calc( Latitude, Longitude, W, p, Date, Time, AOD, timezone) if self.states[0]: self.axes.set_title('Solar Spectrum') if self.states[1]: self.axes.plot(lam_bb * 10**6, sol * 10**3, label='Black body at 5800K') if self.states[2]: self.axes.plot(self.lam, ext_ter_spec, label='Extraterrestrial Spectrum') if self.states[3]: self.axes.plot(self.lam, I_direct, label='Direct Irradiance') if self.states[4]: self.axes.plot(self.lam, I_diffuse, label='Diffuse Irradiance') if self.states[5]: self.axes.plot(self.lam, self.I_total, label='Total Irradiance') if self.states[6]: self.axes.legend() self.axes.set_xlabel('Wavelength ($\mu m$)') self.axes.set_ylabel('Irradiance ($W/m^2/\mu m$)') self.axes.set_xlim(0.3, 3) self.axes.set_ylim(0, 2200) self.ValidityLabel.setText('') def update(self): lam = 0.0 I_direct = 0.0 I_diffuse = 0.0 I_total = 0.0 lam_bb = 0.0 sol = 0.0 ext_ter_spec = 0.0 self.irradiance = 0.0 self.fig = Figure(figsize=(12, 8), dpi=100) self.canvas = FigureCanvas(self.fig) self.canvas.figure.patch.set_facecolor('white') self.grid.addWidget(self.canvas, 0, 1, 7, 1) self.fig.clf() self.axes = self.fig.add_subplot(111) #For Orbital Plot if self.enable_orbitalpoint == True: self.fig_orbit = Figure(figsize=(4, 4), dpi=100) self.canvas_orbit = FigureCanvas(self.fig_orbit) self.canvas_orbit.figure.patch.set_facecolor('white') self.grid.addWidget(self.canvas_orbit, 4, 0) self.fig_orbit.clf() self.fig_orbit_axes = self.fig_orbit.add_subplot( 111, projection='polar') #For Earth if self.enable_earthattr == True: self.calculate_earth() #For Mercury if self.enable_mercuryattr == True: orbitalpoint = float(self.OrbitalPointInput.text()) sol, lam_bb, maximum, r, self.irradiance, r_plot, theta, ext_ter_spec, lam = mercury_calc( orbitalpoint) self.plot_orbit(r, r_plot, theta, orbitalpoint) if self.states[0]: self.axes.set_title('Solar Spectrum') if self.states[1]: self.axes.plot(lam_bb * 10**6, sol * 10**3, label='Black body at 5800K') if self.states[2]: self.axes.plot(lam, ext_ter_spec, label='Extraterrestrial Spectrum') if self.states[6]: self.axes.legend() self.axes.set_xlabel('Wavelength ($\mu m$)') self.axes.set_ylabel('Irradiance ($W/m^2/\mu m$)') self.axes.set_xlim(0.3, 3) self.axes.set_ylim(0, 1.1 * maximum) # For Mars if self.enable_marsattr == True: AOD = float(self.AODInput.text()) orbitalpoint = float(self.OrbitalPointInput.text()) sol, lam_bb, maximum, r, self.irradiance, r_plot, theta, ext_ter_spec, lam, total = mars_calc( orbitalpoint, AOD) self.plot_orbit(r, r_plot, theta, orbitalpoint) if self.states[0]: self.axes.set_title('Solar Spectrum') if self.states[1]: self.axes.plot(lam_bb * 10**6, sol * 10**3, label='Black body at 5800K') if self.states[2]: self.axes.plot(lam, ext_ter_spec, label='Extraterrestrial Spectrum') if self.states[5]: self.axes.plot(lam, total, label='Total') if self.states[6]: self.axes.legend() self.axes.set_xlabel('Wavelength ($\mu m$)') self.axes.set_ylabel('Irradiance ($W/m^2/\mu m$)') self.axes.set_xlim(0.3, 3) self.axes.set_ylim(0, 1.1 * maximum) #For Venus if self.enable_venusattr == True: orbitalpoint = float(self.OrbitalPointInput.text()) sol, lam_bb, maximum, r, self.irradiance, r_plot, theta, ext_ter_spec, lam, total = venus_calc( orbitalpoint) self.plot_orbit(r, r_plot, theta, orbitalpoint) if self.states[0]: self.axes.set_title('Solar Spectrum') if self.states[1]: self.axes.plot(lam_bb * 10**6, sol * 10**3, label='Black body at 5800K') if self.states[2]: self.axes.plot(lam, ext_ter_spec, label='Extraterrestrial Spectrum') if self.states[5]: self.axes.plot(lam, total, label="Total") if self.states[6]: self.axes.legend() self.axes.set_xlabel('Wavelength ($\mu m$)') self.axes.set_ylabel('Irradiance ($W/m^2/\mu m$)') self.axes.set_xlim(0.3, 3) self.axes.set_ylim(0, 1.1 * maximum) #For Halley if self.enable_halleyattr == True: orbitalpoint = float(self.OrbitalPointInput.text()) sol, lam_bb, maximum, r, self.irradiance, r_plot, theta, r2, ext_ter_spec, lam = halley_calc( orbitalpoint) self.fig_orbit_axes.plot(theta, r_plot) self.fig_orbit_axes.plot(0, 0, c='y', marker='o', markersize=10) self.fig_orbit_axes.plot(orbitalpoint * 2 * pi, r2, c='r', marker='o', markersize=5) self.fig_orbit_axes.set_title('Orbital Position', fontsize=10) self.fig_orbit_axes.yaxis.grid(False) self.fig_orbit_axes.xaxis.grid(False) self.fig_orbit_axes.get_xaxis().set_visible(False) self.fig_orbit_axes.get_yaxis().set_visible(False) self.fig_orbit_axes.spines['polar'].set_visible(False) if self.states[0]: self.axes.set_title('Solar Spectrum') if self.states[1]: self.axes.plot(lam_bb * 10**6, sol * 10**3, label='Black body at 5800K') if self.states[2]: self.axes.plot(lam, ext_ter_spec, label='Extraterrestrial Spectrum') if self.states[6]: self.axes.legend() self.axes.set_xlabel('Wavelength ($\mu m$)') self.axes.set_ylabel('Irradiance ($W/m^2/\mu m$)') self.axes.set_xlim(0.3, 3) self.axes.set_ylim(0, 1.1 * maximum) # For Europa if self.enable_europaattr == True: orbitalpoint = float(self.OrbitalPointInput.text()) sol, lam_bb, maximum, r, self.irradiance, r_plot, theta, ext_ter_spec, lam = europa_calc( orbitalpoint) self.plot_orbit(r, r_plot, theta, orbitalpoint) if self.states[0]: self.axes.set_title('Solar Spectrum') if self.states[1]: self.axes.plot(lam_bb * 10**6, sol * 10**3, label='Black body at 5800K') if self.states[2]: self.axes.plot(lam, ext_ter_spec, label='Extraterrestrial Spectrum') if self.states[6]: self.axes.legend() self.axes.set_xlabel('Wavelength ($\mu m$)') self.axes.set_ylabel('Irradiance ($W/m^2/\mu m$)') self.axes.set_xlim(0.3, 3) self.axes.set_ylim(0, 1.1 * maximum) # For Ceres if self.enable_ceresattr == True: orbitalpoint = float(self.OrbitalPointInput.text()) sol, lam_bb, maximum, r, self.irradiance, r_plot, theta, ext_ter_spec, lam = ceres_calc( orbitalpoint) self.plot_orbit(r, r_plot, theta, orbitalpoint) if self.states[0]: self.axes.set_title('Solar Spectrum') if self.states[1]: self.axes.plot(lam_bb * 10**6, sol * 10**3, label='Black body at 5800K') if self.states[2]: self.axes.plot(lam, ext_ter_spec, label='Extraterrestrial Spectrum') if self.states[6]: self.axes.legend() self.axes.set_xlabel('Wavelength ($\mu m$)') self.axes.set_ylabel('Irradiance ($W/m^2/\mu m$)') self.axes.set_xlim(0.3, 3) self.axes.set_ylim(0, 1.1 * maximum) # For Ceres if self.enable_plutoattr == True: orbitalpoint = float(self.OrbitalPointInput.text()) sol, lam_bb, maximum, r, self.irradiance, r_plot, theta, ext_ter_spec, lam = pluto_calc( orbitalpoint) self.plot_orbit(r, r_plot, theta, orbitalpoint) if self.states[0]: self.axes.set_title('Solar Spectrum') if self.states[1]: self.axes.plot(lam_bb * 10**6, sol * 10**3, label='Black body at 5800K') if self.states[2]: self.axes.plot(lam, ext_ter_spec, label='Extraterrestrial Spectrum') if self.states[6]: self.axes.legend() self.axes.set_xlabel('Wavelength ($\mu m$)') self.axes.set_ylabel('Irradiance ($W/m^2/\mu m$)') self.axes.set_xlim(0.3, 3) self.axes.set_ylim(0, 1.1 * maximum) self.irradiance = round(Decimal(self.irradiance), 2) self.solar_const_label.setText('Solar Constant (W/m^2):') self.solar_const.setText(str(self.irradiance)) def copy2clip(self): buf = io.BytesIO() self.fig.savefig(buf) QApplication.clipboard().setImage(QImage.fromData(buf.getvalue())) def showInfo(self): popup = infoBox(self) popup.show() def setPlotPreferences(self): dialog = checkBoxInput(self) dialog.show() def onActivated(self, modelName): if modelName != "User Input": self.LatitudeInput.setDisabled(True) self.LongitudeInput.setDisabled(True) self.DateInput.setDisabled(True) self.TimeInput.setDisabled(True) self.TimezoneInput.setDisabled(True) self.pInput.setDisabled(True) self.WInput.setDisabled(True) self.AODInput.setDisabled(True) else: self.LatitudeInput.setDisabled(False) self.LongitudeInput.setDisabled(False) self.DateInput.setDisabled(False) self.TimeInput.setDisabled(False) self.TimezoneInput.setDisabled(False) self.pInput.setDisabled(False) self.WInput.setDisabled(False) self.AODInput.setDisabled(False) # remembers inputs self.selectedModel.Latitude = self.LatitudeInput.text() self.selectedModel.Longitude = self.LongitudeInput.text() self.selectedModel.Date = self.DateInput.text() self.selectedModel.Time = self.TimeInput.text() self.selectedModel.Timezone = self.TimezoneInput.text() self.selectedModel.p = self.pInput.text() self.selectedModel.W = self.WInput.text() self.selectedModel.AOD = self.AODInput.text() self.selectedModel = self.models[modelName] self.LatitudeInput.setText(self.selectedModel.Latitude) self.LongitudeInput.setText(self.selectedModel.Longitude) self.DateInput.setText(self.selectedModel.Date) self.TimeInput.setText(self.selectedModel.Time) self.TimezoneInput.setText(self.selectedModel.Timezone) self.pInput.setText(self.selectedModel.p) self.WInput.setText(self.selectedModel.W) self.AODInput.setText(self.selectedModel.AOD) def plot_orbit(self, r, r_plot, theta, orbitalpoint): self.fig_orbit_axes.plot(theta, r_plot) self.fig_orbit_axes.plot(0, 0, c='y', marker='o', markersize=10) self.fig_orbit_axes.plot(orbitalpoint * 2 * pi, r, c='r', marker='o', markersize=5) self.fig_orbit_axes.set_title('Orbital Position', fontsize=10) self.fig_orbit_axes.yaxis.grid(False) self.fig_orbit_axes.xaxis.grid(False) self.fig_orbit_axes.get_xaxis().set_visible(False) self.fig_orbit_axes.get_yaxis().set_visible(False) self.fig_orbit_axes.spines['polar'].set_visible(False) #functions to enable 'planet' specific GUI items def set_earth(self, data): self.enable_earthattr = data def set_mercury(self, data): self.enable_mercuryattr = data def set_mars(self, data): self.enable_marsattr = data def set_venus(self, data): self.enable_venusattr = data def set_halley(self, data): self.enable_halleyattr = data def set_europa(self, data): self.enable_europaattr = data def set_ceres(self, data): self.enable_ceresattr = data def set_pluto(self, data): self.enable_plutoattr = data #common widget functions def set_orbitalpoint(self, data): self.enable_orbitalpoint = data
def __init__(self, variety_info, *args, **kwargs): super(CreateReportPopup, self).__init__(*args, **kwargs) self.variety_info = variety_info # 总布局-左右 layout = QHBoxLayout() # 左侧上下布局 llayout = QVBoxLayout() # 左侧是品种树 self.left_tree = QTreeWidget(clicked=self.variety_tree_clicked) self.left_tree.header().hide() self.left_tree.setMaximumWidth(160) llayout.addWidget(self.left_tree) layout.addLayout(llayout) # 右侧上下布局 rlayout = QVBoxLayout() # 所属品种 attach_varieties_layout = QHBoxLayout() attach_varieties_layout.addWidget(QLabel('所属品种:')) self.attach_varieties = QLabel() self.attach_varieties.variety_ids = list() # id字符串 attach_varieties_layout.addWidget(self.attach_varieties) attach_varieties_layout.addStretch() attach_varieties_layout.addWidget(QPushButton( '清空', objectName='deleteBtn', cursor=Qt.PointingHandCursor, clicked=self.clear_attach_varieties), alignment=Qt.AlignRight) rlayout.addLayout(attach_varieties_layout) rlayout.addWidget(QLabel(parent=self, objectName='varietyError')) # 所属分类 attach_category_layout = QHBoxLayout() attach_category_layout.addWidget(QLabel('所属分类:')) self.category_combo = QComboBox() self.category_combo.setMinimumWidth(400) attach_category_layout.addWidget(self.category_combo) attach_category_layout.addStretch() # attach_category_layout.addWidget(QPushButton('新分类?', objectName='newCategoryBtn', cursor=Qt.PointingHandCursor, clicked=self.add_new_category), alignment=Qt.AlignRight) rlayout.addLayout(attach_category_layout) rlayout.addWidget(QLabel(parent=self, objectName='categoryError')) # 选择报告 rlayout.addWidget(QPushButton('选择报告', clicked=self.select_reports), alignment=Qt.AlignLeft) # 预览表格 self.review_table = QTableWidget() self.review_table.verticalHeader().hide() rlayout.addWidget(self.review_table) # 提交按钮 self.commit_button = QPushButton('提交', clicked=self.commit_upload_report) rlayout.addWidget(self.commit_button, alignment=Qt.AlignRight) layout.addLayout(rlayout) self.setLayout(layout) self.setMinimumWidth(800) self.setStyleSheet(""" #deleteBtn{ border: none; color:rgb(200,100,80) } #newCategoryBtn{ border:none; color:rgb(80,100,200) } """) self.geTreeVarieties() for category_item in [("日报", 1), ("周报", 2), ("月报", 3), ("年报", 4), ("专题报告", 5), ("其他", 0)]: self.category_combo.addItem(category_item[0], category_item[1])
def setFODImageNameField(self, imageName, cameraID, subsectorID, date, time): title_FODImgName = QLabel('Image name: ' + imageName) title_cameraID = QLabel('Camera: ' + cameraID) title_subsectorID = QLabel('Subsector: ' + subsectorID) title_date = QLabel('Date: ' + date) title_time = QLabel('Time: ' + time) vbox1 = QVBoxLayout() vbox1.addWidget(title_FODImgName) vbox1.addWidget(title_cameraID) vbox1.addWidget(title_subsectorID) vbox1.addWidget(title_date) vbox1.addWidget(title_time) vbox1.setSpacing(10) vbox1.addStretch(1) # Add a strechable h-space before the widgets title_UserRemark = QLabel('User Remark: ') textbox_UserRemark = QTextEdit() # multiple lines textbox_UserRemark.setFixedHeight( textbox_UserRemark.document().size().height() * 4) textbox_UserRemark.setFixedWidth( textbox_UserRemark.document().size().width() * 20) textbox_UserRemark.setDisabled(True) gridUserRemark = QGridLayout() gridUserRemark.addWidget(textbox_UserRemark, 0, 0) # row 1 col 0, span 1 row 1 col vbox2 = QVBoxLayout() vbox2.addWidget(title_UserRemark) vbox2.addLayout(gridUserRemark) vbox2.setSpacing(10) vbox2.addStretch(1) title_SSLRemark = QLabel('SSL Remark: ') textbox_SSLRemark = QTextEdit() # multiple lines textbox_SSLRemark.setFixedHeight( textbox_SSLRemark.document().size().height() * 4) textbox_SSLRemark.setFixedWidth( textbox_SSLRemark.document().size().width() * 20) gridSSLRemark = QGridLayout() gridSSLRemark.addWidget(textbox_SSLRemark, 0, 0) # row 1 col 0, span 1 row 1 col vbox3 = QVBoxLayout() vbox3.addWidget(title_SSLRemark) vbox3.addLayout(gridSSLRemark) vbox3.setSpacing(10) vbox3.addStretch(1) button_SaveRemarks = QPushButton("Save Remarks") button_CopyImage = QPushButton("Copy Image") checkbox_skipEmptyImg = QCheckBox("Skip empty images") checkbox_skipEmptyImg.setChecked(True) #checkbox_skipEmptyImg.hide() # Not to let users know there are FOD detail without images. vbox4 = QVBoxLayout() vbox4.addWidget(button_SaveRemarks) vbox4.addWidget(button_CopyImage) vbox4.addWidget(checkbox_skipEmptyImg) vbox4.setSpacing(10) vbox4.addStretch(1) hbox = QHBoxLayout() hbox.addLayout(vbox1) hbox.addLayout(self.createEmptyBoxLayout()) hbox.addLayout(vbox2) #hbox.addLayout(self.createEmptyBoxLayout()) hbox.addLayout(vbox3) hbox.addLayout(self.createEmptyBoxLayout()) hbox.addLayout(vbox4) hbox.addStretch(1) # Add strechable v-space above the h-box pixmap_FODImage = QPixmap("FODImage.jpg") pixmap_FODImage = pixmap_FODImage.scaledToWidth(self.imageWidth * self.frameScaleRatio) display_FODImage = QLabel(self) display_FODImage.setPixmap(pixmap_FODImage) gridAppLayout = QGridLayout() gridAppLayout.addLayout(hbox, 0, 0) gridAppLayout.addWidget(display_FODImage, 1, 0) self.setLayout(gridAppLayout) pass
def createGridLayout(self): self.centralWidget = QWidget(self) self.centralWidget.setStyleSheet("background-color: white;") self.centralWidget.setStatusTip('Ready') self.setCentralWidget(self.centralWidget) self.sld = QSlider(Qt.Horizontal, self) mainLayout = QHBoxLayout() vLayout = QVBoxLayout() grid = QGridLayout() grid.setSpacing(25) grid.setContentsMargins(25, 25, 25, 25) self.dragndrop = DropButton('Drop images here', self.width - self.minSize, self.minSize, self) grid.addWidget(self.dragndrop, 0, 0, 1, 4) self.viewerGroupBox = QGroupBox('Time-lapse viewer') self.img1 = QLabel(self.centralWidget) self.img1.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.img1.setMinimumSize(self.minSize, self.minSize) self.img2 = QLabel(self.centralWidget) self.img2.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.img2.setMinimumSize(self.minSize, self.minSize) imgviewer = QHBoxLayout() leftSpacer = QSpacerItem(self.minSize / 10, self.minSize, QSizePolicy.Expanding, QSizePolicy.Minimum) imgviewer.addSpacerItem(leftSpacer) imgviewer.addWidget(self.img1) imgviewer.addWidget(self.img2) rightSpacer = QSpacerItem(self.minSize / 10, self.minSize, QSizePolicy.Expanding, QSizePolicy.Minimum) imgviewer.addSpacerItem(rightSpacer) self.viewerGroupBox.setLayout(imgviewer) self.viewerGroupBox.setVisible(False) grid.addWidget(self.viewerGroupBox, 2, 1) grid.addWidget(self.sld, 3, 1) self.sld.setValue(0) self.sld.setRange(0, 0) self.sld.valueChanged.connect(self.updateViewerIndex) self.sld.setVisible(False) # Encapsulate grid layout in VBox and HBox vLayout.addLayout(grid) verticalSpacer = QSpacerItem(self.minSize, 20, QSizePolicy.Minimum, QSizePolicy.Expanding) vLayout.addItem(verticalSpacer) hLeftSpacer = QSpacerItem(self.minSize / 10, self.minSize, QSizePolicy.Expanding, QSizePolicy.Minimum) mainLayout.addItem(hLeftSpacer) mainLayout.addLayout(vLayout) hRightSpacer = QSpacerItem(self.minSize / 10, self.minSize, QSizePolicy.Expanding, QSizePolicy.Minimum) mainLayout.addItem(hRightSpacer) self.centralWidget.setLayout(mainLayout)
class UiMainWindow: def __init__(self, main): self.main = main def setup_ui(self): logger.info("Initializing UI") self.main.resize(1850, 1000) self.setup_base() self.setup_calculator_song_layout() self.setup_card_unit_layout() self.setup_tip_view() self.main.setCentralWidget(self.central_widget) self.retranslate_ui(self.main) QMetaObject.connectSlotsByName(self.main) def setup_base(self): logger.info("Setting up UI base") self.central_widget = QWidget(self.main) self.grid_layout = QGridLayout(self.central_widget) self.main_layout = QVBoxLayout() def setup_tip_view(self): self.tip_view = TipView() self.grid_layout.addWidget(self.tip_view, 1, 0, 1, 1) def setup_calculator_song_layout(self): logger.info("Setting up calculator and song layouts") self.calculator_song_layout = QHBoxLayout() self.calculator = QTabWidget(self.central_widget) self.calculator_view = MainView() self.calculator_model = MainModel(self.calculator_view) self.calculator_view.set_model(self.calculator_model) self.calculator_view.setup() self.potential_view = PotentialView() self.potential_model = PotentialModel(self.potential_view) self.potential_view.set_model(self.potential_model) self.potential_model.initialize_data() self.calculator.addTab(self.calculator_view.widget, "Simulator") self.calculator.addTab(self.potential_view.widget, "Potentials") self.calculator_song_layout.addWidget(self.calculator) self.song_layout = QVBoxLayout() self.import_layout = QHBoxLayout() self.import_text = QLineEdit(self.main) self.import_text.setPlaceholderText( "Input user ID (9 digits, e.g. 123456789)") self.import_text.setValidator(QIntValidator( 0, 999999999, None)) # Only number allowed self.import_button = QPushButton("Import from ID", self.main) self.import_button.pressed.connect( lambda: self.import_from_id(self.import_text.text())) self.import_layout.addWidget(self.import_text) self.import_layout.addWidget(self.import_button) self.song_layout.addLayout(self.import_layout) self.song_view = SongView(self.central_widget) self.song_model = SongModel(self.song_view) self.song_model.initialize_data() self.song_view.set_model(self.song_model) self.song_layout.addWidget(self.song_view.widget) self.songsearch_view = SongQuickSearchView(self.central_widget, self.song_model) self.songsearch_model = SongQuickSearchModel(self.songsearch_view, self.song_view) self.songsearch_view.set_model(self.songsearch_model) hl = QHBoxLayout() hl.addWidget(self.songsearch_view.widget) chart_viewer_button = QPushButton("Popup Chart Viewer") hl.addWidget(chart_viewer_button) chart_viewer_button.pressed.connect(lambda: eventbus.eventbus.post( PopupChartViewerEvent(look_for_chart=True))) self.song_layout.addLayout(hl) self.calculator_song_layout.addLayout(self.song_layout) self.calculator_song_layout.setStretch(0, 3) self.calculator_song_layout.setStretch(1, 2) self.main_layout.addLayout(self.calculator_song_layout) self.calculator.setCurrentIndex(0) def setup_card_unit_layout(self): logger.info("Setting up card and unit layouts") self.card_unit_layout = QHBoxLayout() self.card_layout = QVBoxLayout() self.card_quicksearch_layout = QHBoxLayout() self.quicksearch_layout = QHBoxLayout() # Set up card MV first self.card_view = CardView(self.central_widget) self.card_model = CardModel(self.card_view) self.card_view.set_model(self.card_model) self.card_model.initialize_cards() self.card_view.initialize_pics() self.card_view.connect_cell_change() self.card_layout.addWidget(self.card_view.widget) # Need card view self.quicksearch_view = QuickSearchView(self.central_widget, self.card_model) self.quicksearch_model = QuickSearchModel(self.quicksearch_view, self.card_view) self.quicksearch_view.set_model(self.quicksearch_model) self.card_quicksearch_layout.addLayout(self.quicksearch_layout) self.quicksearch_layout.addWidget(self.quicksearch_view.widget) self.highlight_checkbox = QCheckBox(self.central_widget) self.highlight_checkbox.setText("Highlight Carnival Idols") self.highlight_checkbox.clicked.connect( lambda _: self.card_model.highlight_event_cards(_)) self.quicksearch_layout.addWidget(self.highlight_checkbox) self.quicksearch_model.add_options(self.quicksearch_layout, self.central_widget) # Then icon loader MV since it makes use of the card model self.icon_loader_view = IconLoaderView(self.central_widget) self.icon_loader_model = IconLoaderModel(self.icon_loader_view, self.card_model) self.icon_loader_view.set_model(self.icon_loader_model) self.icon_loader_view.widget.setToolTip( "Larger icons require more RAM to run.") self.icon_loader_model.load_image(0) self.card_quicksearch_layout.addWidget(self.icon_loader_view.widget) self.card_layout.addLayout(self.card_quicksearch_layout) self.card_layout.setStretch(1, 1) self.unit_layout = QVBoxLayout() self.unit_view = UnitView(self.central_widget) self.unit_model = UnitModel(self.unit_view) self.unit_view.set_model(self.unit_model) self.unit_model.initialize_units() self.unit_layout.addWidget(self.unit_view.widget) self.card_unit_layout.addLayout(self.unit_layout) self.card_unit_layout.addLayout(self.card_layout) self.add_unit_button = QPushButton() self.add_unit_button.setText("Add unit") self.add_unit_button.setToolTip( "Add an untitled unit. Untitled units are not saved upon exit!\n" "Make sure to give your units a name. Unit names must be different.\n" "First/Red card is the leader, last/blue card is the guest.") self.add_unit_button.clicked.connect( lambda: self.unit_view.add_empty_widget()) self.unit_layout.addWidget(self.add_unit_button) self.card_unit_layout.setStretch(0, 1) self.card_unit_layout.setStretch(1, 2) self.main_layout.addLayout(self.card_unit_layout) self.grid_layout.addLayout(self.main_layout, 0, 0, 1, 1) def import_from_id(self, game_id): self.card_view.disconnect_cell_change() updated_card_ids = profile_manager.import_from_gameid(game_id) if updated_card_ids is None: self.card_view.connect_cell_change() return indexer.im.initialize_index_db(updated_card_ids) indexer.im.reindex(updated_card_ids) search_engine.engine.refresh_searcher() self.card_model.initialize_cards(updated_card_ids) self.card_view.connect_cell_change() def retranslate_ui(self, MainWindow): _translate = QCoreApplication.translate MainWindow.setWindowTitle(_translate("main", "Chihiro")) def disable_auto_resize(self): self.card_view.toggle_auto_resize(False)
def initUI(self): self.resize(533,408) self.setWindowTitle('中医药数据特征选择分析平台') self.setProperty('name','UI') self.setWindowIcon(QIcon('./image/分析.png')) self.setWindowFlags(Qt.WindowCloseButtonHint|Qt.WindowMinimizeButtonHint) self.send = EmitUserInforSignal() self.id_label = QLabel('账号') self.id_lineEdit = QLineEdit() hlayout1 = QHBoxLayout() hlayout1.addWidget(self.id_label) hlayout1.addWidget(self.id_lineEdit) self.password_label = QLabel('密码') self.password_lineEdit = QLineEdit() hlayout2 = QHBoxLayout() hlayout2.addWidget(self.password_label) hlayout2.addWidget(self.password_lineEdit) self.checkBox1 = QCheckBox('注册账号') self.checkBox2 = QCheckBox('记住密码') self.findPassword_action = QAction('找回密码') hlayout3 = QHBoxLayout() hlayout3.addWidget(self.checkBox1) hlayout3.addWidget(self.checkBox2) self.tool_bar = QToolBar() self.tool_bar.addAction(self.findPassword_action) hlayout3.addWidget(self.tool_bar) self.login_button = QPushButton('登录') self.login_button.setProperty('name','loginButton') loader = LoadQSSHelper.LoadQSSHelper() qssStyle = loader.load('./qss_/loginWindow.qss') self.setStyleSheet(qssStyle) #使用了qss时会无效 # palette = QPalette() # pix = QPixmap(r'./image/login.jpg') # pix.scaled(self.width(),self.height()) # palette.setBrush(QPalette.Background,QBrush(pix)) # self.setPalette(palette) vlayout = QVBoxLayout() vlayout.addStretch(18) vlayout.addLayout(hlayout1,1) vlayout.addLayout(hlayout2,1) vlayout.addLayout(hlayout3,1) vlayout.addWidget(self.login_button,1) vlayout.addStretch(2) left_vlayout = QVBoxLayout() self.other_login = QPushButton('第三方登录') self.other_login.setFlat(True) left_vlayout.addStretch(1) left_vlayout.addWidget(self.other_login) right_vlayout = QVBoxLayout() self.tool_bar2 = QToolBar() self.QRC_action = QAction('二维码登录') self.tool_bar2.addAction(self.QRC_action) right_vlayout.addStretch(1) right_vlayout.addWidget(self.tool_bar2) icon = QIcon('./image/二维码.png') self.QRC_action.setIcon(icon) self.tool_bar2.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) self.first_psw = None self.second_psw = None self.id_lineEdit.setFont(QFont('宋体',25)) self.password_lineEdit.setEchoMode(QLineEdit.Password) #设置清除按钮 # self.id_lineEdit.setClearButtonEnabled(True) # self.password_lineEdit.setClearButtonEnabled(True) #设置自动补全列表 user_list = self.loadLoaclUserList() self.completer = QCompleter() model = QStringListModel() model.setStringList(user_list) self.completer.setModel(model) self.id_lineEdit.setCompleter(self.completer) #密码长度 self.password_lineEdit.setMaxLength(16) self.id_label.setToolTip('建议您使用邮箱注册') self.password_label.setToolTip('密码最大长度为16') self.id_lineEdit.setText("*****@*****.**") self.password_lineEdit.setText("123456") hlayout = QHBoxLayout() hlayout.addLayout(left_vlayout,1) hlayout.addLayout(vlayout,2) hlayout.addLayout(right_vlayout,1) self.setLayout(hlayout) self.checkBox1.stateChanged.connect(self.checkStatus) self.login_button.clicked.connect(self.onClickLogin)
def __init__(self, tx, parent, desc, prompt_if_unsaved): '''Transactions in the wallet will show their description. Pass desc to give a description for txs not yet in the wallet. ''' # We want to be a top-level window QDialog.__init__(self, parent=None) # Take a copy; it might get updated in the main window by # e.g. the FX plugin. If this happens during or after a long # sign operation the signatures are lost. self.tx = tx = copy.deepcopy(tx) # type: Transaction try: self.tx.deserialize() except BaseException as e: raise SerializationError(e) self.main_window = parent # type: ElectrumWindow self.wallet = parent.wallet self.prompt_if_unsaved = prompt_if_unsaved self.saved = False self.desc = desc # if the wallet can populate the inputs with more info, do it now. # as a result, e.g. we might learn an imported address tx is segwit, # in which case it's ok to display txid tx.add_inputs_info(self.wallet) self.setMinimumWidth(950) self.setWindowTitle(_("Transaction")) vbox = QVBoxLayout() self.setLayout(vbox) vbox.addWidget(QLabel(_("Transaction ID:"))) self.tx_hash_e = ButtonsLineEdit() qr_show = lambda: parent.show_qrcode( str(self.tx_hash_e.text()), 'Transaction ID', parent=self) qr_icon = "qrcode.png" self.tx_hash_e.addButton(qr_icon, qr_show, _("Show as QR code")) self.tx_hash_e.setReadOnly(True) vbox.addWidget(self.tx_hash_e) self.add_tx_stats(vbox) vbox.addSpacing(10) self.add_io(vbox) if tx.tx_type: self.extra_pld_label = QLabel('Extra payload:') vbox.addWidget(self.extra_pld_label) self.extra_pld = ExtraPayloadWidget() vbox.addWidget(self.extra_pld) self.sign_button = b = QPushButton(_("Sign")) b.clicked.connect(self.sign) self.broadcast_button = b = QPushButton(_("Broadcast")) b.clicked.connect(self.do_broadcast) self.save_button = b = QPushButton(_("Save")) save_button_disabled = not tx.is_complete() b.setDisabled(save_button_disabled) if save_button_disabled: b.setToolTip(SAVE_BUTTON_DISABLED_TOOLTIP) else: b.setToolTip(SAVE_BUTTON_ENABLED_TOOLTIP) b.clicked.connect(self.save) self.export_button = b = QPushButton(_("Export")) b.clicked.connect(self.export) self.cancel_button = b = QPushButton(_("Close")) b.clicked.connect(self.close) b.setDefault(True) self.qr_button = b = QPushButton() b.setIcon(read_QIcon(qr_icon)) b.clicked.connect(self.show_qr) self.copy_button = CopyButton(lambda: str(self.tx), parent.app) # Action buttons self.buttons = [ self.sign_button, self.broadcast_button, self.cancel_button ] # Transaction sharing buttons self.sharing_buttons = [ self.copy_button, self.qr_button, self.export_button, self.save_button ] run_hook('transaction_dialog', self) hbox = QHBoxLayout() hbox.addLayout(Buttons(*self.sharing_buttons)) hbox.addStretch(1) hbox.addLayout(Buttons(*self.buttons)) vbox.addLayout(hbox) self.update()
class SelectionWindow(QWidget): def __init__(self, app, OAuth_token, main_window): super().__init__() self.app = app self.token = OAuth_token self.main_window = main_window self.selection_article_list = set() self.initUI() def initUI(self): self.formatWindow() self.hbox = QHBoxLayout() self.vbox = QVBoxLayout() self.current_view = 'list' self.hbox.addLayout(self.view_options_layout()) self.hbox.addWidget(self.create_article_layout(self.current_view)) self.hbox.addLayout(self.upload_layout()) self.selection_open = self.main_window.centralWidget().selection_open self.vbox.addLayout(self.hbox) self.setLayout(self.vbox) self.activate_project_article_selection_btn() self.activate_data_save_btn() def formatWindow(self): mw_geom = self.main_window.geometry() mw_x0 = mw_geom.x() mw_y0 = mw_geom.y() mw_width = mw_geom.width() mw_height = mw_geom.height() screen = self.app.primaryScreen().availableGeometry() x0 = mw_x0 + mw_width + 10 y0 = mw_y0 + 0.75 * screen.height() self.w_width = screen.width() - x0 self.w_height = (mw_y0 + mw_height) - y0 self.setGeometry(x0, y0, self.w_width, self.w_height) self.setWindowFlags(Qt.FramelessWindowHint) def mousePressEvent(self, event): self.oldPos = event.globalPos() def mouseMoveEvent(self, event): delta = QPoint(event.globalPos() - self.oldPos) self.move(self.x() + delta.x(), self.y() + delta.y()) self.oldPos = event.globalPos() def view_options_layout(self): sizepolicy = QSizePolicy() sizepolicy.setVerticalPolicy(QSizePolicy.Expanding) sizepolicy.setVerticalPolicy(QSizePolicy.Preferred) btn_list = QPushButton() btn_list.setIcon(QIcon(os.path.abspath(__file__ + '/../..' + '/img/Bulleted List-50.png'))) btn_list.setCheckable(True) btn_list.toggle() btn_list.setSizePolicy(sizepolicy) btn_list.clicked[bool].connect(lambda: self.change_view('list')) self.list_view_btn = btn_list btn_thumb = QPushButton() btn_thumb.setIcon(QIcon(os.path.abspath(__file__ + '/../..' + 'img/Picture-64.png'))) btn_thumb.setCheckable(True) btn_thumb.setSizePolicy(sizepolicy) btn_thumb.clicked[bool].connect(lambda: self.change_view('thumb')) self.thumb_view_btn = btn_thumb layout = QVBoxLayout() layout.addWidget(self.list_view_btn) layout.addWidget(self.thumb_view_btn) return layout def change_view(self, view): if self.current_view == view: if view == 'list': self.list_view_btn.toggle() self.current_view = 'list' else: self.thumb_view_btn.toggle() self.current_view = 'thumb' else: if view == 'list': self.thumb_view_btn.toggle() self.current_view = 'list' else: self.list_view_btn.toggle() self.current_view = 'thumb' def create_article_layout(self, view): if view == 'list': return self.article_list_layout() elif view == 'thumb': return self.create_article_layout('list') def article_list_layout(self): lst = QTreeWidget() header_lst = ["Location", "Title", "id", "Status", "Tags"] header = QTreeWidgetItem(header_lst) lst.setHeaderItem(header) lst.setSelectionMode(QAbstractItemView.ExtendedSelection) for article in self.selection_article_list: lst.addTopLevelItem(article) for column in range(len(header_lst)): lst.resizeColumnToContents(column) self.article_tree = lst return self.article_tree def update_article_list_layout(self, headers=None): """ Re-formats the selection window QTreeWidget by a given set of column headers. :param headers: List of strings containing metadata field names. :return: """ # Set headers to default if none are given. if headers is None: headers = ["location", "title", "id", "status", "tags"] self.article_tree.clear() # Iterate through the article ids. for article_id in self.selection_article_list: # Get the type of the article article_type = type(article_id) if article_type is not str: # If the article id is not a string it is likely an integer id for a figshare article. If so make it a # string. if article_type is int: article_id = str(article_id) # Otherwise it is an unrecognised format and should be ignored. else: article_id = None # From the string value of the article_id determine if it is a local file. # Local ids are prepended by an 'L'. if article_id is not None: if article_id[0] == 'L': # Get article from local articles article = self.main_window.local_articles[article_id] else: # Get article from figshare articles article = self.main_window.articles[article_id] # generate a qtreewidgetitem from the article and headers list. article.gen_qtree_item(headers) # Add qtreeitem as top level item in the tree. self.article_tree.addTopLevelItem(article.qtreeitem) # Format the Qtreewidget for column in range(len(headers)): # Set the width of the columns to the data. self.article_tree.resizeColumnToContents(column) # sort the list by local or figshare. self.article_tree.sortItems(0, Qt.AscendingOrder) def upload_layout(self): sizepolicy = QSizePolicy() sizepolicy.setVerticalPolicy(QSizePolicy.Expanding) sizepolicy.setVerticalPolicy(QSizePolicy.Preferred) btn_upload = QPushButton() btn_upload.setIcon(QIcon(os.path.abspath(__file__ + '/../..' + '/img/figshare_upload.png'))) btn_upload.setSizePolicy(sizepolicy) btn_upload.pressed.connect(self.upload_selection) self.upload_btn = btn_upload layout = QVBoxLayout() layout.addWidget(self.upload_btn) return layout def upload_selection(self): header_item = self.article_tree.headerItem() for column in range(header_item.columnCount()): if header_item.data(column, 0) == 'id': id_element = column break tree_items = self.article_tree.selectedItems() article_ids = [] for item in tree_items: article_ids.append(item.data(id_element, 0)) if tree_items == []: reply = QMessageBox.question(self, 'Message', "Upload all files?", QMessageBox.Yes, QMessageBox.No) if reply == QMessageBox.Yes: article_ids = [] for row in range(self.article_tree.topLevelItemCount()): article_item = self.article_tree.topLevelItem(row) article_ids.append(article_item.data(id_element, 0)) else: article_ids = None if article_ids != None: upload_type, upload_id = self.projects_or_collections_upload() if upload_type == 'project': # Can only upload new files to a project. Cannot move figshare_articles between existing projects. #Iterate through the selected articles. for article in article_ids: # Check that the article is a local file. if article[0] == 'L': self.upload_to_project(article, upload_id) else: pass elif upload_type == 'collection': # Can only add exsiting figshare_articles to a collection. pass for i in range(2): self.main_window.centralWidget().projects_window.projects_info_window.on_show_articles_pressed() def projects_or_collections_upload(self): if self.main_window.centralWidget().projects_open: projects_window = self.main_window.centralWidget().projects_window if projects_window.projects_info_open: projects_info_window = projects_window.projects_info_window if projects_info_window.articles_window_open: return 'project', projects_info_window.project_id else: return 'collection', 'collection_id' def upload_to_project(self, local_article_id, project_id): """ Uploads a local file to a given figshare project. :param local_article_id: str. ID of local file to be uploaded. :param project_id: int. Project ID for file to be uploaded to. :return: """ # Get the local article local_article = self.main_window.local_articles[local_article_id] # Generate the upload dictionary. upload_dict = local_article.get_upload_dict() local_file_location = local_article.figshare_desktop_metadata['location'] # Upload file to project. projects = Projects(self.token) try: figshare_article_id = projects.create_article(project_id, upload_dict) projects.upload_file(figshare_article_id, local_file_location) except FileExistsError as err: print(err) except HTTPError as err: print(err) def activate_project_article_selection_btn(self): if self.main_window.centralWidget().projects_open: if self.main_window.centralWidget().projects_window.projects_info_open: if self.main_window.centralWidget().projects_window.projects_info_window.articles_window_open: window = self.main_window.centralWidget().projects_window.projects_info_window window.articles_window.btn_selection.setEnabled(True) def deactivate_project_article_selection_btn(self): if self.main_window.centralWidget().projects_open: if self.main_window.centralWidget().projects_window.projects_info_open: if self.main_window.centralWidget().projects_window.projects_info_window.articles_window_open: window = self.main_window.centralWidget().projects_window.projects_info_window window.articles_window.btn_selection.setEnabled(False) def activate_data_save_btn(self): if self.main_window.centralWidget().data_open: if self.main_window.centralWidget().data_window.local_article_edit_window_open: window = self.main_window.centralWidget().data_window.local_metadata_window window.btn_save.setEnabled(True) def deactivate_data_save_btn(self): if self.main_window.centralWidget().data_open: if self.main_window.centralWidget().data_window.local_article_edit_window_open: window = self.main_window.centralWidget().data_window.local_metadata_window window.btn_save.setEnabled(False)
class DataEntryForm(QWidget): def __init__(self): super().__init__() self.items = 0 # Data self._data = {} # Left Side self.table = QTableWidget() self.table.setColumnCount(2) self.table.setHorizontalHeaderLabels(('Description', 'Price')) self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch) self.layoutRight = QVBoxLayout() # Chart Widget self.chartView = QChartView() self.chartView.setRenderHint(QPainter.Antialiasing) self.lineEditDescription = QLineEdit() self.lineEditPrice = QLineEdit() self.buttonAdd = QPushButton('Add Expense') self.buttonClear = QPushButton('Clear All') self.buttonPlot = QPushButton('Pie Chart') self.buttonAdd.setEnabled(False) self.layoutRight.setSpacing(10) self.layoutRight.addWidget(QLabel('Description')) self.layoutRight.addWidget(self.lineEditDescription) self.layoutRight.addWidget(QLabel('Price')) self.layoutRight.addWidget(self.lineEditPrice) self.layoutRight.addWidget(self.buttonAdd) self.layoutRight.addWidget(self.buttonPlot) self.layoutRight.addWidget(self.chartView) self.layoutRight.addWidget(self.buttonClear) self.layout = QHBoxLayout() self.layout.addWidget(self.table, 50) self.layout.addLayout(self.layoutRight, 50) self.setLayout(self.layout) self.buttonClear.clicked.connect(self.reset_table) self.buttonPlot.clicked.connect(self.graph_chart) self.buttonAdd.clicked.connect(self.add_entry) self.lineEditDescription.textChanged[str].connect(self.check_disable) self.lineEditPrice.textChanged[str].connect(self.check_disable) self.fill_table() # Fill Table def fill_table(self, data=None): data = self._data if not data else data for desc, price in data.items(): descItem = QTableWidgetItem(desc) priceItem = QTableWidgetItem('${0:.2f}'.format(price)) priceItem.setTextAlignment(Qt.AlignRight | Qt.AlignCenter) self.table.insertRow(self.items) self.table.setItem(self.items, 0, descItem) self.table.setItem(self.items, 1, priceItem) self.items += 1 # Add Entry def add_entry(self): desc = self.lineEditDescription.text() price = self.lineEditPrice.text() try: descItem = QTableWidgetItem(desc) priceItem = QTableWidgetItem('${0:.2f}'.format(float(price))) priceItem.setTextAlignment(Qt.AlignRight | Qt.AlignCenter) self.table.insertRow(self.items) self.table.setItem(self.items, 0, descItem) self.table.setItem(self.items, 1, priceItem) self.items += 1 self.lineEditDescription.setText('') self.lineEditPrice.setText('') except ValueError: pass # Check If Buttons Are Disabled def check_disable(self): if self.lineEditDescription.text() and self.lineEditPrice.text(): self.buttonAdd.setEnabled(True) else: self.buttonAdd.setEnabled(False) # Reset Table def reset_table(self): self.table.setRowCount(0) self.items = 0 chart = QChart() self.chartView.setChart(chart) # Graph Data Chart def graph_chart(self): series = QPieSeries() for i in range(self.table.rowCount()): text = self.table.item(i, 0).text() val = float(self.table.item(i, 1).text().replace('$', '')) series.append(text, val) chart = QChart() chart.addSeries(series) chart.legend().setAlignment(Qt.AlignTop) self.chartView.setChart(chart)
def __init__(self, persepolis_setting): super().__init__() self.persepolis_setting = persepolis_setting # add support for other languages locale = str(self.persepolis_setting.value('settings/locale')) QLocale.setDefault(QLocale(locale)) self.translator = QTranslator() if self.translator.load(':/translations/locales/ui_' + locale, 'ts'): QCoreApplication.installTranslator(self.translator) # set ui direction ui_direction = self.persepolis_setting.value('ui_direction') if ui_direction == 'rtl': self.setLayoutDirection(Qt.RightToLeft) elif ui_direction in 'ltr': self.setLayoutDirection(Qt.LeftToRight) # get icons name icons = ':/' + \ str(self.persepolis_setting.value('settings/icons')) + '/' self.setMinimumSize(QtCore.QSize(520, 425)) self.setWindowIcon( QIcon.fromTheme('persepolis', QIcon(':/persepolis.svg'))) window_verticalLayout = QVBoxLayout() # add link tab widget self.add_link_tabWidget = QTabWidget(self) window_verticalLayout.addWidget(self.add_link_tabWidget) # link tab self.link_tab = QWidget() link_tab_verticalLayout = QVBoxLayout(self.link_tab) link_tab_verticalLayout.setContentsMargins(21, 21, 21, 81) self.link_frame = QFrame(self.link_tab) self.link_frame.setFrameShape(QFrame.StyledPanel) self.link_frame.setFrameShadow(QFrame.Raised) horizontalLayout_2 = QHBoxLayout(self.link_frame) self.link_verticalLayout = QVBoxLayout() # link -> self.link_horizontalLayout = QHBoxLayout() self.link_label = QLabel(self.link_frame) self.link_horizontalLayout.addWidget(self.link_label) self.link_lineEdit = QLineEdit(self.link_frame) self.link_horizontalLayout.addWidget(self.link_lineEdit) self.link_verticalLayout.addLayout(self.link_horizontalLayout) horizontalLayout_2.addLayout(self.link_verticalLayout) link_tab_verticalLayout.addWidget(self.link_frame) # add change_name field -> change_name_horizontalLayout = QHBoxLayout() self.change_name_checkBox = QCheckBox(self.link_frame) change_name_horizontalLayout.addWidget(self.change_name_checkBox) self.change_name_lineEdit = QLineEdit(self.link_frame) change_name_horizontalLayout.addWidget(self.change_name_lineEdit) self.link_verticalLayout.addLayout(change_name_horizontalLayout) # add_category -> queue_horizontalLayout = QHBoxLayout() self.queue_frame = QFrame(self) self.queue_frame.setFrameShape(QFrame.StyledPanel) self.queue_frame.setFrameShadow(QFrame.Raised) add_queue_horizontalLayout = QHBoxLayout(self.queue_frame) self.add_queue_label = QLabel(self.queue_frame) add_queue_horizontalLayout.addWidget(self.add_queue_label) self.add_queue_comboBox = QComboBox(self.queue_frame) add_queue_horizontalLayout.addWidget(self.add_queue_comboBox) queue_horizontalLayout.addWidget(self.queue_frame) queue_horizontalLayout.addStretch(1) self.size_label = QLabel(self) queue_horizontalLayout.addWidget(self.size_label) link_tab_verticalLayout.addLayout(queue_horizontalLayout) self.add_link_tabWidget.addTab(self.link_tab, '') # proxy tab self.proxy_tab = QWidget(self) proxy_verticalLayout = QVBoxLayout(self.proxy_tab) proxy_verticalLayout.setContentsMargins(21, 21, 21, 171) proxy_horizontalLayout = QHBoxLayout() self.proxy_checkBox = QCheckBox(self.proxy_tab) self.detect_proxy_pushButton = QPushButton(self.proxy_tab) self.detect_proxy_label = QLabel(self.proxy_tab) proxy_horizontalLayout.addWidget(self.proxy_checkBox) proxy_horizontalLayout.addWidget(self.detect_proxy_label) proxy_horizontalLayout.addWidget(self.detect_proxy_pushButton) proxy_verticalLayout.addLayout(proxy_horizontalLayout) self.proxy_frame = QFrame(self.proxy_tab) self.proxy_frame.setFrameShape(QFrame.StyledPanel) self.proxy_frame.setFrameShadow(QFrame.Raised) gridLayout = QGridLayout(self.proxy_frame) self.ip_label = QLabel(self.proxy_frame) gridLayout.addWidget(self.ip_label, 0, 0, 1, 1) self.ip_lineEdit = QLineEdit(self.proxy_frame) self.ip_lineEdit.setInputMethodHints(QtCore.Qt.ImhNone) gridLayout.addWidget(self.ip_lineEdit, 0, 1, 1, 1) self.port_label = QLabel(self.proxy_frame) gridLayout.addWidget(self.port_label, 0, 2, 1, 1) self.port_spinBox = QSpinBox(self.proxy_frame) self.port_spinBox.setMaximum(65535) self.port_spinBox.setSingleStep(1) gridLayout.addWidget(self.port_spinBox, 0, 3, 1, 1) self.proxy_user_label = QLabel(self.proxy_frame) gridLayout.addWidget(self.proxy_user_label, 2, 0, 1, 1) self.proxy_user_lineEdit = QLineEdit(self.proxy_frame) gridLayout.addWidget(self.proxy_user_lineEdit, 2, 1, 1, 1) self.proxy_pass_label = QLabel(self.proxy_frame) gridLayout.addWidget(self.proxy_pass_label, 2, 2, 1, 1) self.proxy_pass_lineEdit = QLineEdit(self.proxy_frame) self.proxy_pass_lineEdit.setEchoMode(QLineEdit.Password) gridLayout.addWidget(self.proxy_pass_lineEdit, 2, 3, 1, 1) proxy_verticalLayout.addWidget(self.proxy_frame) self.add_link_tabWidget.addTab(self.proxy_tab, '') # more options tab self.more_options_tab = QWidget(self) more_options_tab_verticalLayout = QVBoxLayout(self.more_options_tab) # download UserName & Password -> download_horizontalLayout = QHBoxLayout() download_horizontalLayout.setContentsMargins(-1, 10, -1, -1) download_verticalLayout = QVBoxLayout() self.download_checkBox = QCheckBox(self.more_options_tab) download_verticalLayout.addWidget(self.download_checkBox) self.download_frame = QFrame(self.more_options_tab) self.download_frame.setFrameShape(QFrame.StyledPanel) self.download_frame.setFrameShadow(QFrame.Raised) gridLayout_2 = QGridLayout(self.download_frame) self.download_user_lineEdit = QLineEdit(self.download_frame) gridLayout_2.addWidget(self.download_user_lineEdit, 0, 1, 1, 1) self.download_user_label = QLabel(self.download_frame) gridLayout_2.addWidget(self.download_user_label, 0, 0, 1, 1) self.download_pass_label = QLabel(self.download_frame) gridLayout_2.addWidget(self.download_pass_label, 1, 0, 1, 1) self.download_pass_lineEdit = QLineEdit(self.download_frame) self.download_pass_lineEdit.setEchoMode(QLineEdit.Password) gridLayout_2.addWidget(self.download_pass_lineEdit, 1, 1, 1, 1) download_verticalLayout.addWidget(self.download_frame) download_horizontalLayout.addLayout(download_verticalLayout) # select folder -> self.folder_frame = QFrame(self.more_options_tab) self.folder_frame.setFrameShape(QFrame.StyledPanel) self.folder_frame.setFrameShadow(QFrame.Raised) gridLayout_3 = QGridLayout(self.folder_frame) self.download_folder_lineEdit = QLineEdit(self.folder_frame) gridLayout_3.addWidget(self.download_folder_lineEdit, 2, 0, 1, 1) self.folder_pushButton = QPushButton(self.folder_frame) gridLayout_3.addWidget(self.folder_pushButton, 3, 0, 1, 1) self.folder_pushButton.setIcon(QIcon(icons + 'folder')) self.folder_label = QLabel(self.folder_frame) self.folder_label.setAlignment(QtCore.Qt.AlignCenter) gridLayout_3.addWidget(self.folder_label, 1, 0, 1, 1) download_horizontalLayout.addWidget(self.folder_frame) more_options_tab_verticalLayout.addLayout(download_horizontalLayout) # start time -> time_limit_horizontalLayout = QHBoxLayout() time_limit_horizontalLayout.setContentsMargins(-1, 10, -1, -1) start_verticalLayout = QVBoxLayout() self.start_checkBox = QCheckBox(self.more_options_tab) start_verticalLayout.addWidget(self.start_checkBox) self.start_frame = QFrame(self.more_options_tab) self.start_frame.setFrameShape(QFrame.StyledPanel) self.start_frame.setFrameShadow(QFrame.Raised) horizontalLayout_5 = QHBoxLayout(self.start_frame) self.start_time_qDataTimeEdit = QDateTimeEdit(self.start_frame) self.start_time_qDataTimeEdit.setDisplayFormat('H:mm') horizontalLayout_5.addWidget(self.start_time_qDataTimeEdit) start_verticalLayout.addWidget(self.start_frame) time_limit_horizontalLayout.addLayout(start_verticalLayout) # end time -> end_verticalLayout = QVBoxLayout() self.end_checkBox = QCheckBox(self.more_options_tab) end_verticalLayout.addWidget(self.end_checkBox) self.end_frame = QFrame(self.more_options_tab) self.end_frame.setFrameShape(QFrame.StyledPanel) self.end_frame.setFrameShadow(QFrame.Raised) horizontalLayout_6 = QHBoxLayout(self.end_frame) self.end_time_qDateTimeEdit = QDateTimeEdit(self.end_frame) self.end_time_qDateTimeEdit.setDisplayFormat('H:mm') horizontalLayout_6.addWidget(self.end_time_qDateTimeEdit) end_verticalLayout.addWidget(self.end_frame) time_limit_horizontalLayout.addLayout(end_verticalLayout) # limit Speed -> limit_verticalLayout = QVBoxLayout() self.limit_checkBox = QCheckBox(self.more_options_tab) limit_verticalLayout.addWidget(self.limit_checkBox) self.limit_frame = QFrame(self.more_options_tab) self.limit_frame.setFrameShape(QFrame.StyledPanel) self.limit_frame.setFrameShadow(QFrame.Raised) horizontalLayout_4 = QHBoxLayout(self.limit_frame) self.limit_spinBox = QDoubleSpinBox(self.limit_frame) self.limit_spinBox.setMinimum(1) self.limit_spinBox.setMaximum(1023) horizontalLayout_4.addWidget(self.limit_spinBox) self.limit_comboBox = QComboBox(self.limit_frame) self.limit_comboBox.addItem("") self.limit_comboBox.addItem("") horizontalLayout_4.addWidget(self.limit_comboBox) limit_verticalLayout.addWidget(self.limit_frame) time_limit_horizontalLayout.addLayout(limit_verticalLayout) more_options_tab_verticalLayout.addLayout(time_limit_horizontalLayout) # number of connections -> connections_horizontalLayout = QHBoxLayout() connections_horizontalLayout.setContentsMargins(-1, 10, -1, -1) self.connections_frame = QFrame(self.more_options_tab) self.connections_frame.setFrameShape(QFrame.StyledPanel) self.connections_frame.setFrameShadow(QFrame.Raised) horizontalLayout_3 = QHBoxLayout(self.connections_frame) self.connections_label = QLabel(self.connections_frame) horizontalLayout_3.addWidget(self.connections_label) self.connections_spinBox = QSpinBox(self.connections_frame) self.connections_spinBox.setMinimum(1) self.connections_spinBox.setMaximum(16) self.connections_spinBox.setProperty("value", 16) horizontalLayout_3.addWidget(self.connections_spinBox) connections_horizontalLayout.addWidget(self.connections_frame) connections_horizontalLayout.addStretch(1) more_options_tab_verticalLayout.addLayout(connections_horizontalLayout) self.add_link_tabWidget.addTab(self.more_options_tab, '') # advance options self.advance_options_tab = QWidget(self) advance_options_tab_verticalLayout = QVBoxLayout( self.advance_options_tab) # referer referer_horizontalLayout = QHBoxLayout() self.referer_label = QLabel(self.advance_options_tab) referer_horizontalLayout.addWidget(self.referer_label) self.referer_lineEdit = QLineEdit(self.advance_options_tab) referer_horizontalLayout.addWidget(self.referer_lineEdit) advance_options_tab_verticalLayout.addLayout(referer_horizontalLayout) # header header_horizontalLayout = QHBoxLayout() self.header_label = QLabel(self.advance_options_tab) header_horizontalLayout.addWidget(self.header_label) self.header_lineEdit = QLineEdit(self.advance_options_tab) header_horizontalLayout.addWidget(self.header_lineEdit) advance_options_tab_verticalLayout.addLayout(header_horizontalLayout) # user_agent user_agent_horizontalLayout = QHBoxLayout() self.user_agent_label = QLabel(self.advance_options_tab) user_agent_horizontalLayout.addWidget(self.user_agent_label) self.user_agent_lineEdit = QLineEdit(self.advance_options_tab) user_agent_horizontalLayout.addWidget(self.user_agent_lineEdit) advance_options_tab_verticalLayout.addLayout( user_agent_horizontalLayout) # load_cookies load_cookies_horizontalLayout = QHBoxLayout() self.load_cookies_label = QLabel(self.advance_options_tab) load_cookies_horizontalLayout.addWidget(self.load_cookies_label) self.load_cookies_lineEdit = QLineEdit(self.advance_options_tab) load_cookies_horizontalLayout.addWidget(self.load_cookies_lineEdit) advance_options_tab_verticalLayout.addLayout( load_cookies_horizontalLayout) self.add_link_tabWidget.addTab(self.advance_options_tab, '') # ok cancel download_later buttons -> buttons_horizontalLayout = QHBoxLayout() buttons_horizontalLayout.addStretch(1) self.download_later_pushButton = QPushButton(self) self.download_later_pushButton.setIcon(QIcon(icons + 'stop')) self.cancel_pushButton = QPushButton(self) self.cancel_pushButton.setIcon(QIcon(icons + 'remove')) self.ok_pushButton = QPushButton(self) self.ok_pushButton.setIcon(QIcon(icons + 'ok')) buttons_horizontalLayout.addWidget(self.download_later_pushButton) buttons_horizontalLayout.addWidget(self.cancel_pushButton) buttons_horizontalLayout.addWidget(self.ok_pushButton) window_verticalLayout.addLayout(buttons_horizontalLayout) self.setLayout(window_verticalLayout) # labels -> self.setWindowTitle( QCoreApplication.translate("addlink_ui_tr", "Enter Your Link")) self.link_label.setText( QCoreApplication.translate("addlink_ui_tr", "Download Link : ")) self.add_queue_label.setText( QCoreApplication.translate("addlink_ui_tr", "Add to category : ")) self.change_name_checkBox.setText( QCoreApplication.translate("addlink_ui_tr", "Change File Name : ")) self.detect_proxy_pushButton.setText( QCoreApplication.translate("addlink_ui_tr", "Detect system proxy setting")) self.proxy_checkBox.setText( QCoreApplication.translate("addlink_ui_tr", "Proxy")) self.proxy_pass_label.setText( QCoreApplication.translate("addlink_ui_tr", "Proxy PassWord : "******"addlink_ui_tr", "IP : ")) self.proxy_user_label.setText( QCoreApplication.translate("addlink_ui_tr", "Proxy UserName : "******"addlink_ui_tr", "Port:")) self.download_checkBox.setText( QCoreApplication.translate("addlink_ui_tr", "Download UserName and PassWord")) self.download_user_label.setText( QCoreApplication.translate("addlink_ui_tr", "Download UserName : "******"addlink_ui_tr", "Download PassWord : "******"addlink_ui_tr", "Change Download Folder")) self.folder_label.setText( QCoreApplication.translate("addlink_ui_tr", "Download Folder : ")) self.start_checkBox.setText( QCoreApplication.translate("addlink_ui_tr", "Start Time")) self.end_checkBox.setText( QCoreApplication.translate("addlink_ui_tr", "End Time")) self.limit_checkBox.setText( QCoreApplication.translate("addlink_ui_tr", "Limit Speed")) self.limit_comboBox.setItemText( 0, QCoreApplication.translate("addlink_ui_tr", "KB/S")) self.limit_comboBox.setItemText( 1, QCoreApplication.translate("addlink_ui_tr", "MB/S")) self.connections_label.setText( QCoreApplication.translate("addlink_ui_tr", "Number Of Connections :")) self.cancel_pushButton.setText( QCoreApplication.translate("addlink_ui_tr", "Cancel")) self.ok_pushButton.setText( QCoreApplication.translate("addlink_ui_tr", "OK")) self.download_later_pushButton.setText( QCoreApplication.translate("addlink_ui_tr", "Download later")) self.add_link_tabWidget.setTabText( self.add_link_tabWidget.indexOf(self.link_tab), QCoreApplication.translate("addlink_ui_tr", "Link")) self.add_link_tabWidget.setTabText( self.add_link_tabWidget.indexOf(self.proxy_tab), QCoreApplication.translate("addlink_ui_tr", "Proxy")) self.add_link_tabWidget.setTabText( self.add_link_tabWidget.indexOf(self.more_options_tab), QCoreApplication.translate("addlink_ui_tr", "More Options")) self.add_link_tabWidget.setTabText( self.add_link_tabWidget.indexOf(self.advance_options_tab), QCoreApplication.translate("addlink_ui_tr", "Advanced Options")) self.referer_label.setText( QCoreApplication.translate("addlink_ui_tr", 'Referrer: ')) self.header_label.setText( QCoreApplication.translate("addlink_ui_tr", 'Header: ')) self.load_cookies_label.setText( QCoreApplication.translate("addlink_ui_tr", 'Load cookies: ')) self.user_agent_label.setText( QCoreApplication.translate("addlink_ui_tr", 'User agent: '))
class Friture( QMainWindow, ): def __init__(self): QMainWindow.__init__(self) # exception hook that logs to console, file, and display a message box self.errorDialogOpened = False sys.excepthook = self.excepthook # Setup the user interface self.ui = Ui_MainWindow() self.ui.setupUi(self) # Initialize the audio data ring buffer self.audiobuffer = AudioBuffer() # Initialize the audio backend # signal containing new data from the audio callback thread, processed as numpy array AudioBackend().new_data_available.connect( self.audiobuffer.handle_new_data) # this timer is used to update widgets that just need to display as fast as they can self.display_timer = QtCore.QTimer() self.display_timer.setInterval( SMOOTH_DISPLAY_TIMER_PERIOD_MS) # constant timing # slow timer self.slow_timer = QtCore.QTimer() self.slow_timer.setInterval(SLOW_TIMER_PERIOD_MS) # constant timing self.about_dialog = About_Dialog(self, self.slow_timer) self.settings_dialog = Settings_Dialog(self) self.level_widget = Levels_Widget(self) self.level_widget.set_buffer(self.audiobuffer) self.audiobuffer.new_data_available.connect( self.level_widget.handle_new_data) self.hboxLayout = QHBoxLayout(self.ui.centralwidget) self.hboxLayout.setContentsMargins(0, 0, 0, 0) self.hboxLayout.addWidget(self.level_widget) self.centralLayout = TileLayout() self.centralLayout.setContentsMargins(0, 0, 0, 0) self.hboxLayout.addLayout(self.centralLayout) self.dockmanager = DockManager(self) # timer ticks self.display_timer.timeout.connect(self.dockmanager.canvasUpdate) self.display_timer.timeout.connect(self.level_widget.canvasUpdate) # toolbar clicks self.ui.actionStart.triggered.connect(self.timer_toggle) self.ui.actionSettings.triggered.connect(self.settings_called) self.ui.actionAbout.triggered.connect(self.about_called) self.ui.actionNew_dock.triggered.connect(self.dockmanager.new_dock) # restore the settings and widgets geometries self.restoreAppState() # start timers self.timer_toggle() self.slow_timer.start() Logger().push("Init finished, entering the main loop") # exception hook that logs to console, file, and display a message box def excepthook(self, exception_type, exception_value, traceback_object): gui_message = fileexcepthook(exception_type, exception_value, traceback_object) # we do not want to flood the user with message boxes when the error happens repeatedly on each timer event if not self.errorDialogOpened: self.errorDialogOpened = True errorBox(gui_message) self.errorDialogOpened = False # slot def settings_called(self): self.settings_dialog.show() # slot def about_called(self): self.about_dialog.show() # event handler def closeEvent(self, event): AudioBackend().close() self.saveAppState() event.accept() # method def saveAppState(self): settings = QtCore.QSettings("Friture", "Friture") settings.beginGroup("Docks") self.dockmanager.saveState(settings) settings.endGroup() settings.beginGroup("MainWindow") windowGeometry = self.saveGeometry() settings.setValue("windowGeometry", windowGeometry) windowState = self.saveState() settings.setValue("windowState", windowState) settings.endGroup() settings.beginGroup("AudioBackend") self.settings_dialog.saveState(settings) settings.endGroup() # method def migrateSettings(self): settings = QtCore.QSettings("Friture", "Friture") #1. move the central widget to a normal dock if settings.contains("CentralWidget/type"): settings.beginGroup("CentralWidget") centralWidgetKeys = settings.allKeys() children = { key: settings.value(key, type=QtCore.QVariant) for key in centralWidgetKeys } settings.endGroup() if not settings.contains("Docks/central/type"): #write them to a new dock instead for key, value in children.items(): settings.setValue("Docks/central/" + key, value) #add the new dock name to dockNames docknames = settings.value("Docks/dockNames", []) docknames = ["central"] + docknames settings.setValue("Docks/dockNames", docknames) settings.remove("CentralWidget") #2. remove any level widget if settings.contains("Docks/dockNames"): docknames = settings.value("Docks/dockNames") newDockNames = [] for dockname in docknames: widgetType = settings.value("Docks/" + dockname + "/type", 0, type=int) if widgetType == 0: settings.remove("Docks/" + dockname) else: newDockNames.append(dockname) settings.setValue("Docks/dockNames", newDockNames) # method def restoreAppState(self): self.migrateSettings() settings = QtCore.QSettings("Friture", "Friture") settings.beginGroup("Docks") self.dockmanager.restoreState(settings) settings.endGroup() settings.beginGroup("MainWindow") self.restoreGeometry( settings.value("windowGeometry", type=QtCore.QByteArray)) self.restoreState(settings.value("windowState", type=QtCore.QByteArray)) settings.endGroup() settings.beginGroup("AudioBackend") self.settings_dialog.restoreState(settings) settings.endGroup() # slot def timer_toggle(self): if self.display_timer.isActive(): Logger().push("Timer stop") self.display_timer.stop() self.ui.actionStart.setText("Start") AudioBackend().pause() self.dockmanager.pause() else: Logger().push("Timer start") self.display_timer.start() self.ui.actionStart.setText("Stop") AudioBackend().restart() self.dockmanager.restart()
class UITenBrushes(object): def __init__(self): self.kritaInstance = krita.Krita.instance() self.mainDialog = tenbrushesdialog.TenBrushesDialog( self, self.kritaInstance.activeWindow().qwindow()) self.buttonBox = QDialogButtonBox(self.mainDialog) self.vbox = QVBoxLayout(self.mainDialog) self.hbox = QHBoxLayout(self.mainDialog) self.checkBoxActivatePrev = QCheckBox( i18n("&Activate previous brush preset when pressing the shortcut for the " "second time"), self.mainDialog) self.checkBoxAutoBrush = QCheckBox( i18n("&Select freehand brush tool when pressing a shortcut"), self.mainDialog) self.buttonBox.accepted.connect(self.mainDialog.accept) self.buttonBox.rejected.connect(self.mainDialog.reject) self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons( QDialogButtonBox.Ok | QDialogButtonBox.Cancel) self.presetChooser = krita.PresetChooser(self.mainDialog) def initialize(self, tenbrushes): self.tenbrushes = tenbrushes self.loadButtons() self.vbox.addLayout(self.hbox) self.vbox.addWidget( QLabel(i18n("Select the brush preset, then click on the button " "you want to use to select the preset."))) self.vbox.addWidget( QLabel(i18n("Shortcuts are configurable through the <i>Keyboard Shortcuts</i> " "interface in Krita's settings."))) self.vbox.addWidget(self.presetChooser) self.checkBoxActivatePrev.setChecked(self.tenbrushes.activatePrev) self.checkBoxActivatePrev.toggled.connect(self.setActivatePrev) self.vbox.addWidget(self.checkBoxActivatePrev) self.checkBoxAutoBrush.setChecked(self.tenbrushes.autoBrush) self.checkBoxAutoBrush.toggled.connect(self.setAutoBrush) self.vbox.addWidget(self.checkBoxAutoBrush) self.vbox.addWidget(self.buttonBox) self.mainDialog.show() self.mainDialog.activateWindow() self.mainDialog.exec_() def setActivatePrev(self, checked): self.tenbrushes.activatePrev = checked def setAutoBrush(self, checked): self.tenbrushes.autoBrush = checked def loadButtons(self): self.tenbrushes.buttons = [] allPresets = Application.resources("preset") for index, item in enumerate(['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']): buttonLayout = QVBoxLayout() button = dropbutton.DropButton(self.mainDialog) button.setObjectName(item) button.clicked.connect(button.selectPreset) button.presetChooser = self.presetChooser action = self.tenbrushes.actions[index] if action and action.preset and action.preset in allPresets: p = allPresets[action.preset] button.preset = p.name() button.setIcon(QIcon(QPixmap.fromImage(p.image()))) buttonLayout.addWidget(button) label = QLabel( action.shortcut().toString()) label.setAlignment(Qt.AlignHCenter) buttonLayout.addWidget(label) self.hbox.addLayout(buttonLayout) self.tenbrushes.buttons.append(button)
class PreferencesDialogBase(QDialog): def __init__(self, parent, app, **kwargs): flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint super().__init__(parent, flags, **kwargs) self.app = app all_languages = get_langnames() self.supportedLanguages = sorted(SUPPORTED_LANGUAGES, key=lambda lang: all_languages[lang]) self._setupUi() self.filterHardnessSlider.valueChanged['int'].connect( self.filterHardnessLabel.setNum) self.buttonBox.clicked.connect(self.buttonClicked) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) def _setupFilterHardnessBox(self): self.filterHardnessHLayout = QHBoxLayout() self.filterHardnessLabel = QLabel(self) self.filterHardnessLabel.setText(tr("Filter Hardness:")) self.filterHardnessLabel.setMinimumSize(QSize(0, 0)) self.filterHardnessHLayout.addWidget(self.filterHardnessLabel) self.filterHardnessVLayout = QVBoxLayout() self.filterHardnessVLayout.setSpacing(0) self.filterHardnessHLayoutSub1 = QHBoxLayout() self.filterHardnessHLayoutSub1.setSpacing(12) self.filterHardnessSlider = QSlider(self) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.filterHardnessSlider.sizePolicy().hasHeightForWidth()) self.filterHardnessSlider.setSizePolicy(sizePolicy) self.filterHardnessSlider.setMinimum(1) self.filterHardnessSlider.setMaximum(100) self.filterHardnessSlider.setTracking(True) self.filterHardnessSlider.setOrientation(Qt.Horizontal) self.filterHardnessHLayoutSub1.addWidget(self.filterHardnessSlider) self.filterHardnessLabel = QLabel(self) self.filterHardnessLabel.setText("100") self.filterHardnessLabel.setMinimumSize(QSize(21, 0)) self.filterHardnessHLayoutSub1.addWidget(self.filterHardnessLabel) self.filterHardnessVLayout.addLayout(self.filterHardnessHLayoutSub1) self.filterHardnessHLayoutSub2 = QHBoxLayout() self.filterHardnessHLayoutSub2.setContentsMargins(-1, 0, -1, -1) self.moreResultsLabel = QLabel(self) self.moreResultsLabel.setText(tr("More Results")) self.filterHardnessHLayoutSub2.addWidget(self.moreResultsLabel) spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.filterHardnessHLayoutSub2.addItem(spacerItem) self.fewerResultsLabel = QLabel(self) self.fewerResultsLabel.setText(tr("Fewer Results")) self.filterHardnessHLayoutSub2.addWidget(self.fewerResultsLabel) self.filterHardnessVLayout.addLayout(self.filterHardnessHLayoutSub2) self.filterHardnessHLayout.addLayout(self.filterHardnessVLayout) def _setupBottomPart(self): # The bottom part of the pref panel is always the same in all editions. self.fontSizeLabel = QLabel(tr("Font size:")) self.fontSizeSpinBox = QSpinBox() self.fontSizeSpinBox.setMinimum(5) self.widgetsVLayout.addLayout( horizontalWrap([self.fontSizeLabel, self.fontSizeSpinBox, None])) self.languageLabel = QLabel(tr("Language:"), self) self.languageComboBox = QComboBox(self) for lang in self.supportedLanguages: self.languageComboBox.addItem(get_langnames()[lang]) self.widgetsVLayout.addLayout( horizontalWrap([self.languageLabel, self.languageComboBox, None])) self.copyMoveLabel = QLabel(self) self.copyMoveLabel.setText(tr("Copy and Move:")) self.widgetsVLayout.addWidget(self.copyMoveLabel) self.copyMoveDestinationComboBox = QComboBox(self) self.copyMoveDestinationComboBox.addItem(tr("Right in destination")) self.copyMoveDestinationComboBox.addItem(tr("Recreate relative path")) self.copyMoveDestinationComboBox.addItem(tr("Recreate absolute path")) self.widgetsVLayout.addWidget(self.copyMoveDestinationComboBox) self.customCommandLabel = QLabel(self) self.customCommandLabel.setText( tr("Custom Command (arguments: %d for dupe, %r for ref):")) self.widgetsVLayout.addWidget(self.customCommandLabel) self.customCommandEdit = QLineEdit(self) self.widgetsVLayout.addWidget(self.customCommandEdit) def _setupAddCheckbox(self, name, label, parent=None): if parent is None: parent = self cb = QCheckBox(parent) cb.setText(label) setattr(self, name, cb) def _setupPreferenceWidgets(self): # Edition-specific pass def _setupUi(self): self.setWindowTitle(tr("Options")) self.setSizeGripEnabled(False) self.setModal(True) self.mainVLayout = QVBoxLayout(self) self.widgetsVLayout = QVBoxLayout() self._setupPreferenceWidgets() self.mainVLayout.addLayout(self.widgetsVLayout) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok | QDialogButtonBox.RestoreDefaults) self.mainVLayout.addWidget(self.buttonBox) self.layout().setSizeConstraint(QLayout.SetFixedSize) def _load(self, prefs, setchecked): # Edition-specific pass def _save(self, prefs, ischecked): # Edition-specific pass def load(self, prefs=None): if prefs is None: prefs = self.app.prefs self.filterHardnessSlider.setValue(prefs.filter_hardness) self.filterHardnessLabel.setNum(prefs.filter_hardness) setchecked = lambda cb, b: cb.setCheckState(Qt.Checked if b else Qt.Unchecked) setchecked(self.mixFileKindBox, prefs.mix_file_kind) setchecked(self.useRegexpBox, prefs.use_regexp) setchecked(self.removeEmptyFoldersBox, prefs.remove_empty_folders) setchecked(self.ignoreHardlinkMatches, prefs.ignore_hardlink_matches) setchecked(self.debugModeBox, prefs.debug_mode) self.copyMoveDestinationComboBox.setCurrentIndex( prefs.destination_type) self.customCommandEdit.setText(prefs.custom_command) self.fontSizeSpinBox.setValue(prefs.tableFontSize) try: langindex = self.supportedLanguages.index(self.app.prefs.language) except ValueError: langindex = 0 self.languageComboBox.setCurrentIndex(langindex) self._load(prefs, setchecked) def save(self): prefs = self.app.prefs prefs.filter_hardness = self.filterHardnessSlider.value() ischecked = lambda cb: cb.checkState() == Qt.Checked prefs.mix_file_kind = ischecked(self.mixFileKindBox) prefs.use_regexp = ischecked(self.useRegexpBox) prefs.remove_empty_folders = ischecked(self.removeEmptyFoldersBox) prefs.ignore_hardlink_matches = ischecked(self.ignoreHardlinkMatches) prefs.debug_mode = ischecked(self.debugModeBox) prefs.destination_type = self.copyMoveDestinationComboBox.currentIndex( ) prefs.custom_command = str(self.customCommandEdit.text()) prefs.tableFontSize = self.fontSizeSpinBox.value() lang = self.supportedLanguages[self.languageComboBox.currentIndex()] oldlang = self.app.prefs.language if oldlang not in self.supportedLanguages: oldlang = 'en' if lang != oldlang: QMessageBox.information( self, "", tr("dupeGuru has to restart for language changes to take effect." )) self.app.prefs.language = lang self._save(prefs, ischecked) def resetToDefaults(self): self.load(Preferences()) #--- Events def buttonClicked(self, button): role = self.buttonBox.buttonRole(button) if role == QDialogButtonBox.ResetRole: self.resetToDefaults()
def __init__(self, parent=None): super(Window, self).__init__(parent) self.setWindowTitle('Feedback Interactive Analysis') self.enzyme = E_PIP5K self.f_type = FEEDBACK_POSITIVE self.f_carry = 1 self.f_multi = 1 self.f_hill = 1 self.f_sub = I_PIP2 self.carry_factor = 1 self.lipids_to_analyze = [I_PIP2] self.mutant_enzyme = E_NONE self.enz_box = None self.show_standard = True # a figure instance to plot on self.figure = plt.figure() # this is the Canvas Widget that displays the `figure` self.canvas = FigureCanvas(self.figure) # it takes the Canvas widget and a parent self.toolbar = NavigationToolbar(self.canvas, self) grid = QGridLayout() widget = QWidget(self) # central widget s_box = QHBoxLayout() substrate_group = QButtonGroup(widget) # Substrate group s_box.addStretch() s_box.setContentsMargins(1, 15, 1, 1) s_box.addWidget(QLabel("Feedback From")) self.substrates = [] for l in LIPID_NAMES: b = QRadioButton(l, self) b.setObjectName(l) b.setCheckable(True) if l == L_PIP2: b.setChecked(True) b.clicked.connect(partial(self.substrate_clicked, l)) self.substrates.append(b) substrate_group.addButton(b) s_box.addWidget(b) display_box = QVBoxLayout() display_box.setContentsMargins(30, 1, 1, 1) display_box.addStretch() self.display_lipids = [] for l in LIPID_NAMES: b = QCheckBox(l) b.setObjectName(l) b.setCheckable(True) if l == L_PIP2: b.setChecked(True) b.clicked.connect(partial(self.on_display_lipid_changed, l)) self.display_lipids.append(b) display_box.addWidget(b) display_box.addStretch() feedback_group = QButtonGroup(widget) # Number group f_box = QVBoxLayout() f_box.setContentsMargins(30, 1, 1, 1) f_box.addStretch() f_box.addWidget(QLabel("Feedback Type")) self.b_pos_feed = QRadioButton("Positive", self) self.b_pos_feed.setObjectName("p") self.b_pos_feed.setCheckable(True) self.b_pos_feed.setChecked(True) self.b_pos_feed.clicked.connect(partial(self.feedback_changed, "p")) feedback_group.addButton(self.b_pos_feed) f_box.addWidget(self.b_pos_feed) self.b_neg_feed = QRadioButton("Negative", self) self.b_neg_feed.setObjectName("n") self.b_neg_feed.setCheckable(True) self.b_neg_feed.clicked.connect(partial(self.feedback_changed, "n")) feedback_group.addButton(self.b_neg_feed) f_box.addWidget(self.b_neg_feed) f_box.addStretch() a_box = QVBoxLayout() a_box.setContentsMargins(30, 30, 30, 15) a_slider = QSlider(Qt.Horizontal, self) a_slider.setMinimum(1) a_slider.setMaximum(100) a_slider.setTickInterval(1) self.a_label = QLabel("Multiplication Factor : 1") a_slider.valueChanged[int].connect(self.multi_changed) a_slider.setValue(1) a_box.addWidget(self.a_label) a_box.addWidget(a_slider) c_box = QVBoxLayout() c_box.setContentsMargins(30, 0, 30, 15) c_slider = QSlider(Qt.Horizontal, self) c_slider.setMinimum(1) c_slider.setMaximum(10) c_slider.setTickInterval(1) self.c_label = QLabel("Carrying Capacity : 1") c_slider.valueChanged[int].connect(self.carry_changed) c_slider.setValue(1) c_sub_box = QHBoxLayout() c_sub_box.addWidget(self.c_label) carry_factor = QComboBox(self) for c in CARRY_FACTORS: carry_factor.addItem(c) carry_factor.activated[str].connect(self.on_carry_factor) c_sub_box.addWidget(carry_factor) c_sub_box.addStretch() c_box.addLayout(c_sub_box, 1) c_box.addWidget(c_slider) h_box = QVBoxLayout() h_box.setContentsMargins(30, 0, 30, 15) h_slider = QSlider(Qt.Horizontal, self) h_slider.setMinimum(0) h_slider.setMaximum(5) h_slider.setTickInterval(1) self.h_label = QLabel("Hill Coefficient") h_slider.valueChanged[int].connect(self.hill_changed) h_slider.setValue(1) h_box.addWidget(self.h_label) h_box.addWidget(h_slider) e_box = QVBoxLayout() e_box.setContentsMargins(30, 1, 1, 1) e_box.addStretch() e_box.addWidget(QLabel("Feedback to")) enz_box = QComboBox(self) for e in ENZYME_NAMES: enz_box.addItem(e) enz_box.activated[str].connect(self.on_enzyme_selection) e_box.addWidget(enz_box) e_box.addStretch() hill_box = QHBoxLayout() hill_box.addLayout(h_box) hill_box.addWidget(self.toggle_plot) grid.addWidget(self.toolbar, 1, 0) grid.addWidget(self.canvas, 2, 0) grid.addLayout(display_box, 1, 1, 2, 2) grid.addLayout(s_box, 4, 0) grid.addLayout(f_box, 5, 1, 2, 2) grid.addLayout(self.mutant_list, 4, 1) grid.addLayout(a_box, 5, 0) grid.addLayout(c_box, 6, 0) grid.addLayout(hill_box, 7, 0) grid.addLayout(e_box, 7, 1) self.setLayout(grid)