class QtPysideApp(QApplication): def __init__(self, renderer, title): QApplication.__init__(self, sys.argv) self.window = QMainWindow() self.window.setWindowTitle(title) self.window.resize(800,600) # Get OpenGL 4.1 context glformat = QGLFormat() glformat.setVersion(4, 1) glformat.setProfile(QGLFormat.CoreProfile) glformat.setDoubleBuffer(False) self.glwidget = MyGlWidget(renderer, glformat, self) self.window.setCentralWidget(self.glwidget) self.window.show() def __enter__(self): "setup for RAII using 'with' keyword" return self def __exit__(self, type_arg, value, traceback): "cleanup for RAII using 'with' keyword" self.glwidget.disposeGL() def run_loop(self): retval = self.exec_() sys.exit(retval)
class WageStat(object): def __init__(self): self.window = QMainWindow() self.window.resize(600, 500) self.window.setWindowTitle('薪酬统筹') self.textEdit = QPlainTextEdit(self.window) self.textEdit.setPlaceholderText('请输入薪资表') self.textEdit.resize(400, 400) self.textEdit.move(100, 25) self.button = QPushButton('统计', self.window) self.button.move(250, 450) self.button.clicked.connect(self.__handler_click) def __handler_click(self): info = self.textEdit.toPlainText() info = info.split('\n') name = '' for data in info: num = re.search(r'\d{4,}', data) if num: if int(num.group()) <= 20000: name += data[0:4] + '\n' else: print('匹配失败') QMessageBox.about(self.window, '统计结果', f'薪资低于2万人员名单\n{name}')
def run(self): # 2. Implement run() window = QMainWindow() version = self.build_settings["version"] window.setWindowTitle("HelloWorld v" + version) window.resize(250, 150) window.show() return self.app.exec_() # 3. End run() with this line
def run_interface(): app = QApplication(sys.argv) window = QMainWindow() widget = DicomMoveWindow() window.setCentralWidget(widget) window.setWindowTitle("Dicom move") window.resize(600, widget.sizeHint().height()) window.show() sys.exit(app.exec_())
def main(): app = QApplication([]) windows = QMainWindow() windows.resize(500, 400) windows.move(300, 310) windows.show() app.exec_()
def make_pdl_editor(parent): pdl_editor = PDLEditor() w = QMainWindow(parent=parent) w.setCentralWidget(pdl_editor) w.setWindowModality(Qt.WindowModal) w.resize(1000, 800) return w
def create_window(IMG_PATH): #initial window creation app = QApplication([]) qpix = QPixmap(IMG_PATH) w, h = get_screen_dim(app.desktop()) qpix, iw, ih = scale_qpix(qpix, w, h) window = QMainWindow() window.resize(w, h) window.setWindowFlags(Qt.WindowStaysOnBottomHint | Qt.FramelessWindowHint) bg = QBackgroundImage(window, w, h) bg.setBackground(qpix, iw, ih) window.show() sys.exit(app.exec_())
class CSDN(): def __init__(self): self.windows = QMainWindow() self.windows.resize(450, 300) self.windows.setWindowTitle("轻松获取csdn文章--by tansty") self.setup_ui() self.set_connect() def set_connect(self): #设置建立联系 self.button.clicked.connect(self.spider_csdn) def setup_ui(self): #设置ui界面的建立 self.button = QPushButton(self.windows) self.button.resize(100, 100) self.button.move(150, 150) self.button.setText("获取文章") self.text = QPlainTextEdit(self.windows) self.text.setPlaceholderText("请输入需要获取文章的链接") self.text.resize(450, 100) def spider_csdn(self): # 目标文章的链接 title_url = self.text.toPlainText() MessageBox = QMessageBox(self.windows) if not title_url: MessageBox.critical(self.windows, "错误", "请输入网址") return head = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36 Edg/84.0.522.52" } html = requests.get(url=title_url, headers=head).text page = parsel.Selector(html) #创建解释器 title = page.css(".title-article::text").get() res = re.compile("[^\u4e00-\u9fa5^a-z^A-Z^0-9]") restr = '' res.sub(restr, title) content = page.css("article").get() content = re.sub("<a.*?a>", "", content) content = re.sub("<br>", "", content) texts = tomd.Tomd(content).markdown #转换为markdown 文件 with open(title + ".md", mode="w", encoding="utf-8") as f: f.write("#" + title) f.write(texts) MessageBox.information(self.windows, "正确", "获取文章完成")
class JosephusUIOnPyside2(QTUI): def __init__(self, title) -> None: self.window = QMainWindow() self.window.resize(500, 400) self.window.move(300, 310) self.window.setWindowTitle(title) self.textEdit = QPlainTextEdit(self.window) self.textEdit.setPlaceholderText("Please input people's items") self.textEdit.move(10, 25) self.textEdit.resize(300, 350) self.button = QPushButton('Generate survior', self.window) self.button.move(380, 80) self.button.clicked.connect(self.handle_button) def handle_button(self) -> None: people_info = self.textEdit.toPlainText() reader = [] for row in people_info: data = row(read_files.str2list_row) reader.append(data) ring = Josephus.Ring(reader) ring.start = 0 ring.step = 1 res = ring.query_list_all() size_res = len(res) generator = ring.iter() survior = '' for i in range(size_res): some_one = next(generator) if some_one == None: break if i == size_res - 1: survior = 'Survivor\'s name is' + some_one.name + \ 'age is' + some_one.age + 'gender is' + some_one.gender else: continue QmessageBox.about(self.window, 'Survior\'s items', survior)
class Stats(): def __init__(self): self.window = QMainWindow() self.window.resize(500, 400) self.window.move(300, 300) self.window.setWindowTitle('薪资统计') self.textEdit = QPlainTextEdit(self.window) self.textEdit.setPlaceholderText('请输入薪资表') self.textEdit.move(10, 25) self.textEdit.resize(300, 350) self.button = QPushButton('统计', self.window) self.button.move(380, 80) self.button.clicked.connect(self.handleCalc) pass def handleCalc(self): info = self.textEdit.toPlainText() salary_above_20k = '' salary_below_20k = '' for line in info.splitlines(): if not line.strip(): continue pass parts = line.split(' ') print(type(parts)) parts = [p for p in parts if p] name, salary, age = parts if int(salary) >= 20000: salary_above_20k += name + '\n' pass else: salary_below_20k += name + '\n' pass pass QMessageBox.about( self.window, '统计结果', f'''薪资20000 以上的有:\n{salary_above_20k} \n薪资20000 以下的有:\n{salary_below_20k}''') pass pass
class Stats(): def __init__(self): self.window = QMainWindow() self.window.resize(500, 400) self.window.move(300, 300) self.window.setWindowTitle('学生管理系统') self.label_account = QLabel(self.window) self.label_password = QLabel(self.window) self.label_account.setText("账号") self.label_password.setText("密码") self.textEdit = QPlainTextEdit(self.window) self.textEdit.setPlaceholderText("请输入薪资表") self.textEdit.move(10, 25) self.textEdit.resize(300, 350) self.button = QPushButton('统计', self.window) self.button.move(380, 80) self.button.clicked.connect(self.handleCalc) def handleCalc(self): info = self.textEdit.toPlainText() print(info) # 薪资20000 以上 和 以下 的人员名单 salary_above_20k = '' salary_below_20k = '' for line in info.splitlines(): print(line) if not line.strip(): continue parts = line.split(' ') # 去掉列表中的空字符串内容 parts = [p for p in parts if p] name, salary, age = parts if int(salary) >= 20000: salary_above_20k += name + '\n' else: salary_below_20k += name + '\n' QMessageBox.about( self.window, '统计结果', f'''薪资20000 以上的有:\n{salary_above_20k} \n薪资20000 以下的有:\n{salary_below_20k}''')
def _open_item_tracker(self): # Importing this at root level seems to crash linux tests :( from PySide2.QtWebEngineWidgets import QWebEngineView tracker_window = QMainWindow() tracker_window.setWindowTitle("Item Tracker") tracker_window.resize(370, 380) web_view = QWebEngineView(tracker_window) tracker_window.setCentralWidget(web_view) self.web_view = web_view def update_window_icon(): tracker_window.setWindowIcon(web_view.icon()) web_view.iconChanged.connect(update_window_icon) web_view.load(QUrl("https://spaghettitoastbook.github.io/echoes/tracker/")) tracker_window.show() self._item_tracker_window = tracker_window
class Stats(): def __init__(self): # 主窗口 self.window = QMainWindow() self.window.resize(500, 400) self.window.move(300, 300) self.window.setWindowTitle('薪资统计') # 纯文本框 self.textEdit = QPlainTextEdit(self.window) self.textEdit.setPlaceholderText("请输入薪资表") self.textEdit.move(10, 25) self.textEdit.resize(300, 350) # 按钮 self.button = QPushButton('统计', self.window) self.button.move(380, 80) # 按钮绑定响应函数 self.button.clicked.connect(self.handleCalc) def handleCalc(self): # 获取纯文本框里的内容 info = self.textEdit.toPlainText() # 薪资20000 以上 和 以下 的人员名单 salary_above_20k = '' salary_below_20k = '' for line in info.splitlines(): if not line.strip(): continue parts = line.split(' ') # 去掉列表中的空字符串内容 parts = [p for p in parts if p] name, salary, age = parts if int(salary) >= 20000: salary_above_20k += name + '\n' else: salary_below_20k += name + '\n' QMessageBox.about( self.window, '统计结果', f'''薪资20000 以上的有:\n{salary_above_20k} \n薪资20000 以下的有:\n{salary_below_20k}''')
def run(self): # 2. Implement run() window = QMainWindow() self.ui = Ui_MainWindow() self.ui.setupUi(window) version = self.build_settings['version'] window.setWindowTitle("NosDamage v" + version) window.resize(250, 150) window.show() version_checker = VersionCheckerService(version) version_checker.needUpdate.connect(lambda need_update: ( self.show_update_dialog() if need_update else None)) version_checker.start() entities = ObservableList(ps.load_entities()) self.editor_controller = EditorController(self.ui, entities) self.calculator_controller = CalculatorController(self.ui, entities) entities.add_observer(self.calculator_controller) return self.app.exec_() # 3. End run() with this line
class Stats: def __init__(self): self.ui = QUiLoader().load('F:\\Msc_project.ui') self.ui.PushButton.clicked.connect(self.handleCalc) self.ui.pushButton_2.clicked.connect(self.handleCalc2) self.window = QMainWindow() self.window.resize(500, 400) self.window.move(450, 200) self.ui.radioButton.clicked.connect(self.handleCalc3) self.ui.radioButton_2.clicked.connect(self.handleCalc4) self.pattern = 1 def handleCalc(self): sent = self.ui.plainTextEdit.toPlainText() length = len(sent) print(length) if length == 0: QMessageBox.about(self.window, 'warnning:empty input', 'please write something!') elif (length != 0 and self.pattern == 1): # model = Seq2Seq().to(cfg.device) # model.load_state_dict(torch.load('D:\\NMT\\model.pt',map_location='cpu')['model_dict']) result = predict(sent, model) self.ui.plainTextEdit_2.appendPlainText(result) else: QMessageBox.about(self.window, 'warnning:change the src and target', 'will coming') def handleCalc2(self): self.ui.plainTextEdit_2.clear() def handleCalc3(self): self.pattern = 1 def handleCalc4(self): self.pattern = 2
def __init__(self, BigScript: QMainWindow): # Set Window parameters BigScript.setWindowTitle("ASL Tools - Big Script") BigScript.setWindowFlag(Qt.Window) # Main frame frame = QWidget(BigScript) self.h_layout = QHBoxLayout(frame) # Menubar menubar = BigScript.menuBar() menu_file: QMenu = menubar.addMenu("Fichier") self.action_file_new = QAction("Nouveau", menubar) self.action_file_new.setIcon(QIcon(":/images/new-file.svg")) self.action_file_new.setShortcut("Ctrl+N") menu_file.addAction(self.action_file_new) self.action_file_save = QAction("Enregistrer", menubar) self.action_file_save.setIcon(QIcon(":/images/save.svg")) self.action_file_save.setShortcut("Ctrl+S") menu_file.addAction(self.action_file_save) self.action_file_saveas = QAction("Enregistrer sous", menubar) self.action_file_saveas.setIcon(QIcon(":/images/save-as.svg")) self.action_file_saveas.setShortcut("Ctrl+Shift+S") menu_file.addAction(self.action_file_saveas) menu_file.addSeparator() self.action_file_export = QAction("Exporter", menubar) self.action_file_export.setIcon(QIcon(":/images/export.svg")) menu_file.addAction(self.action_file_export) menu_file.addSeparator() self.action_file_quit = QAction("Quitter", menubar) self.action_file_quit.setIcon(QIcon(":/images/quit.svg")) menu_file.addAction(self.action_file_quit) # Spacer spacerItem = QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.h_layout.addItem(spacerItem) # Grid layout self.gridLayout = QtWidgets.QGridLayout() self.gridLayout.setSpacing(15) # File self.label_file = QtWidgets.QLabel(frame) self.label_file.setTextFormat(QtCore.Qt.PlainText) self.label_file.setAlignment(QtCore.Qt.AlignCenter) self.label_file.setObjectName("label_file") self.gridLayout.addWidget(self.label_file, 0, 0, 1, 4) # Header self.label_from = QLabel(frame) self.gridLayout.addWidget(self.label_from, 1, 1, 1, 1) self.label_to = QLabel(frame) self.gridLayout.addWidget(self.label_to, 1, 2, 1, 1) self.label_step = QLabel(frame) self.gridLayout.addWidget(self.label_step, 1, 3, 1, 1) # Resistance self.label_r = QLabel(frame) self.gridLayout.addWidget(self.label_r, 2, 0, 1, 1) self.r_from = QtWidgets.QSpinBox(frame) self.r_from.setObjectName("grid-spin") self.r_from.setMinimum(0) self.r_from.setMaximum(200) self.gridLayout.addWidget(self.r_from, 2, 1, 1, 1) self.r_to = QtWidgets.QSpinBox(frame) self.r_to.setObjectName("grid-spin") self.r_to.setMinimum(0) self.r_to.setMaximum(200) self.gridLayout.addWidget(self.r_to, 2, 2, 1, 1) self.r_step = QtWidgets.QSpinBox(frame) self.r_step.setObjectName("grid-spin") self.r_step.setMinimum(1) self.gridLayout.addWidget(self.r_step, 2, 3, 1, 1) # Compliance self.label_c = QLabel(frame) self.gridLayout.addWidget(self.label_c, 3, 0, 1, 1) self.c_from = QtWidgets.QSpinBox(frame) self.c_from.setObjectName("grid-spin") self.c_from.setMinimum(0) self.c_from.setMaximum(200) self.gridLayout.addWidget(self.c_from, 3, 1, 1, 1) self.c_to = QtWidgets.QSpinBox(frame) self.c_to.setObjectName("grid-spin") self.c_to.setMinimum(0) self.c_to.setMaximum(200) self.gridLayout.addWidget(self.c_to, 3, 2, 1, 1) self.c_step = QtWidgets.QSpinBox(frame) self.c_step.setObjectName("grid-spin") self.c_step.setMinimum(1) self.gridLayout.addWidget(self.c_step, 3, 3, 1, 1) # Breath rate self.label_br = QLabel(frame) self.gridLayout.addWidget(self.label_br, 4, 0, 1, 1) self.br_from = QtWidgets.QSpinBox(frame) self.br_from.setObjectName("grid-spin") self.br_from.setMinimum(1) self.br_from.setMaximum(100) self.gridLayout.addWidget(self.br_from, 4, 1, 1, 1) self.br_to = QtWidgets.QSpinBox(frame) self.br_to.setObjectName("grid-spin") self.br_to.setMinimum(1) self.br_to.setMaximum(100) self.gridLayout.addWidget(self.br_to, 4, 2, 1, 1) self.br_step = QtWidgets.QSpinBox(frame) self.br_step.setObjectName("grid-spin") self.br_step.setMinimum(1) self.gridLayout.addWidget(self.br_step, 4, 3, 1, 1) # Pmus self.label_i_pmus = QLabel(frame) self.gridLayout.addWidget(self.label_i_pmus, 5, 0, 1, 1) self.i_pmus_from = QtWidgets.QSpinBox(frame) self.i_pmus_from.setObjectName("grid-spin") self.i_pmus_from.setMinimum(0) self.i_pmus_from.setMaximum(100) self.gridLayout.addWidget(self.i_pmus_from, 5, 1, 1, 1) self.i_pmus_to = QtWidgets.QSpinBox(frame) self.i_pmus_to.setObjectName("grid-spin") self.i_pmus_to.setMinimum(0) self.i_pmus_to.setMaximum(100) self.gridLayout.addWidget(self.i_pmus_to, 5, 2, 1, 1) self.i_pmus_step = QtWidgets.QSpinBox(frame) self.i_pmus_step.setObjectName("grid-spin") self.i_pmus_step.setMinimum(1) self.gridLayout.addWidget(self.i_pmus_step, 5, 3, 1, 1) # Pmus increase self.label_i_pmus_inc = QLabel(frame) self.gridLayout.addWidget(self.label_i_pmus_inc, 6, 0, 1, 1) self.i_pmus_inc_from = QtWidgets.QSpinBox(frame) self.i_pmus_inc_from.setObjectName("grid-spin") self.i_pmus_inc_from.setMinimum(0) self.i_pmus_inc_from.setMaximum(100) self.gridLayout.addWidget(self.i_pmus_inc_from, 6, 1, 1, 1) self.i_pmus_inc_to = QtWidgets.QSpinBox(frame) self.i_pmus_inc_to.setObjectName("grid-spin") self.i_pmus_inc_to.setMinimum(0) self.i_pmus_inc_to.setMaximum(100) self.gridLayout.addWidget(self.i_pmus_inc_to, 6, 2, 1, 1) self.i_pmus_inc_step = QtWidgets.QSpinBox(frame) self.i_pmus_inc_step.setObjectName("grid-spin") self.i_pmus_inc_step.setMinimum(1) self.gridLayout.addWidget(self.i_pmus_inc_step, 6, 3, 1, 1) # Pmus hold self.label_i_pmus_hld = QLabel(frame) self.gridLayout.addWidget(self.label_i_pmus_hld, 7, 0, 1, 1) self.i_pmus_hld_from = QtWidgets.QSpinBox(frame) self.i_pmus_hld_from.setObjectName("grid-spin") self.i_pmus_hld_from.setMinimum(0) self.i_pmus_hld_from.setMaximum(100) self.gridLayout.addWidget(self.i_pmus_hld_from, 7, 1, 1, 1) self.i_pmus_hld_to = QtWidgets.QSpinBox(frame) self.i_pmus_hld_to.setObjectName("grid-spin") self.i_pmus_hld_to.setMinimum(0) self.i_pmus_hld_to.setMaximum(100) self.gridLayout.addWidget(self.i_pmus_hld_to, 7, 2, 1, 1) self.i_pmus_hld_step = QtWidgets.QSpinBox(frame) self.i_pmus_hld_step.setObjectName("grid-spin") self.i_pmus_hld_step.setMinimum(1) self.gridLayout.addWidget(self.i_pmus_hld_step, 7, 3, 1, 1) # Pmus hold self.label_i_pmus_rel = QLabel(frame) self.gridLayout.addWidget(self.label_i_pmus_rel, 8, 0, 1, 1) self.i_pmus_rel_from = QtWidgets.QSpinBox(frame) self.i_pmus_rel_from.setObjectName("grid-spin") self.i_pmus_rel_from.setMinimum(0) self.i_pmus_rel_from.setMaximum(100) self.gridLayout.addWidget(self.i_pmus_rel_from, 8, 1, 1, 1) self.i_pmus_rel_to = QtWidgets.QSpinBox(frame) self.i_pmus_rel_to.setObjectName("grid-spin") self.i_pmus_rel_to.setMinimum(0) self.i_pmus_rel_to.setMaximum(100) self.gridLayout.addWidget(self.i_pmus_rel_to, 8, 2, 1, 1) self.i_pmus_rel_step = QtWidgets.QSpinBox(frame) self.i_pmus_rel_step.setObjectName("grid-spin") self.i_pmus_rel_step.setMinimum(1) self.gridLayout.addWidget(self.i_pmus_rel_step, 8, 3, 1, 1) # Repetitions self.label_n_cycles = QLabel(frame) self.gridLayout.addWidget(self.label_n_cycles, 9, 0, 1, 1) self.n_cycles = QtWidgets.QSpinBox(frame) self.n_cycles.setObjectName("grid-spin") self.n_cycles.setMinimum(0) self.n_cycles.setMaximum(100) self.gridLayout.addWidget(self.n_cycles, 9, 1, 1, 1) # Informations separator = QtWidgets.QFrame(frame) separator.setFrameShape(QtWidgets.QFrame.HLine) separator.setFrameShadow(QtWidgets.QFrame.Sunken) self.gridLayout.addWidget(separator, 10, 0, 1, 4) self.label_tot_simus = QLabel(frame) self.gridLayout.addWidget(self.label_tot_simus, 11, 0, 1, 1) self.tot_simus = QLabel(frame) self.gridLayout.addWidget(self.tot_simus, 11, 1, 1, 1) self.label_tot_time = QLabel(frame) self.gridLayout.addWidget(self.label_tot_time, 12, 0, 1, 3) self.tot_time = QLabel(frame) self.gridLayout.addWidget(self.tot_time, 12, 1, 1, 3) # Progress self.progress = QProgressBar(frame) self.progress.setMaximumHeight(10) self.progress.setTextVisible(False) self.gridLayout.addWidget(self.progress, 13, 0, 1, 4) # Spacer spacerItem = QSpacerItem(40, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) self.gridLayout.addItem(spacerItem, 14, 0, 1, 4) self.h_layout.addLayout(self.gridLayout) spacerItem5 = QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.h_layout.addItem(spacerItem5) # Set size and position w, h = self.h_layout.sizeHint().toTuple() w_s, h_s = QApplication.primaryScreen().size().toTuple() x = round(w_s / 2 - w / 2) y = round(h_s / 2 - h / 2) BigScript.setCentralWidget(frame) BigScript.resize(w, h) BigScript.move(x, y) self.retranslateUi(BigScript) QtCore.QMetaObject.connectSlotsByName(BigScript)
csSet.setLow(x[3]) csSet.setClose(x[4]) series1.append(csSet) chart.addSeries(series1) chart.createDefaultAxes() axisX = QtCharts.QBarCategoryAxis() axisX.setCategories( [QDateTime.fromMSecsSinceEpoch(d[0]).toString("d") for d in data]) axisX.setTitleText("day") axisY = QtCharts.QValueAxis() axisY.setMax(chart.axisY().max() * 1.01) axisY.setMin(chart.axisY().min() * 0.99) chart.setAxisX(axisX, series1) chart.setAxisY(axisY, series1) chartView = QtCharts.QChartView(chart) chartView.setRenderHint(QPainter.Antialiasing) window = QMainWindow() window.setCentralWidget(chartView) window.resize(400, 300) window.show() sys.exit(app.exec_())
category_item = QTreeWidgetItem() category_item.setText(0, category) for elem_name in d[category]: it = QTreeWidgetItem() it.setText(0, elem_name) category_item.addChild(it) self.addTopLevelItem(category_item) if __name__ == "__main__": app = QApplication() w = QMainWindow() w.setMinimumSize(640, 480) w.resize(1280, 720) elems = ElementTree() elems.create_from_dict(ELEMENTS) elems.expandAll() dw = QDockWidget() dw.setWidget(elems) dw.setWindowTitle('Elements') dw.setFeatures(QDockWidget.DockWidgetMovable | QDockWidget.DockWidgetFloatable) w.addDockWidget(Qt.LeftDockWidgetArea, dw) sim = Simulator() g = NotGate(1) g.name = 'gate' sim.root = g
def __init__(self, Settings: QMainWindow): # Set window parameters Settings.setWindowTitle("ASL Tools - Settings") Settings.setWindowFlag(Qt.Window) icon_size = QSize(48, 48) # Main frame frame = QWidget() frame.setObjectName("mainwindow") self.v_layout = QVBoxLayout(frame) # Select tool window location self.label_location = QLabel() self.v_layout.addWidget(self.label_location) self.group_corner = QButtonGroup() self.grid_layout = QGridLayout() # Top left corner self.btn_corner_tl = QPushButton() self.btn_corner_tl.setObjectName("top-left") self.btn_corner_tl.setIcon(QIcon(":/images/corner-tl.svg")) self.btn_corner_tl.setIconSize(QSize(32, 32)) self.btn_corner_tl.setCheckable(True) self.group_corner.addButton(self.btn_corner_tl) self.grid_layout.addWidget(self.btn_corner_tl, 0, 1) # Top right corner self.btn_corner_tr = QPushButton() self.btn_corner_tr.setObjectName("top-right") self.btn_corner_tr.setIcon(QIcon(":/images/corner-tr.svg")) self.btn_corner_tr.setIconSize(QSize(32, 32)) self.btn_corner_tr.setCheckable(True) self.group_corner.addButton(self.btn_corner_tr) self.grid_layout.addWidget(self.btn_corner_tr, 0, 2) # bottom left corner self.btn_corner_bl = QPushButton() self.btn_corner_bl.setObjectName("bottom-left") self.btn_corner_bl.setIcon(QIcon(":/images/corner-bl.svg")) self.btn_corner_bl.setIconSize(QSize(32, 32)) self.btn_corner_bl.setCheckable(True) self.group_corner.addButton(self.btn_corner_bl) self.grid_layout.addWidget(self.btn_corner_bl, 1, 1) # Bottom right corner self.btn_corner_br = QPushButton() self.btn_corner_br.setObjectName("bottom-right") self.btn_corner_br.setIcon(QIcon(":/images/corner-br.svg")) self.btn_corner_br.setIconSize(QSize(32, 32)) self.btn_corner_br.setCheckable(True) self.group_corner.addButton(self.btn_corner_br) self.grid_layout.addWidget(self.btn_corner_br, 1, 2) # Spacers spacer = QSpacerItem(20, 20) self.grid_layout.addItem(spacer, 0, 0) spacer = QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.grid_layout.addItem(spacer, 0, 3) self.v_layout.addLayout(self.grid_layout) # Window fit the layout Settings.setCentralWidget(frame) # Set size and position w, h = self.v_layout.sizeHint().toTuple() w_s, h_s = QApplication.primaryScreen().size().toTuple() x = round(w_s / 2 - w / 2) y = round(h_s / 2 - h / 2) Settings.setCentralWidget(frame) Settings.resize(w, h) Settings.move(x, y) self.retranslateUi(Settings) QtCore.QMetaObject.connectSlotsByName(Settings)
import os import sys from PySide2.QtWidgets import QApplication, QMainWindow from PySide2.QtWebEngineWidgets import QWebEngineView from PySide2.QtCore import QUrl if __name__ == "__main__": BASE_DIR = os.path.dirname(__file__) print('BASE_DIR=%s' % BASE_DIR) app = QApplication(sys.argv) frame = QMainWindow() frame.resize(800, 600) frame.setWindowTitle("测试") webView = QWebEngineView() webView.load(QUrl("web_file.html")) sys.exit(app.exec_())
def __init__(self, Script:QMainWindow): # Set window parameters Script.setWindowTitle("ASL Tools - Script") Script.setWindowFlag(Qt.Window) # Main frame frame = QWidget(Script) self.h_layout = QHBoxLayout(frame) # Menubar menubar = Script.menuBar() menu_file:QMenu = menubar.addMenu("Fichier") self.action_file_new = QAction("Nouveau", menubar) self.action_file_new.setIcon(QIcon(":/images/new-file.svg")) self.action_file_new.setShortcut("Ctrl+N") menu_file.addAction(self.action_file_new) self.action_file_open = QAction("Ouvrir", menubar) self.action_file_open.setIcon(QIcon(":/images/open-file.svg")) self.action_file_open.setShortcut("Ctrl+O") menu_file.addAction(self.action_file_open) self.action_file_save = QAction("Enregistrer", menubar) self.action_file_save.setIcon(QIcon(":/images/save.svg")) self.action_file_save.setShortcut("Ctrl+S") menu_file.addAction(self.action_file_save) self.action_file_saveas = QAction("Enregistrer sous", menubar) self.action_file_saveas.setIcon(QIcon(":/images/save-as.svg")) self.action_file_saveas.setShortcut("Ctrl+Shift+S") menu_file.addAction(self.action_file_saveas) menu_file.addSeparator() self.action_file_export = QAction("Exporter", menubar) self.action_file_export.setIcon(QIcon(":/images/export.svg")) menu_file.addAction(self.action_file_export) menu_file.addSeparator() self.action_file_quit = QAction("Quitter", menubar) self.action_file_quit.setIcon(QIcon(":/images/quit.svg")) menu_file.addAction(self.action_file_quit) menu_edit:QMenu = menubar.addMenu("Edition") self.action_edit_copy = QAction("Copier", menubar) self.action_edit_copy.setIcon(QIcon(":/images/copy.svg")) self.action_edit_copy.setShortcut("Alt+C") menu_edit.addAction(self.action_edit_copy) self.action_edit_paste = QAction("Coller", menubar) self.action_edit_paste.setIcon(QIcon(":/images/paste.svg")) self.action_edit_paste.setShortcut("Alt+V") menu_edit.addAction(self.action_edit_paste) # Spacer spacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.h_layout.addItem(spacer) # Main grid self.grid_layout = QtWidgets.QGridLayout() # Filename self.label_file = QtWidgets.QLabel(frame) self.label_file.setAlignment(QtCore.Qt.AlignCenter) self.label_file.setObjectName("label_file") self.grid_layout.addWidget(self.label_file, 0, 0, 1, 2) # Action widgets self.h_layout_actions = QtWidgets.QHBoxLayout() self.btn_add = QtWidgets.QToolButton(frame) self.btn_add.setEnabled(True) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(":/images/add.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.btn_add.setIcon(icon) self.btn_add.setIconSize(QtCore.QSize(24, 24)) self.btn_add.setAutoRaise(True) self.h_layout_actions.addWidget(self.btn_add) self.btn_remove = QtWidgets.QToolButton(frame) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(":/images/remove.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.btn_remove.setIcon(icon) self.btn_remove.setIconSize(QtCore.QSize(24, 24)) self.btn_remove.setAutoRaise(True) self.h_layout_actions.addWidget(self.btn_remove) self.btn_move_up = QtWidgets.QToolButton(frame) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(":/images/arrow-up.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.btn_move_up.setIcon(icon) self.btn_move_up.setIconSize(QtCore.QSize(24, 24)) self.btn_move_up.setAutoRaise(True) self.h_layout_actions.addWidget(self.btn_move_up) self.btn_move_down = QtWidgets.QToolButton(frame) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(":/images/arrow-down.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.btn_move_down.setIcon(icon) self.btn_move_down.setIconSize(QtCore.QSize(24, 24)) self.btn_move_down.setAutoRaise(True) self.h_layout_actions.addWidget(self.btn_move_down) spacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.h_layout_actions.addItem(spacer) self.grid_layout.addLayout(self.h_layout_actions, 1, 0, 1, 1) # List widget self.list = QtWidgets.QListWidget(frame) self.grid_layout.addWidget(self.list, 2, 0, 1, 1) # Grid self.grid_layout_form = QtWidgets.QGridLayout() # Compliance self.label_compliance = QtWidgets.QLabel(frame) self.grid_layout_form.addWidget(self.label_compliance, 0, 0, 1, 1) self.compliance = QtWidgets.QSpinBox(frame) self.compliance.setMaximum(500) self.grid_layout_form.addWidget(self.compliance, 0, 1, 1, 1) # Resistance self.label_resistance = QtWidgets.QLabel(frame) self.grid_layout_form.addWidget(self.label_resistance, 1, 0, 1, 1) self.resistance = QtWidgets.QSpinBox(frame) self.resistance.setMaximum(500) self.grid_layout_form.addWidget(self.resistance, 1, 1, 1, 1) # Respiratory rate self.label_respi_rate = QtWidgets.QLabel(frame) self.grid_layout_form.addWidget(self.label_respi_rate, 2, 0, 1, 1) self.respi_rate = QtWidgets.QSpinBox(frame) self.respi_rate.setMaximum(500) self.grid_layout_form.addWidget(self.respi_rate, 2, 1, 1, 1) # Spacer spacerItem1 = QtWidgets.QSpacerItem(20, 30, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred) self.grid_layout_form.addItem(spacerItem1, 4, 0, 1, 1) # Pmus insp self.label_i_pmus = QtWidgets.QLabel(frame) self.grid_layout_form.addWidget(self.label_i_pmus, 5, 0, 1, 1) self.i_pmus = QtWidgets.QSpinBox(frame) self.i_pmus.setMaximum(100) self.grid_layout_form.addWidget(self.i_pmus, 5, 1, 1, 1) # Pmus insp inc self.label_i_pmus_inc = QtWidgets.QLabel(frame) self.grid_layout_form.addWidget(self.label_i_pmus_inc, 6, 0, 1, 1) self.i_pmus_inc = QtWidgets.QSpinBox(frame) self.i_pmus_inc.setMaximum(100) self.grid_layout_form.addWidget(self.i_pmus_inc, 6, 1, 1, 1) # Pmus insp hold self.label_i_pmus_hld = QtWidgets.QLabel(frame) self.grid_layout_form.addWidget(self.label_i_pmus_hld, 7, 0, 1, 1) self.i_pmus_hld = QtWidgets.QSpinBox(frame) self.i_pmus_hld.setMaximum(100) self.grid_layout_form.addWidget(self.i_pmus_hld, 7, 1, 1, 1) # Pmus insp rel self.label_i_pmus_rel = QtWidgets.QLabel(frame) self.grid_layout_form.addWidget(self.label_i_pmus_rel, 8, 0, 1, 1) self.i_pmus_rel = QtWidgets.QSpinBox(frame) self.i_pmus_rel.setMaximum(100) self.grid_layout_form.addWidget(self.i_pmus_rel, 8, 1, 1, 1) # Spacer spacerItem4 = QtWidgets.QSpacerItem(20, 30, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred) self.grid_layout_form.addItem(spacerItem4, 9, 0, 1, 1) # Pmus exp self.label_e_pmus = QtWidgets.QLabel(frame) self.grid_layout_form.addWidget(self.label_e_pmus, 10, 0, 1, 1) self.e_pmus = QtWidgets.QSpinBox(frame) self.e_pmus.setMaximum(100) self.grid_layout_form.addWidget(self.e_pmus, 10, 1, 1, 1) # Pmus exp inc self.label_e_pmus_inc = QtWidgets.QLabel(frame) self.grid_layout_form.addWidget(self.label_e_pmus_inc, 11, 0, 1, 1) self.e_pmus_inc = QtWidgets.QSpinBox(frame) self.e_pmus_inc.setMaximum(100) self.grid_layout_form.addWidget(self.e_pmus_inc, 11, 1, 1, 1) # Pmus exp hold self.label_e_pmus_hld = QtWidgets.QLabel(frame) self.grid_layout_form.addWidget(self.label_e_pmus_hld, 12, 0, 1, 1) self.e_pmus_hld = QtWidgets.QSpinBox(frame) self.e_pmus_hld.setMaximum(100) self.grid_layout_form.addWidget(self.e_pmus_hld, 12, 1, 1, 1) # Pmus exp rel self.label_e_pmus_rel = QtWidgets.QLabel(frame) self.grid_layout_form.addWidget(self.label_e_pmus_rel, 13, 0, 1, 1) self.e_pmus_rel = QtWidgets.QSpinBox(frame) self.e_pmus_rel.setMaximum(100) self.grid_layout_form.addWidget(self.e_pmus_rel, 13, 1, 1, 1) # Spacer spacerItem3 = QtWidgets.QSpacerItem(20, 30, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred) self.grid_layout_form.addItem(spacerItem3, 14, 0, 1, 1) # CRF self.label_crf = QtWidgets.QLabel(frame) self.grid_layout_form.addWidget(self.label_crf, 15, 0, 1, 1) self.crf = QtWidgets.QDoubleSpinBox(frame) self.crf.setDecimals(1) self.crf.setSingleStep(0.1) self.grid_layout_form.addWidget(self.crf, 15, 1, 1, 1) # Spacer spacerItem2 = QtWidgets.QSpacerItem(20, 30, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Preferred) self.grid_layout_form.addItem(spacerItem2, 16, 0, 1, 1) # Repetions self.label_repetitions = QtWidgets.QLabel(frame) self.grid_layout_form.addWidget(self.label_repetitions, 17, 0, 1, 1) self.repetitions = QtWidgets.QSpinBox(frame) self.repetitions.setMaximum(9999) self.grid_layout_form.addWidget(self.repetitions, 17, 1, 1, 1) self.label_repetitions_total = QtWidgets.QLabel(frame) self.label_repetitions_total.setMinimumWidth(30) self.grid_layout_form.addWidget(self.label_repetitions_total, 17, 2, 1, 1) # Spacer spacerItem2 = QtWidgets.QSpacerItem(20, 30, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) self.grid_layout_form.addItem(spacerItem2, 18, 0, 1, 1) # Set form layout in the main grid self.grid_layout.addLayout(self.grid_layout_form, 2, 1, 1, 1) # Progress bar self.progress = QProgressBar(frame) self.progress.setMaximumHeight(10) self.progress.setTextVisible(False) self.grid_layout.addWidget(self.progress, 3, 0, 1, 2) # Spacer spacer = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding) self.grid_layout.addItem(spacer, 4, 0, 1, 2) self.h_layout.addLayout(self.grid_layout) spacer = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum) self.h_layout.addItem(spacer) # Set size and position w, h = self.h_layout.sizeHint().toTuple() w_s, h_s = QApplication.primaryScreen().size().toTuple() x = round(w_s/2 - w/2) y = round(h_s/2 - h/2) Script.setCentralWidget(frame) Script.resize(w, h) Script.move(x, y) self.retranslateUi(Script) QtCore.QMetaObject.connectSlotsByName(Script) Script.setTabOrder(self.btn_add, self.btn_remove) Script.setTabOrder(self.btn_remove, self.btn_move_up) Script.setTabOrder(self.btn_move_up, self.btn_move_down) Script.setTabOrder(self.btn_move_down, self.list) Script.setTabOrder(self.list, self.compliance) Script.setTabOrder(self.compliance, self.resistance) Script.setTabOrder(self.resistance, self.respi_rate) Script.setTabOrder(self.respi_rate, self.i_pmus) Script.setTabOrder(self.i_pmus, self.i_pmus_inc) Script.setTabOrder(self.i_pmus_inc, self.i_pmus_hld) Script.setTabOrder(self.i_pmus_hld, self.i_pmus_rel) Script.setTabOrder(self.i_pmus_rel, self.e_pmus) Script.setTabOrder(self.e_pmus, self.e_pmus_inc) Script.setTabOrder(self.e_pmus_inc, self.e_pmus_hld) Script.setTabOrder(self.e_pmus_hld, self.e_pmus_rel) Script.setTabOrder(self.e_pmus_rel, self.crf) Script.setTabOrder(self.crf, self.repetitions)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Author : 影子 # @Time : 2020-10-25 18:25 # @Software: PyCharm # @File : PySide2_01.py # 用户输入一段文本包含:员工姓名,薪资,年龄。把薪资在 2万 以上、以下的人员名单分别打印出来 import os from PySide2.QtWidgets import QApplication, QMainWindow, QPushButton, QPlainTextEdit # 增加环境变量 # https://blog.csdn.net/liuzhuchen/article/details/101348454?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-5.add_param_isCf&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-5.add_param_isCf # envpath = r'D:\ProgramData\Anaconda3\Lib\site-packages\PySide2\plugins\platforms' # os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = envpath app = QApplication([]) # 初始化操作提供整个图形界面程序的底层管理功能:初始化、程序入口参数的处理,用户事件等 window = QMainWindow() window.resize(500, 400) window.move(300, 310) window.setWindowTitle("薪资统计") textEdit = QPlainTextEdit(window) textEdit.setPlaceholderText("请输入薪资表") textEdit.move(10, 25) textEdit.resize(300, 350) button = QPushButton("统计", window) button.move(380, 80) window.show() app.exec_()
class MainWindow(QMainWindow): def __init__(self, screen_width, screen_height): self.screen_width = screen_width self.screen_height = screen_height self.screen_ratio = screen_width / 3840 self.half_screen_ratio = 0.45 + self.screen_ratio / 2 self.production_speed_ratio = 1 self.window = QMainWindow() self.window.resize(self.screen_width, self.screen_height) self.window.setWindowTitle('戴森球计划产量计算器 ver.0.1') self.grid_width = 75 * self.screen_ratio self.grid_height = 50 * self.screen_ratio self.init_bias = 50 * self.screen_ratio self.interval = 0 * self.screen_ratio self.box_width = self.grid_width * 4 + self.interval + 5 * self.screen_ratio self.box_height = self.grid_height * 2 + self.init_bias + 5 * self.screen_ratio # Subtitle: app name - author self.subtitle_font_size = 50 * self.screen_ratio if self.screen_ratio > 0.7: self.subtitle_font_size = 50 * self.screen_ratio / 1.5 subtitle = QLabel(self.window) subtitle.setText('戴森球计划 材料生产计算器 -- by 魂月') subtitle.setStyleSheet('QLabel {font: 75 ' + str(int(self.subtitle_font_size)) + 'pt "宋体";}') subtitle.move(1000 * self.screen_ratio, int(25 * self.screen_ratio)) subtitle.resize(1840 * self.screen_ratio, self.box_height * self.screen_ratio) # Bottom: 取整机器数量 self.button = QPushButton('取整机器数量', self.window) self.button.move(2840 * self.screen_ratio, int(25 * self.screen_ratio) + int(self.box_height / 3)) self.button.resize(400 * self.screen_ratio, int(self.box_height / 3)) self.button.setStyleSheet('QPushButton {font: ' + str(int(self.subtitle_font_size / 2)) + 'pt "宋体";}') self.button.clicked.connect(self.ceil_machine_number) self.ox = (self.screen_width - 12 * self.box_width) / 2 self.oy = self.box_height + 50 * self.screen_ratio self.font_size = 14 * self.half_screen_ratio self.line_edit_font_size = self.font_size * 0.9 * 0.75 self.element = source.element self.production = source.production self.supporter = source.support self.bi_material = source.bi_material self.sorted_element = source.sorted_element self.element_box = [[[None, None, None, None] for _ in range(len(self.element[0]))] for _ in range(len(self.element))] self.element_amount = [[[0, 0, 0, 0] for _ in range(len(self.element[0]))] for _ in range(len(self.element))] self.table_gen() for resource in self.sorted_element: i, j = self.get_idx(resource) for k in range(4): self.element_box[i][j][k].editingFinished.connect(self.update_element_amount) def table_gen(self): nrows = len(self.element) ncols = len(self.element[0]) for i in range(nrows): for j in range(ncols): foo = self.box_gen(self.ox + j * self.box_width, self.oy + i * self.box_height, self.element[i][j]) if len(foo) == 4: for k in range(4): self.element_box[i][j][k] = foo[k] def box_gen(self, x, y, resource=''): group_box = QGroupBox(self.window) group_box.move(x, y) group_box.resize(self.box_width, self.box_height) if resource == '': return [] group_box.setTitle('') group_box.setStyleSheet('QGroupBox { background-color: \ rgb(255, 255, 255); border: 3px solid rgb(122, 255, 100); } \ QGroupBox::title{font: 75 ' + str(100 * self.screen_ratio) + 'pt "宋体"; color: rgb(255, 0, 0)}') label_again = QLabel(group_box) label_again.setStyleSheet('QLabel {font: 75 ' + str(self.font_size) + 'pt "宋体"; color: rgb(255, 0, 0)}') label_again.setText(resource) label_again.move(int(self.grid_width * 0.7), 5 * self.screen_ratio) label_again.resize(int(self.grid_width * 3.3), self.init_bias - 5) product_label00 = QLabel(group_box) product_label00.setText('产量') product_label00.move(3, self.init_bias) product_label00.resize(self.grid_width, self.grid_height) product_label00.setStyleSheet('QLabel {font: 75 ' + str(self.font_size) + 'pt "宋体"}') product00 = QLineEdit(group_box) product00.setText('0') product00.move(self.grid_width, self.init_bias) product00.resize(self.grid_width, self.grid_height) product00.setEnabled(False) product00.setStyleSheet('QLineEdit {font: ' + str(self.line_edit_font_size) + 'pt "宋体"}') product_label10 = QLabel(group_box) product_label10.setText('额外') product_label10.move(3, self.grid_height + self.init_bias) product_label10.resize(self.grid_width, self.grid_height) product_label10.setStyleSheet('QLabel {font: 75 ' + str(self.font_size) + 'pt "宋体"}') product10 = QLineEdit(group_box) product10.setText('0') product10.move(self.grid_width, self.grid_height + self.init_bias) product10.resize(self.grid_width, self.grid_height) product10.setStyleSheet('QLineEdit {font: ' + str(self.line_edit_font_size) + 'pt "宋体"}') product_label01 = QLabel(group_box) product_label01.setText('机器') product_label01.move(self.grid_width * 2 + self.interval, self.init_bias) product_label01.resize(self.grid_width, self.grid_height) product_label01.setStyleSheet('QLabel {font: 75 ' + str(self.font_size) + 'pt "宋体"}') product01 = QLineEdit(group_box) product01.setText('0.0') product01.move(self.grid_width * 3 + self.interval, self.init_bias) product01.resize(self.grid_width, self.grid_height) product01.setStyleSheet('QLineEdit {font: ' + str(self.line_edit_font_size) + 'pt "宋体"}') product01.setEnabled(False) product_label11 = QLabel(group_box) product_label11.setText('已有') product_label11.move(self.grid_width * 2 + self.interval, self.grid_height + self.init_bias) product_label11.resize(self.grid_width, self.grid_height) product_label11.setStyleSheet('QLabel {font: 75 ' + str(self.font_size) + 'pt "宋体"}') product11 = QLineEdit(group_box) product11.setText('0') product11.move(self.grid_width * 3 + self.interval, self.grid_height + self.init_bias) product11.resize(self.grid_width, self.grid_height) product11.setStyleSheet('QLineEdit {font: ' + str(self.line_edit_font_size) + 'pt "宋体"}') if resource in self.supporter: product11.setEnabled(True) else: product11.setEnabled(False) return [product00, product01, product10, product11] # update the window by the values of the self.element_amount. def update_view(self, is_int=[True, False, True, True]): for resource in self.sorted_element: i, j = self.get_idx(resource) for k in range(4): amount = round(self.element_amount[i][j][k], 1) if is_int[k]: amount = int(self.element_amount[i][j][k]) self.element_box[i][j][k].setText(str(amount)) def get_idx(self, resource): idx = None if resource != '': for i in range(len(self.element)): for j in range(len(self.element[0])): if resource == self.element[i][j]: idx = [i, j] return idx def produce_resource(self, resource, increase_production_number): # Add resource amount in self.element_amount. idx = self.get_idx(resource) if not idx: exit(1) else: i, j = idx self.element_amount[i][j][0] += increase_production_number production_speed = self.production[resource][0][0] self.element_amount[i][j][1] += increase_production_number / production_speed # Start to product required amount of the resource. component = self.production[resource][1:] if not component: return for obj_resource in component: production_name = obj_resource[0] production_number = increase_production_number * obj_resource[1] self.produce_resource(production_name, production_number) def calculate_supporter(self): for supporter, properties in self.supporter.items(): i, j = self.get_idx(supporter) amount = self.element_amount[i][j][3] for production in properties: i, j = self.get_idx(production[0]) production_amount = self.element_amount[i][j][0] convert_amount_to_production_amount = amount * production[1] need_negative_production = convert_amount_to_production_amount - production_amount if need_negative_production > 0: self.produce_resource(production[0], -1 * production_amount) else: self.produce_resource(production[0], -1 * convert_amount_to_production_amount) def calculate_bi_raw_material(self): # Calculate the need of the bi_raw_materials. for material, properties in self.bi_material.items(): # production1 production1 = properties[0][0] i, j = self.get_idx(production1) production1_amount = properties[0][1] need_production1_amount = self.element_amount[i][j][0] need_material_amount1 = need_production1_amount / production1_amount # production2 production2 = properties[1][0] i, j = self.get_idx(production2) production2_amount = properties[1][1] need_production2_amount = self.element_amount[i][j][0] need_material_amount2 = need_production2_amount / production2_amount # Calculate the need of the material need_material_amount = max(need_material_amount1, need_material_amount2) i, j = self.get_idx(material) self.element_amount[i][j][0] = need_material_amount material_production_speed = self.production[material][0][0] self.element_amount[i][j][1] = need_material_amount / material_production_speed def update_element_amount(self, has_supporter=True): # Read all LineEdit boxes. for resource in self.sorted_element: i, j = self.get_idx(resource) for k in range(4): input_value = self.element_box[i][j][k].text() if k == 0 or k == 1 or input_value == '': self.element_amount[i][j][k] = 0.0 else: self.element_amount[i][j][k] = float(input_value) # Produce the required amount of all resources. for resource in self.sorted_element: i, j = self.get_idx(resource) production_amount = self.element_amount[i][j][2] - self.element_amount[i][j][3] if production_amount < 0: self.produce_resource(resource, 0) else: self.produce_resource(resource, production_amount) # Calculate the second product of the special supporter. if has_supporter: self.calculate_supporter() # Calculate the need of the bi_raw_material. self.calculate_bi_raw_material() # Update the view of the app. self.update_view() def ceil_machine_number(self): # Re-update element amount without considering supporter. self.update_element_amount(False) # Calculate supporter. supporter_stack = dict() for support, products in self.supporter.items(): i, j = self.get_idx(support) support_amount = self.element_amount[i][j][3] for product in products: product_name = product[0] product_amount = product[1] supporter_stack[product_name] = support_amount * product_amount # Ceil machine amount and produce the required amount of the resources. for resource in self.sorted_element: if resource not in self.supporter: i, j = self.get_idx(resource) production_speed = self.production[resource][0][0] if resource in supporter_stack: cur_resource_amount = self.element_amount[i][j][0] real_resource_amount = cur_resource_amount - supporter_stack[resource] if real_resource_amount > 0: cur_machine_amount = real_resource_amount / production_speed new_machine_amount = ceil(cur_machine_amount) else: new_machine_amount = 0 else: cur_machine_amount = self.element_amount[i][j][1] new_machine_amount = ceil(cur_machine_amount) cur_resource_amount = self.element_amount[i][j][0] incre_resource_amount = new_machine_amount * production_speed - cur_resource_amount self.produce_resource(resource, incre_resource_amount) self.element_amount[i][j][1] = new_machine_amount # Calculate the need of the bi_raw_material. self.calculate_bi_raw_material() # Update the view of the app. # Production amount is allowed to be float since its unit is piece/min. self.update_view([False, True, True, True]) def show(self): self.window.show()
series2 = QtCharts.QPieSeries() series2.setName("Renewables") series2.append("Wood fuels", 319663) series2.append("Hydro power", 45875) series2.append("Wind power", 1060) series3 = QtCharts.QPieSeries() series3.setName("Others") series3.append("Nuclear energy", 238789) series3.append("Import energy", 37802) series3.append("Other", 32441) donut_breakdown = DonutBreakdownChart() donut_breakdown.setAnimationOptions(QtCharts.QChart.AllAnimations) donut_breakdown.setTitle("Total consumption of energy in Finland 2010") donut_breakdown.legend().setAlignment(Qt.AlignRight) donut_breakdown.add_breakdown_series(series1, Qt.red) donut_breakdown.add_breakdown_series(series2, Qt.darkGreen) donut_breakdown.add_breakdown_series(series3, Qt.darkBlue) window = QMainWindow() chart_view = QtCharts.QChartView(donut_breakdown) chart_view.setRenderHint(QPainter.Antialiasing) window.setCentralWidget(chart_view) available_geometry = app.desktop().availableGeometry(window) size = available_geometry.height() * 0.75 window.resize(size, size * 0.8) window.show() sys.exit(app.exec_())
import sys import time from PySide2.QtCore import QUrl from PySide2.QtWidgets import QApplication from PySide2.QtWidgets import QMainWindow, QPushButton from PySide2.QtWebEngineWidgets import QWebEngineView from Util import MyTabWidget from Util import WebEngineView if __name__ == "__main__": # 启动应用 app = QApplication(sys.argv) # 生成窗口并配置 mainWindow = QMainWindow() mainWindow.resize(640, 480) mainWindow.setWindowTitle('测试应用') # 生成并配置tab组件 tabWidget = MyTabWidget() webView = WebEngineView(tabWidget) webView.load(QUrl("http://www.ifeng.com")) tabWidget.create_Tab([webView]) mainWindow.setCentralWidget(tabWidget) mainWindow.showMaximized() # 退出应用 sys.exit(app.exec_())
class Ui_Application(object): # ---------------------------------------------------------------------------------------------------------------- # def buySellStocks(self): self.inputWindow = inputDialog() portfolioName = self.inputWindow.gettext("Enter portfolio to update: ") if portfolioName is not None: stockTicker = self.inputWindow.gettext( "Enter the stock name to trade: ") if stockTicker is not None: tickerPrice = Main.getStockPrice(portfolioName, stockTicker) stockAmount = self.inputWindow.getint( f"The price of this stock is: ${tickerPrice}\nEnter how many shares to buy/sell: " ) if stockAmount is not None: Main.buySellStocks(portfolioName, stockTicker, stockAmount, tickerPrice) # ---------------------------------------------------------------------------------------------------------------- # def createPortfolioWindow(self): self.inputWindow = inputDialog() portfolioName = self.inputWindow.gettext() if portfolioName is not None: createPortfolio(portfolioName) return portfolioName # ---------------------------------------------------------------------------------------------------------------- # def viewPortfolioWindow(self): self.inputWindow = inputDialog() portfolioName = self.inputWindow.gettext() if portfolioName is not None: self.viewPortfolioWindow = QMainWindow() self.viewPortfolioWindow.resize(1000, 500) self.viewPortfolioWindow.setWindowTitle("View Portfolio") label = QtWidgets.QLabel(self.viewPortfolioWindow) label.move(50, 50) label.setText(Main.getPortfolioInfo(portfolioName)) label.setStyleSheet("QLabel {font: 22pt Courier}") label.adjustSize() self.viewPortfolioWindow.show() # ---------------------------------------------------------------------------------------------------------------- # def detailedStockInfo(self): self.inputWindow = inputDialog() stockTickers = self.inputWindow.gettext("Enter stock name: ") if stockTickers is not None: self.detailedStockInfo = QMainWindow() self.detailedStockInfo.resize(1000, 1000) self.detailedStockInfo.setWindowTitle("Detailed Stock Info") label = QtWidgets.QLabel(self.detailedStockInfo) label.move(50, 50) label.setText(Main.getAllStockData(stockTickers)) label.setStyleSheet("QLabel {font: 22pt Courier}") label.adjustSize() self.detailedStockInfo.show() # ---------------------------------------------------------------------------------------------------------------- # def plotStockHistory(self): self.inputWindow = inputDialog() tickerChoice = self.inputWindow.gettext("Enter stock to view: ") if tickerChoice is not None: numberOfDays = self.inputWindow.getint( "Enter number of days to view: ") if numberOfDays is not None: chartChoice = self.inputWindow.getItem("Choose chart type: ") print(chartChoice) self.wid = QtWidgets.QWidget() self.wid.setWindowTitle(f"{tickerChoice} Stock History") self.wid.resize(1000, 500) grid = QtWidgets.QGridLayout(self.wid) fig, ax = plt.subplots() data = GrabDataFromAPI.grabStockHistory( tickerChoice, numberOfDays) fig.patch.set_facecolor('silver') ax.set_facecolor('grey') if chartChoice != 'Candlestick': x = [ dates.datestr2num(data[i][0]) for i in range(numberOfDays) ] y = [float(data[i][4]) for i in range(numberOfDays)] ax.xaxis.set_major_formatter( dates.DateFormatter('%m/%d/%Y')) ax.xaxis.set_major_locator(ticker.MaxNLocator(10)) ax.set_xlabel('Date') ax.set_ylabel('Price in USD') ax.set_title(tickerChoice + ' Closing Price History') ax.grid(True) ax.plot(x, y, color='cyan') else: ohlc_data = [] # Open High Low Close Data for row in data: ohlc_data.append( (dates.datestr2num(row[0]), np.float64(row[1]), np.float64(row[2]), np.float64(row[3]), np.float64(row[4]))) candlestick_ohlc(ax, ohlc_data, width=float(0.5), colorup='cyan', colordown='orange', alpha=0.8) ax.xaxis.set_major_formatter( dates.DateFormatter('%m/%d/%Y')) ax.xaxis.set_major_locator(ticker.MaxNLocator(10)) plt.xticks(rotation=30) plt.grid() plt.xlabel('Date') plt.ylabel('Price in USD') plt.title(tickerChoice + ' Candlestick Chart') plt.tight_layout() canvas = FigureCanvas(fig) grid.addWidget(canvas, 0, 0) self.wid.show() # ------------------------------------------------------------------------------------------------------------ # def setupUi(self, Application): Application.setObjectName("Application") Application.resize(1000, 1000) self.gridLayout = QtWidgets.QGridLayout(Application) self.gridLayout.setObjectName("gridLayout") # Top Label self.label = QtWidgets.QLabel(Application) self.label.setAlignment(QtCore.Qt.AlignCenter) self.label.setObjectName("label") self.label.setStyleSheet( "QLabel {font: 30pt Elephant; color: #e8fcca}") self.gridLayout.addWidget(self.label, 0, 0, 1, 1) # First Button self.pushButton = QtWidgets.QPushButton(Application) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.pushButton.sizePolicy().hasHeightForWidth()) self.pushButton.setSizePolicy(sizePolicy) self.pushButton.setObjectName("pushButton") self.pushButton.setStyleSheet('QPushButton {font: 25pt Elephant}') self.gridLayout.addWidget(self.pushButton, 2, 0, 1, 1) # Second Button self.pushButton_2 = QtWidgets.QPushButton(Application) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.pushButton_2.sizePolicy().hasHeightForWidth()) self.pushButton_2.setSizePolicy(sizePolicy) self.pushButton_2.setObjectName("pushButton_2") self.pushButton_2.setStyleSheet('QPushButton {font: 25pt Elephant}') self.gridLayout.addWidget(self.pushButton_2, 3, 0, 1, 1) # Third Button self.pushButton_3 = QtWidgets.QPushButton(Application) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.pushButton_3.sizePolicy().hasHeightForWidth()) self.pushButton_3.setSizePolicy(sizePolicy) self.pushButton_3.setObjectName("pushButton_3") self.pushButton_3.setStyleSheet('QPushButton {font: 25pt Elephant}') self.gridLayout.addWidget(self.pushButton_3, 4, 0, 1, 1) # Fourth Button self.pushButton_4 = QtWidgets.QPushButton(Application) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.pushButton_4.sizePolicy().hasHeightForWidth()) self.pushButton_4.setSizePolicy(sizePolicy) self.pushButton_4.setObjectName("pushButton_4") self.pushButton_4.setStyleSheet('QPushButton {font: 25pt Elephant}') self.gridLayout.addWidget(self.pushButton_4, 5, 0, 1, 1) # Fifth Button self.pushButton_5 = QtWidgets.QPushButton(Application) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.pushButton_5.sizePolicy().hasHeightForWidth()) self.pushButton_5.setSizePolicy(sizePolicy) self.pushButton_5.setObjectName("pushButton_5") self.pushButton_5.setStyleSheet('QPushButton {font: 25pt Elephant}') self.gridLayout.addWidget(self.pushButton_5, 6, 0, 1, 1) # Lines self.line = QtWidgets.QFrame(Application) self.line.setFrameShape(QtWidgets.QFrame.HLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName("line") self.gridLayout.addWidget(self.line, 1, 0, 1, 1) self.line_2 = QtWidgets.QFrame(Application) self.line_2.setFrameShape(QtWidgets.QFrame.HLine) self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken) self.line_2.setObjectName("line") self.gridLayout.addWidget(self.line_2, 7, 0, 1, 1) self.retranslateUi(Application) QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL("clicked()"), self.buySellStocks) QtCore.QObject.connect(self.pushButton_2, QtCore.SIGNAL("clicked()"), self.viewPortfolioWindow) QtCore.QObject.connect(self.pushButton_3, QtCore.SIGNAL("clicked()"), self.createPortfolioWindow) QtCore.QObject.connect(self.pushButton_4, QtCore.SIGNAL("clicked()"), self.plotStockHistory) QtCore.QObject.connect(self.pushButton_5, QtCore.SIGNAL("clicked()"), self.detailedStockInfo) QtCore.QMetaObject.connectSlotsByName(Application) # ------------------------------------------------------------------------------------------------------------ # def retranslateUi(self, Application): Application.setWindowTitle( QtWidgets.QApplication.translate( "Application", "Virtual Stock Market Application", None, -1)) self.pushButton.setText( QtWidgets.QApplication.translate("Application", "Buy/Sell Stocks", None, -1)) self.pushButton_3.setText( QtWidgets.QApplication.translate("Application", "Create Portfolio", None, -1)) self.label.setText( QtWidgets.QApplication.translate( "Application", "Virtual Stock Market Application", None, -1)) self.pushButton_4.setText( QtWidgets.QApplication.translate("Application", "Plot Stock History", None, -1)) self.pushButton_2.setText( QtWidgets.QApplication.translate("Application", "View Portfolio", None, -1)) self.pushButton_5.setText( QtWidgets.QApplication.translate("Application", "View Detailed Stock Data", None, -1))
try: sock = socket(AF_INET, SOCK_STREAM) # 实例化socket sock.settimeout(int(time)) # 限制重连时间 sock.connect((ip, int(port))) # 对对应主机的对应端口发起连接 result = f'{port}端口开放' sock.close() # 关闭连接 except Exception as e: result = f'{port}端口关闭' win.append(result) #QMessageBox.about(window,'扫描结果',result) app = QApplication([]) window = QMainWindow() window.resize(500, 270) window.move(300, 300) window.setWindowTitle('端口扫描') textEdit1 = QPlainTextEdit(window) #textEdit1.setPlaceholderText("输入IP") textEdit1.move(10, 50) textEdit1.resize(200, 40) textEdit2 = QPlainTextEdit(window) #textEdit2.setPlaceholderText("输入端口") textEdit2.move(10, 130) textEdit2.resize(200, 40) textEdit3 = QPlainTextEdit(window) #textEdit3.setPlaceholderText("超时(毫秒)")
class ViolinGUI(QMainWindow): """Main Window Widget for ViolinGUI.""" style = { 'title': 'QLabel {font-size: 18pt; font-weight: 600}', 'header': 'QLabel {font-size: 12pt; font-weight: 520}', 'label': 'QLabel {font-size: 10pt}', 'button': 'QPushButton {font-size: 10pt}', 'run button': 'QPushButton {font-size: 18pt; font-weight: 600}', 'line edit': 'QLineEdit {font-size: 10pt}', 'checkbox': 'QCheckBox {font-size: 10pt}', 'drop down': 'QComboBox {font-size: 10pt}' } def __init__(self) -> None: """ViolinGUI Constructor. Defines all aspects of the GUI.""" # ## Setup section # Inherits from QMainWindow super().__init__() self.rootdir = get_project_root() # QMainWindow basic properties self.setWindowTitle("SCOUTS - Violins") self.setWindowIcon( QIcon( os.path.abspath(os.path.join(self.rootdir, 'src', 'scouts.ico')))) # Creates QWidget as QMainWindow's central widget self.page = QWidget(self) self.setCentralWidget(self.page) # Miscellaneous initialization values self.threadpool = QThreadPool() # Threadpool for workers self.population_df = None # DataFrame of whole population (raw data) self.summary_df = None # DataFrame indicating which SCOUTS output corresponds to which rule self.summary_path = None # path to all DataFrames generated by SCOUTS self.main_layout = QVBoxLayout(self.page) # Title section # Title self.title = QLabel(self.page) self.title.setText('SCOUTS - Violins') self.title.setStyleSheet(self.style['title']) self.title.adjustSize() self.main_layout.addWidget(self.title) # ## Input section # Input header self.input_header = QLabel(self.page) self.input_header.setText('Load data') self.input_header.setStyleSheet(self.style['header']) self.input_header.adjustSize() self.main_layout.addWidget(self.input_header) # Input/Output frame self.input_frame = QFrame(self.page) self.input_frame.setFrameShape(QFrame.StyledPanel) self.input_frame.setLayout(QFormLayout()) self.main_layout.addWidget(self.input_frame) # Raw data button self.input_button = QPushButton(self.page) self.input_button.setStyleSheet(self.style['button']) self.set_icon(self.input_button, 'x-office-spreadsheet') self.input_button.setObjectName('file') self.input_button.setText(' Load raw data file') self.input_button.setToolTip( 'Load raw data file (the file given to SCOUTS as the input file)') self.input_button.clicked.connect(self.get_path) # SCOUTS results button self.output_button = QPushButton(self.page) self.output_button.setStyleSheet(self.style['button']) self.set_icon(self.output_button, 'folder') self.output_button.setObjectName('folder') self.output_button.setText(' Load SCOUTS results') self.output_button.setToolTip( 'Load data from SCOUTS analysis ' '(the folder given to SCOUTS as the output folder)') self.output_button.clicked.connect(self.get_path) # Add widgets above to input frame Layout self.input_frame.layout().addRow(self.input_button) self.input_frame.layout().addRow(self.output_button) # ## Samples section # Samples header self.samples_header = QLabel(self.page) self.samples_header.setText('Select sample names') self.samples_header.setStyleSheet(self.style['header']) self.samples_header.adjustSize() self.main_layout.addWidget(self.samples_header) # Samples frame self.samples_frame = QFrame(self.page) self.samples_frame.setFrameShape(QFrame.StyledPanel) self.samples_frame.setLayout(QFormLayout()) self.main_layout.addWidget(self.samples_frame) # Samples label self.samples_label = QLabel(self.page) self.samples_label.setText( 'Write sample names delimited by semicolons below.\nEx: Control;Treat_01;Pac-03' ) self.samples_label.setStyleSheet(self.style['label']) # Sample names line edit self.sample_names = QLineEdit(self.page) self.sample_names.setStyleSheet(self.style['line edit']) # Add widgets above to samples frame Layout self.samples_frame.layout().addRow(self.samples_label) self.samples_frame.layout().addRow(self.sample_names) # ## Analysis section # Analysis header self.analysis_header = QLabel(self.page) self.analysis_header.setText('Plot parameters') self.analysis_header.setStyleSheet(self.style['header']) self.analysis_header.adjustSize() self.main_layout.addWidget(self.analysis_header) # Analysis frame self.analysis_frame = QFrame(self.page) self.analysis_frame.setFrameShape(QFrame.StyledPanel) self.analysis_frame.setLayout(QFormLayout()) self.main_layout.addWidget(self.analysis_frame) # Analysis labels self.analysis_label_01 = QLabel(self.page) self.analysis_label_01.setText('Compare') self.analysis_label_01.setStyleSheet(self.style['label']) self.analysis_label_02 = QLabel(self.page) self.analysis_label_02.setText('with') self.analysis_label_02.setStyleSheet(self.style['label']) self.analysis_label_03 = QLabel(self.page) self.analysis_label_03.setText('for marker') self.analysis_label_03.setStyleSheet(self.style['label']) self.analysis_label_04 = QLabel(self.page) self.analysis_label_04.setText('Outlier type') self.analysis_label_04.setStyleSheet(self.style['label']) # Analysis drop-down boxes self.drop_down_01 = QComboBox(self.page) self.drop_down_01.addItems([ 'whole population', 'non-outliers', 'top outliers', 'bottom outliers', 'none' ]) self.drop_down_01.setStyleSheet(self.style['drop down']) self.drop_down_01.setCurrentIndex(2) self.drop_down_02 = QComboBox(self.page) self.drop_down_02.addItems([ 'whole population', 'non-outliers', 'top outliers', 'bottom outliers', 'none' ]) self.drop_down_02.setStyleSheet(self.style['drop down']) self.drop_down_02.setCurrentIndex(0) self.drop_down_03 = QComboBox(self.page) self.drop_down_03.setStyleSheet(self.style['drop down']) self.drop_down_04 = QComboBox(self.page) self.drop_down_04.addItems(['OutS', 'OutR']) self.drop_down_04.setStyleSheet(self.style['drop down']) # Add widgets above to samples frame Layout self.analysis_frame.layout().addRow(self.analysis_label_01, self.drop_down_01) self.analysis_frame.layout().addRow(self.analysis_label_02, self.drop_down_02) self.analysis_frame.layout().addRow(self.analysis_label_03, self.drop_down_03) self.analysis_frame.layout().addRow(self.analysis_label_04, self.drop_down_04) self.legend_checkbox = QCheckBox(self.page) self.legend_checkbox.setText('Add legend to the plot') self.legend_checkbox.setStyleSheet(self.style['checkbox']) self.main_layout.addWidget(self.legend_checkbox) # Plot button (stand-alone) self.plot_button = QPushButton(self.page) self.set_icon(self.plot_button, 'system-run') self.plot_button.setText(' Plot') self.plot_button.setToolTip( 'Plot data after loading the input data and selecting parameters') self.plot_button.setStyleSheet(self.style['run button']) self.plot_button.setEnabled(False) self.plot_button.clicked.connect(self.run_plot) self.main_layout.addWidget(self.plot_button) # ## Secondary Window # This is used to plot the violins only self.secondary_window = QMainWindow(self) self.secondary_window.resize(720, 720) self.dynamic_canvas = DynamicCanvas(self.secondary_window, width=6, height=6, dpi=120) self.secondary_window.setCentralWidget(self.dynamic_canvas) self.secondary_window.addToolBar( NavBar(self.dynamic_canvas, self.secondary_window)) def set_icon(self, widget: QWidget, icon: str) -> None: """Associates an icon to a widget.""" i = QIcon() i.addPixmap( QPixmap( os.path.abspath( os.path.join(self.rootdir, 'src', 'default_icons', f'{icon}.svg')))) widget.setIcon(QIcon.fromTheme(icon, i)) def get_path(self) -> None: """Opens a dialog box and loads the corresponding data into memory, depending on the caller widget.""" options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog query = None func = None if self.sender().objectName() == 'file': query, _ = QFileDialog.getOpenFileName(self, "Select file", "", "All Files (*)", options=options) func = self.load_scouts_input_data elif self.sender().objectName() == 'folder': query = QFileDialog.getExistingDirectory(self, "Select Directory", options=options) func = self.load_scouts_results if query: self.load_data(query, func) def load_data(self, query: str, func: Callable) -> None: """Loads input data into memory, while displaying a loading message as a separate worker.""" worker = Worker(func=func, query=query) message = self.loading_message() worker.signals.started.connect(message.show) worker.signals.started.connect(self.page.setDisabled) worker.signals.error.connect(self.generic_error_message) worker.signals.error.connect(message.destroy) worker.signals.failed.connect(self.plot_button.setDisabled) worker.signals.success.connect(message.destroy) worker.signals.success.connect(self.enable_plot) worker.signals.finished.connect(self.page.setEnabled) self.threadpool.start(worker) def loading_message(self) -> QDialog: """Returns the message box to be displayed while the user waits for the input data to load.""" message = QDialog(self) message.setWindowTitle('Loading') message.resize(300, 50) label = QLabel('loading DataFrame into memory...', message) label.setStyleSheet(self.style['label']) label.adjustSize() label.setAlignment(Qt.AlignCenter) label.move(int((message.width() - label.width()) / 2), int((message.height() - label.height()) / 2)) return message def load_scouts_input_data(self, query: str) -> None: """Loads data for whole population prior to SCOUTS into memory (used for plotting the whole population).""" try: self.population_df = pd.read_excel(query, index_col=0) except XLRDError: self.population_df = pd.read_csv(query, index_col=0) self.drop_down_03.clear() self.drop_down_03.addItems(list(self.population_df.columns)) self.drop_down_03.setCurrentIndex(0) def load_scouts_results(self, query: str) -> None: """Loads the SCOUTS summary file into memory, in order to dynamically locate SCOUTS output files later when the user chooses which data to plot.""" self.summary_df = pd.read_excel(os.path.join(query, 'summary.xlsx'), index_col=None) self.summary_path = query def enable_plot(self) -> None: """Enables plot button if all necessary files are placed in memory.""" if isinstance(self.summary_df, pd.DataFrame) and isinstance( self.population_df, pd.DataFrame): self.plot_button.setEnabled(True) def run_plot(self) -> None: """Sets and starts the plot worker.""" worker = Worker(func=self.plot) worker.signals.error.connect(self.generic_error_message) worker.signals.success.connect(self.secondary_window.show) self.threadpool.start(worker) def plot(self) -> None: """Logic for plotting data based on user selection of populations, markers, etc.""" # Clear figure currently on plot self.dynamic_canvas.axes.cla() # Initialize values and get parameters from GUI columns = ['sample', 'marker', 'population', 'expression'] samples = self.parse_sample_names() pop_01 = self.drop_down_01.currentText() pop_02 = self.drop_down_02.currentText() pops_to_analyse = [pop_01, pop_02] marker = self.drop_down_03.currentText() cutoff_from_reference = True if self.drop_down_04.currentText( ) == 'OutR' else False violin_df = pd.DataFrame(columns=columns) # Start fetching data from files # Whole population for pop in pops_to_analyse: if pop == 'whole population': for partial_df in self.yield_violin_values( df=self.population_df, population='whole population', samples=samples, marker=marker, columns=columns): violin_df = violin_df.append(partial_df) # Other comparisons elif pop != 'none': for file_number in self.yield_selected_file_numbers( summary_df=self.summary_df, population=pop, cutoff_from_reference=cutoff_from_reference, marker=marker): df_path = os.path.join(self.summary_path, 'data', f'{"%04d" % file_number}.') try: sample_df = pd.read_excel(df_path + 'xlsx', index_col=0) except FileNotFoundError: sample_df = pd.read_csv(df_path + 'csv', index_col=0) if not sample_df.empty: for partial_df in self.yield_violin_values( df=sample_df, population=pop, samples=samples, marker=marker, columns=columns): violin_df = violin_df.append(partial_df) # Plot data pops_to_analyse = [p for p in pops_to_analyse if p != 'none'] violin_df = violin_df[violin_df['marker'] == marker] for pop in pops_to_analyse: pop_subset = violin_df.loc[violin_df['population'] == pop] for sample in samples: sample_subset = pop_subset.loc[pop_subset['sample'] == sample] sat = 1.0 - samples.index(sample) / (len(samples) + 1) self.dynamic_canvas.update_figure( subset_by_sample=sample_subset, pop=pop, sat=sat, samples=samples) # Draw plotted data on canvas if self.legend_checkbox.isChecked(): self.dynamic_canvas.add_legend() self.dynamic_canvas.axes.set_title( f'{marker} expression - {self.drop_down_04.currentText()}') self.dynamic_canvas.fig.canvas.draw() def parse_sample_names(self) -> List[str]: """Parse sample names from the QLineEdit Widget.""" return self.sample_names.text().split(';') def generic_error_message(self, error: Tuple[Exception, str]) -> None: """Error message box used to display any error message (including traceback) for any uncaught errors.""" name, trace = error QMessageBox.critical( self, 'An error occurred!', f"Error: {str(name)}\n\nfull traceback:\n{trace}") def closeEvent(self, event: QEvent) -> None: """Defines the message box for when the user wants to quit ViolinGUI.""" title = 'Quit Application' mes = "Are you sure you want to quit?" reply = QMessageBox.question(self, title, mes, QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.Yes: self.setEnabled(False) self.threadpool.waitForDone() event.accept() else: event.ignore() @staticmethod def yield_violin_values(df: pd.DataFrame, population: str, samples: List[str], marker: str, columns: List[str]) -> pd.DataFrame: """Returns a DataFrame from expression values, along with information of sample, marker and population. This DataFrame is appended to the violin plot DataFrame in order to simplify plotting the violins afterwards.""" for sample in samples: series = df.loc[df.index.str.contains(sample)].loc[:, marker] yield pd.DataFrame( { 'sample': sample, 'marker': marker, 'population': population, 'expression': series }, columns=columns) @staticmethod def yield_selected_file_numbers( summary_df: pd.DataFrame, population: str, cutoff_from_reference: bool, marker: str) -> Generator[pd.DataFrame, None, None]: """Yields file numbers from DataFrames resulting from SCOUTS analysis. DataFrames are yielded based on global values, i.e. the comparisons the user wants to perform.""" cutoff = 'sample' if cutoff_from_reference is True: cutoff = 'reference' for index, (file_number, cutoff_from, reference, outliers_for, category) in summary_df.iterrows(): if cutoff_from == cutoff and outliers_for == marker and category == population: yield file_number
from PySide2.QtWidgets import QApplication, QMainWindow, QPushButton, QPlainTextEdit, QScrollArea, QWidget, QVBoxLayout app = QApplication([]) window = QMainWindow() window.resize(800, 400) window.move(300, 310) window.setWindowTitle('薪资统计') textEdit = QPlainTextEdit(window) textEdit.setPlaceholderText("请输入薪资表") textEdit.move(10, 25) textEdit.resize(300, 350) def handleCalc(): print('统计按钮被点击了') button = QPushButton('统计', window) button.move(380, 80) button.clicked.connect(handleCalc) w = QWidget() window.setCentralWidget(w) topFiller = QWidget() topFiller.move(380, 2000) topFiller.setMinimumSize(400, 2000) #######设置滚动条的尺寸 for filename in range(20): MapButton = QPushButton(topFiller)
info = info.split('\n') for data in info: wage = re.search(r"\d{4,}", data) if wage: if int(wage.group()) <= 20000: name_list += data[0:4] + '\n' else: print('格式有误') QMessageBox.about(window, '统计结果', '薪资20000以下的有\n' f'{name_list}') if __name__ == '__main__': app = QApplication(sys.argv) window = QMainWindow() window.resize(600, 500) window.setWindowTitle('薪资统筹') # 输入面板 textEdit = QPlainTextEdit(window) textEdit.setPlaceholderText('请输入薪资表') textEdit.move(100, 50) textEdit.resize(400, 300) # 按钮 button = QPushButton('统计', window) button.move(250, 400) button.clicked.connect(handler_click) # 显示和退出 window.show()
series2 = QtCharts.QPieSeries() series2.setName("Renewables") series2.append("Wood fuels", 319663) series2.append("Hydro power", 45875) series2.append("Wind power", 1060) series3 = QtCharts.QPieSeries() series3.setName("Others") series3.append("Nuclear energy", 238789) series3.append("Import energy", 37802) series3.append("Other", 32441) donut_breakdown = DonutBreakdownChart() donut_breakdown.setAnimationOptions(QtCharts.QChart.AllAnimations) donut_breakdown.setTitle("Total consumption of energy in Finland 2010") donut_breakdown.legend().setAlignment(Qt.AlignRight) donut_breakdown.add_breakdown_series(series1, Qt.red) donut_breakdown.add_breakdown_series(series2, Qt.darkGreen) donut_breakdown.add_breakdown_series(series3, Qt.darkBlue) window = QMainWindow() chart_view = QtCharts.QChartView(donut_breakdown) chart_view.setRenderHint(QPainter.Antialiasing) window.setCentralWidget(chart_view) available_geometry = app.desktop().availableGeometry(window) size = available_geometry.height() * 0.75 window.resize(size, size * 0.8) window.show() sys.exit(app.exec_())