def moveScreenCenter(self): w = self.frameGeometry().width() h = self.frameGeometry().height() desktop = QDesktopWidget() screenW = desktop.screen().width() screenH = desktop.screen().height() self.setGeometry((screenW-w)/2, (screenH-h)/2, w, h)
from PySide2.QtWidgets import QApplication, QLabel, QWidget, QHBoxLayout, QVBoxLayout, QRadioButton, QGridLayout, QCheckBox, QSizePolicy, QButtonGroup, QDesktopWidget from PySide2.QtGui import QPixmap from functools import partial def _exit_on_esc(e): if e.key() == Qt.Key_Escape: QApplication.instance().quit() if __name__ == '__main__': app = QApplication([]) window = QWidget() wg = QGridLayout() rect = QDesktopWidget().screenGeometry() window.setFixedSize(rect.width(), rect.height()) window.showFullScreen() window.keyPressEvent = _exit_on_esc grid = QGridLayout() surv = QWidget() surv.setFixedSize(rect.width() // 2, rect.height() // 4) wg.addWidget(surv) # grid.setVerticalSpacing(0) # grid.setContentsMargins(0, 0, 0, 0) dv5_1 = QPixmap('dv5_1.png') grid.addWidget(QLabel('Reserved'), 0, 0) header = [ "1\nCompletely\ninappropriate", "2", "3", "4", "5", "6",
def move_top_middle(self): """ Moves the overlay to the top middle of the screen """ resolution = QDesktopWidget().screenGeometry() self.move((resolution.width() / 2) - (self.frameSize().width() / 2), 0)
def center(self): qRect = self.frameGeometry() centerPoint = QDesktopWidget().availableGeometry().center() qRect.moveCenter(centerPoint) self.move(qRect.topLeft())
def __init__(self): super().__init__() self.users = {} self.fps = 30 self.playing = False self.capturing = False self.capture_frame = None self.flag_recognize = False self.recognizing_frame = None self.recognized_faces = [] self.model = None self.setFixedSize(Config.width, Config.height) qr = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) self.setWindowIcon(QIcon('icons/icon.png')) self.setWindowTitle('人工智障人脸识别客户端') self.lbl_viewer = QLabel(self) self.lbl_viewer.setGeometry( QRect(10, 26, Config.width - 130, Config.height - 60)) self.lbl_viewer.setText('没有图像') font = QFont() font.setPointSize(20) self.lbl_viewer.setFont(font) self.lbl_viewer.setAlignment(Qt.AlignCenter) self.lbl_viewer.setFrameShape(QFrame.StyledPanel) self.btn_open_camera = QPushButton(self) self.btn_open_camera.setGeometry(QRect(Config.width - 110, 10, 100, 26)) self.btn_open_camera.setText('打开摄像头') self.btn_open_camera.clicked.connect(self.btn_click) self.btn_close_camera = QPushButton(self) self.btn_close_camera.setGeometry( QRect(Config.width - 110, 46, 100, 26)) self.btn_close_camera.setText('关闭摄像头') self.btn_close_camera.setDisabled(True) self.btn_close_camera.clicked.connect(self.btn_click) self.btn_open_video = QPushButton(self) self.btn_open_video.setGeometry(QRect(Config.width - 110, 82, 100, 26)) self.btn_open_video.setText('播放视频') self.btn_open_video.clicked.connect(self.btn_click) self.btn_close_video = QPushButton(self) self.btn_close_video.setGeometry( QRect(Config.width - 110, 118, 100, 26)) self.btn_close_video.setText('停止播放') self.btn_close_video.setDisabled(True) self.btn_close_video.clicked.connect(self.btn_click) self.cb_recognize = QCheckBox(self) self.cb_recognize.setText('启动识别') self.cb_recognize.setDisabled(True) self.cb_recognize.setGeometry(QRect(Config.width - 108, 154, 100, 26)) self.cb_recognize.clicked.connect(self.change_recognize) self.cb_show_match_result = QCheckBox(self) self.cb_show_match_result.setText('显示匹配度') self.cb_show_match_result.setDisabled(True) self.cb_show_match_result.setGeometry( QRect(Config.width - 108, 192, 100, 26)) if Config.show_match_result: self.cb_show_match_result.setChecked(True) self.cb_show_match_result.clicked.connect( self.change_show_match_result) lbl_threshold = QLabel(self) lbl_threshold.setText("识别精度") lbl_threshold.setGeometry(QRect(Config.width - 108, 228, 60, 26)) self.sb_threshold = QSpinBox(self) self.sb_threshold.setValue(Config.threshold) self.sb_threshold.setMinimum(30) self.sb_threshold.setMaximum(100) self.sb_threshold.valueChanged.connect(self.change_threshold) self.sb_threshold.setGeometry(QRect(Config.width - 45, 228, 40, 26)) self.btn_capture = QPushButton(self) self.btn_capture.setGeometry( QRect(Config.width - 110, Config.height - 200, 100, 26)) self.btn_capture.setText('截屏') self.btn_capture.setDisabled(True) self.btn_capture.clicked.connect(self.btn_click) self.lbl_capture_pic = QLabel(self) self.lbl_capture_pic.setGeometry( QRect(Config.width - 110, Config.height - 160, 100, 100)) self.lbl_capture_pic.setAlignment(Qt.AlignCenter) self.lbl_capture_pic.setFrameShape(QFrame.StyledPanel) self.btn_capture_save = QPushButton(self) self.btn_capture_save.setGeometry( QRect(Config.width - 110, Config.height - 60, 100, 26)) self.btn_capture_save.setText('保存截图') self.btn_capture_save.setDisabled(True) self.btn_capture_save.clicked.connect(self.btn_click) self.train_model()
def init(self): self.setWindowFlags( Qt.FramelessWindowHint | Qt.WindowCloseButtonHint) # default setting self.screen_num = 0 # default setting is main screen self.line = 0 ####### try: read_file = open("record.json", "r") dic_data = json.load(read_file) read_file.close() self.speed = dic_data['speed'] self.scale = dic_data['scale'] if self.scale == 20: self.checkBox_1.setCheckState(Qt.Checked) elif self.scale == 25: self.checkBox_2.setCheckState(Qt.Checked) elif self.scale == 30: self.checkBox_3.setCheckState(Qt.Checked) else: self.checkBox_2.setCheckState(Qt.Checked) self.transparent_slider.setValue(dic_data['transparent']) if dic_data['bold']: self.isBold.setChecked(Qt.Checked) except: self.checkBox_2.setCheckState(Qt.Checked) # for scale middle (中) self.speed = 50 # between 50 ~ 120 self.scale = 25 # 20 25 30 self.transparent_slider.setValue(100) self.Speed_Slider.setValue(self.speed) self.is_save = True self.Qrcode_msg = MyPopup() self.Qrcode_msg.hide() self.serverThread = serverThread(self.window()) self.serverThread.start() self.public_url = ngrok.connect(8888) self.Qrcode_msg.setLink(self.public_url) self.textEdit.setReadOnly(True) self.textEdit.insertHtml( "<p style='color:red;'>--------------------------Connected!--------------------------</p>") self.textEdit.append('') self.Msg_queue = queue.Queue() self.desktopWidget = QDesktopWidget(QApplication.desktop) self.screenRect = self.desktopWidget.screenGeometry(self.screen_num) screen = QDesktopWidget().screenGeometry(0) size = self.geometry() self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2) self.detect_screen() self.btn_detect_sreen.clicked.connect(self.detect_screen) # when the server gets the msg from the client, then pop up the danmaku # sig is the global signal # signal.sig.connect(self.popupMsg) signal.sig.connect(self.add_to_queue) self.onBindingUI()
def __centrar(self): qtRectangle = self.frameGeometry() centerPoint = QDesktopWidget().availableGeometry().center() qtRectangle.moveCenter(centerPoint) self.move(qtRectangle.topLeft())
def get_screenshot() -> QPixmap: app = QApplication.instance() screen = app.screens()[0] desḱtop_window = QDesktopWidget().winId() return screen.grabWindow(desḱtop_window)
def __center(self): geometry = self.frameGeometry() center = QDesktopWidget().availableGeometry().center() geometry.moveCenter(center) self.move(geometry.topLeft())
class DLPProjectorController(QLabel): print_text_signal = Signal(str) display_image_signal = Signal(QPixmap) def __init__(self, projector_setup="VisitechLRSWQ"): QLabel.__init__(self) base_path = Path(__file__).parent if projector_setup == 'VisitechLRSWQ': self.projector_instance = visitechDLP9000.VisitechDLP9000() elif projector_setup == 'VisitechLRS4KA': self.projector_instance = visitechLRS4KA.VisitechLRS4KA() if self.projector_instance is None: self.print_text_signal.emit( "Visitech LRS4KA not supported: selected Visitech DLP9000") self.projector_instance = visitechDLP9000.VisitechDLP9000() else: print("Error: an invalid projector was selected!") sys.exit(1) self.connected = False self.projector_instance.print_text_signal.connect( self.print_to_console) self.projector_instance.connection_status_signal.connect( self.set_connection_status) self.calibration_pattern = str( (base_path / "../resources/projection_pattern.png").resolve()) self.img = None self.horizontal_mirror = True self.vertical_mirror = False self.project_pattern_on = False self.setStyleSheet("QLabel { background-color : black}") self.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) self.show() self.desktops = QDesktopWidget() for d in range(self.desktops.screenCount()): print(self.desktops.screenGeometry(d)) if self.desktops.screenCount() > 1: self.projector_width = self.desktops.screenGeometry(1).width() self.projector_height = self.desktops.screenGeometry(1).height() self.move( self.desktops.screenGeometry(1).center() - self.rect().center()) self.showFullScreen() else: self.projector_width = 600 self.projector_height = 600 self.setFixedSize(self.projector_width, self.projector_height) self.threadpool = QThreadPool() @Slot() def init_projector(self): worker = Worker(self.projector_instance.init_projector) self.threadpool.start(worker) def stop_projector(self): if self.projector_instance.stop_projector(): self.connected = False def show_image(self, pattern, use_grayscale=False, alpha=0, beta=0, gamma=0): # if not self.connected: # self.print_text_signal.emit("Impossible to show image: projector is not connected!") # return loaded_image = QImage(pattern).convertToFormat( QImage.Format.Format_RGB32) values = loaded_image.bits() pixel_values = np.array(values).reshape(loaded_image.height(), loaded_image.width(), 4) if use_grayscale: thickness = DLPColorCalibrator.my_log_function( 1, alpha, beta, gamma) tmp, corrected_values = DLPColorCalibrator.my_color_correction( pixel_values, alpha, beta, gamma, thickness) corrected_values_tr = corrected_values.copy() corrected_image = QImage(corrected_values_tr, corrected_values_tr.shape[1], corrected_values_tr.shape[0], QImage.Format_RGB32) self.img = QPixmap(corrected_image) else: self.img = QPixmap(loaded_image) if self.horizontal_mirror: self.img = self.img.transformed(QTransform().scale(-1, 1)) if self.vertical_mirror: self.img = self.img.transformed(QTransform().scale(1, -1)) self.display_image_signal.emit(self.img) self.setPixmap(self.img) def clear_image(self): self.img = QPixmap('') self.display_image_signal.emit(self.img) self.setPixmap(self.img) def project_pattern(self): # if not self.connected: # self.print_text_signal.emit("Impossible to show image: projector is not connected!") # return if self.project_pattern_on: self.project_pattern_on = not self.project_pattern_on self.clear_image() else: self.project_pattern_on = not self.project_pattern_on self.show_image(self.calibration_pattern) def set_amplitude(self, amplitude): if DEBUG_MODE_ON: return True if not self.connected: self.print_text_signal.emit( "Impossible to set amplitude: projector is not connected!") return status = self.projector_instance.set_projector_amplitude(amplitude) return status @Slot(str) def print_to_console(self, text): self.print_text_signal.emit(text) @Slot(bool) def set_connection_status(self, status): self.connected = status
def move_to_center(self): screen = QDesktopWidget().screenGeometry() size = self.geometry() self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2)
def __init__(self, parent=None): try: super().__init__(parent) loader = QUiLoader() file = QFile(os.path.abspath("forms/MainWindow.ui")) file.open(QFile.ReadOnly) ui = loader.load(file, self) file.close() self.setLayout(ui.layout()) # Components self.clipboard = QGuiApplication.clipboard() self.desktop = QDesktopWidget() self.trans_label = self.findChild(QLabel, "transLabel") self.transparent_slider = self.findChild(QSlider, "transparentSlider") self.interface_frame = self.findChild(QFrame, "interfaceFrame") self.hide_button = self.findChild(QPushButton, "hideButton") self.enable_box = self.findChild(QCheckBox, "enableBox") self.on_top_box = self.findChild(QCheckBox, "onTopBox") self.clear_button = self.findChild(QPushButton, "clearButton") self.system_tray = SystemTray(self) self.currentScreen = 0 self.currentPosition = 0 self.is_on_top = True self.is_enable = True self.is_show_panel = True self.is_not_fixed = True self.is_grab = False self.is_follow_cursor = False # Instances self.config = config_parser.Configuration() self.trans_request = web_api.YouDaoRequest(self.config) self.translate_thread = threads.TranslatorThread( self.config, self.trans_request, self.get_clip_text, self) # initialize self._initialize() # self.trans_label.setAttribute(QtCore.Qt.WA_TransparentForMouseEvents, True); # register QObject.connect(self.enable_box, SIGNAL("stateChanged(int)"), self, SLOT("_set_enabled(int)")) QObject.connect(self.on_top_box, SIGNAL("stateChanged(int)"), self, SLOT("_set_on_top(int)")) QObject.connect(self.translate_thread, SIGNAL("finished()"), self, SLOT("_translate()")) QObject.connect(self.transparent_slider, SIGNAL("valueChanged(int)"), self, SLOT("_set_transparent(int)")) QObject.connect(self.clipboard, SIGNAL("dataChanged()"), self, SLOT("translate()")) QObject.connect(self.desktop, SIGNAL("resized(int)"), self, SLOT("_set_geometry()")) QObject.connect(self.hide_button, SIGNAL("clicked()"), self, SLOT("hide_interface()")) except TranslatorException as e: err_box = QMessageBox(self.parent()) err_box.setText(str(e)) err_box.exec_() sys.exit(-1)
class MainWindow(QMainWindow): def __init__(self, parent=None): try: super().__init__(parent) loader = QUiLoader() file = QFile(os.path.abspath("forms/MainWindow.ui")) file.open(QFile.ReadOnly) ui = loader.load(file, self) file.close() self.setLayout(ui.layout()) # Components self.clipboard = QGuiApplication.clipboard() self.desktop = QDesktopWidget() self.trans_label = self.findChild(QLabel, "transLabel") self.transparent_slider = self.findChild(QSlider, "transparentSlider") self.interface_frame = self.findChild(QFrame, "interfaceFrame") self.hide_button = self.findChild(QPushButton, "hideButton") self.enable_box = self.findChild(QCheckBox, "enableBox") self.on_top_box = self.findChild(QCheckBox, "onTopBox") self.clear_button = self.findChild(QPushButton, "clearButton") self.system_tray = SystemTray(self) self.currentScreen = 0 self.currentPosition = 0 self.is_on_top = True self.is_enable = True self.is_show_panel = True self.is_not_fixed = True self.is_grab = False self.is_follow_cursor = False # Instances self.config = config_parser.Configuration() self.trans_request = web_api.YouDaoRequest(self.config) self.translate_thread = threads.TranslatorThread( self.config, self.trans_request, self.get_clip_text, self) # initialize self._initialize() # self.trans_label.setAttribute(QtCore.Qt.WA_TransparentForMouseEvents, True); # register QObject.connect(self.enable_box, SIGNAL("stateChanged(int)"), self, SLOT("_set_enabled(int)")) QObject.connect(self.on_top_box, SIGNAL("stateChanged(int)"), self, SLOT("_set_on_top(int)")) QObject.connect(self.translate_thread, SIGNAL("finished()"), self, SLOT("_translate()")) QObject.connect(self.transparent_slider, SIGNAL("valueChanged(int)"), self, SLOT("_set_transparent(int)")) QObject.connect(self.clipboard, SIGNAL("dataChanged()"), self, SLOT("translate()")) QObject.connect(self.desktop, SIGNAL("resized(int)"), self, SLOT("_set_geometry()")) QObject.connect(self.hide_button, SIGNAL("clicked()"), self, SLOT("hide_interface()")) except TranslatorException as e: err_box = QMessageBox(self.parent()) err_box.setText(str(e)) err_box.exec_() sys.exit(-1) def translate(self): assert isinstance(self.trans_label, QLabel) if not self.get_clip_text(): return self.trans_label.setText("Translating...") if self.translate_thread.isRunning(): self.translate_thread.exit(self.translate_thread.exec_()) self.translate_thread.start() if not self.is_follow_cursor: return if self.is_show_panel: return pos = QtGui.QCursor().pos() self.move(pos) self.check_screen() self.move(pos) def get_clip_text(self): text = self.clipboard.text() text = re.sub(r"[#]+ ", " ", text) text = re.sub(r"[ \t]+", " ", text) text = re.sub(r"\n\s*\n", "%linebreak", text) text = re.sub(r"[ \n]+", " ", text) text = re.sub(r"(%linebreak)+", "\n", text) return text def mousePressEvent(self, event: PySide2.QtGui.QMouseEvent): self.is_grab = True def mouseMoveEvent(self, event: PySide2.QtGui.QMouseEvent): if not self.is_grab: return self.check_screen() pos = event.screenPos().toPoint() if pos.x() < self.geometry().left(): self.move(self.pos() + QPoint(pos.x() - self.geometry().left(), 0)) elif pos.x() > self.geometry().right(): self.move(self.pos() + QPoint(pos.x() - self.geometry().right(), 0)) def check_screen(self): currentScreen = self.currentScreen for i in range(self.desktop.screenCount()): if self.desktop.screenGeometry(i).left() < self.pos().x() and\ self.pos().x() + self.geometry().width() < self.desktop.screenGeometry(i).right(): currentScreen = i break if currentScreen != self.currentScreen: self.currentScreen = currentScreen screen = self.desktop.screenGeometry(currentScreen) self.setGeometry(self.x(), screen.top(), self.width(), screen.height()) def mouseReleaseEvent(self, event: PySide2.QtGui.QMouseEvent): self.is_grab = False def move_from_cursor(self): screen = self.desktop.screenGeometry(self.currentScreen) while self.underMouse(): if self.geometry().left() < screen.left() + 100: self.currentPosition = 0 elif self.geometry().right() > screen.right() - 100: self.currentPosition = 1 if self.currentPosition == 0: self.move(self.pos() + QPoint(1, 0)) else: self.move(self.pos() + QPoint(-1, 0)) def enterEvent(self, event: PySide2.QtGui.QMouseEvent): if self.is_show_panel or not self.is_not_fixed: return threading.Thread(target=self.move_from_cursor).start() def closeEvent(self, event: PySide2.QtGui.QCloseEvent): sys.exit(0) def _initialize(self): self.setWindowFlags(QtCore.Qt.Tool | QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowStaysOnTopHint) self.setAttribute(QtCore.Qt.WA_TranslucentBackground, True) # self.trans_label.enterEvent = self.mouse_move_in self._set_geometry() self._set_transparent(self.transparent_slider.value()) self.set_on_top(True) self.set_enable(True) self.show_interface(False) self.show() def _set_geometry(self): screen = self.desktop.screenGeometry(self.currentScreen) self.setGeometry(screen.left(), screen.top(), max(500, screen.width() // 5), screen.height()) self.move(screen.right() - self.width() - 100, self.y()) def _translate(self): assert isinstance(self.trans_label, QLabel) text = self._get_translate() self.trans_label.setText(text) self.trans_label.setSelection(0, len(text)) def _get_translate(self): result = self.translate_thread.result if result is None: return "No result" return result def _set_transparent(self, value): self.setWindowOpacity(1 - value / 100) def _set_on_top(self, state): self.is_on_top = state self.hide() self.setWindowFlag(QtCore.Qt.WindowStaysOnTopHint, state) self.show() def set_on_top(self, state): self.on_top_box.setChecked(state) def _set_enabled(self, state): assert isinstance(self.enable_box, QCheckBox) self.is_enable = state self.clipboard.blockSignals(not state) def set_enable(self, state): self.enable_box.setChecked(state) def set_not_fix(self, state): self.is_not_fixed = state def show_interface(self, state): assert isinstance(self.interface_frame, QFrame) self.is_show_panel = state self.move(self.pos().x(), 0) if state: self.interface_frame.show() else: self.interface_frame.hide() def set_follow_cursor(self, state): self.is_follow_cursor = state def hide_interface(self): self.show_interface(False)
def __init__( self, parent=None, ): super().__init__(parent) # 调用父类构造函数,创建窗体 self.ui = Ui_MainWindow() # 创建UI对象 self.ui.setupUi(self) # 构造UI界面 self.setWindowTitle(bt) # 设置窗体标题 self.setWindowIcon(QIcon(tb)) # 设置窗体图标 # self.setStyleSheet("MainWindow{border-image:url(./python.jpg);}") #设置窗口背景图片 self.tab = {} # 空字典 global L db = self.connect_db() # 获取游标 self.cur = db.cursor(pymysql.cursors.DictCursor) # 使用字典类型输出 # 根据” ID 字段“排序,倒叙输出 人员信息 表中的数据。备注:asc是表示升序,desc表示降序。limit 1表示输出一条记录 sql_renyuan = "select * FROM 人员信息 WHERE 工号 = %s order by ID desc limit 1" rows = self.cur.execute(sql_renyuan, L[len(L) - 1]) rows = self.cur.fetchone() qiye = QLabel(bt) # 设置窗体标题 qiye.setMinimumWidth(150) gonghao = QLabel("工号:%s" % L[len(L) - 1]) gonghao.setMinimumWidth(120) xingming = QLabel("姓名:%s" % rows['姓名']) xingming.setMinimumWidth(120) bumen = QLabel("部门:%s" % rows['部门']) bumen.setMinimumWidth(120) zhiwei = QLabel("职位:%s" % rows['职位']) zhiwei.setMinimumWidth(120) curDateTime = QDateTime.currentDateTime() #提取系统当前日期时间 week = datetime.now().isocalendar()[1] #当前日期的三元组(年号,第几周,第几天) riqi0 = curDateTime.toString("yyyy年MM月dd日 dddd " + '%s周' % week) #日期与星期 riqi = QLabel(riqi0) self.ui.statusBar.addPermanentWidget( riqi) #addPermanentWidget为右侧,showMessage为左侧 self.ui.statusBar.addWidget(qiye) # 加到状态栏 self.ui.statusBar.addWidget(gonghao) self.ui.statusBar.addWidget(xingming) self.ui.statusBar.addWidget(bumen) self.ui.statusBar.addWidget(zhiwei) cur = db.cursor(pymysql.cursors.DictCursor) # 1.控件的上面的小tab变成透明 # 2.选项卡部件:窗格{ 边框:1px纯灰;顶部:-1px;背景:透明;} # 3.突出选中的部分(改变颜色) # 4.设置QTabBar删除按钮图标和位置 # 4.设置QTabBar删除按钮图标(点击前) # 4.设置QTabBar删除按钮图标(点击时) str = "QTabBar::tab{background-color:rbg(255,255,255,0);}" + \ "QTabWidget:pane{border: 0.5px solid grey; top: -1px;background: transparent;}" + \ "QTabBar::tab:selected{color:blue;background-color:rbg(255,255,255);} " + \ "QTabBar::close-button{image: url(ICO/240.png);subcontrol-postion:left}" + \ "QTabBar::close-button:hover{image:url(ICO/301.png);subcontrol-postion:left}" + \ "QTabBar::close-button:pressed{image:url(ICO/302.png);subcontrol-postion:left}" self.ui.ZhuCaiDan.setStyleSheet(str) # 使用父级构造一个空的日期编辑器。日期设置为date。 sty = "QDateEdit :: QDateEdit(const QDate&date,QWidget * parent = nullptr)" self.ui.xmxx_Q_riqi.setStyleSheet(sty) self.ui.ZhuCaiDan.setCurrentIndex(0) # 显示第一个选项卡 self.ui.ZhuCaiDan.setTabsClosable(True) # 所有选项加上关闭按钮 self.ui.ZhuCaiDan.tabBar().setTabButton(0, QTabBar.RightSide, None) # 第一项去掉关闭按钮 # self.ui.ZhuCaiDan.tabBar().setTabButton(1, QTabBar.RightSide, None) # # 第二项去掉关闭按钮 u = self.ui.ZhuCaiDan.count() # 获取选项卡数量 # 删除多余选项卡 while u > 0: self.ui.ZhuCaiDan.removeTab(u) u = u - 1 self.ui.ZhuCaiDan.tabCloseRequested.connect( self.close_tab) # ZhuCaiDan(页)关闭函数取消 # 窗体居中设置 deskSize = QDesktopWidget().screenGeometry() # 获取桌面窗体参数 windowSize = self.geometry() # 获取窗体本身参数 self.move((deskSize.width() - windowSize.width()) / 2, (deskSize.height() - windowSize.height()) / 2 - 30) # 居中设置 # # self.LineEdit_Date() # self.ryxx_Q_riqi = QAction(self.ui.ryxx_Q_riqi) # self.ryxx_J_riqi = QAction(self.ui.ryxx_J_riqi) # self.renyuanxinxi_Q = QCalendarWidget(self.ui.renyuanxinxi) # self.renyuanxinxi_Q.setObjectName('renyuanxinxi_Q') # self.renyuanxinxi_J = QCalendarWidget(self.ui.renyuanxinxi) # self.renyuanxinxi_J.setObjectName('renyuanxinxi_J') # self.riqikuangxuanxiang(self.ui.ryxx_Q_riqi, self.ryxx_Q_riqi,self.renyuanxinxi_Q,self.renyuanxinxi_QQ,self.renyuanxinxi_QQ_showDate) # 创建日历控件 # self.riqikuangxuanxiang(self.ui.ryxx_J_riqi, self.ryxx_J_riqi,self.renyuanxinxi_J,self.renyuanxinxi_JJ,self.renyuanxinxi_JJ_showDate) # # self.renyuanxinxi_Q.installEventFilter(self) # self.renyuanxinxi_J.installEventFilter(self) # self.ui.xmxx_Q_riqi.setSpecialValueText(" ") #设置QDateEdit 可清空 # self.ui.xmxx_J_riqi.setSpecialValueText(" ") #设置QDateEdit 可清空 # self.ui.xmxx_J_riqi.setDate(QDate.currentDate()) # self.ui.xmxx_Q_riqi.setDate('0000/01/01') DateTimeEdit(self.ui.xmxx_Q_riqi) DateTimeEdit(self.ui.xmxx_J_riqi)
def center_window(self): screen = QDesktopWidget().screenGeometry() widget = self.geometry() Dx = screen.width() - widget.width() Dy = screen.height() - widget.height() self.move(Dx / 2, Dy / 2)
def __init__(self, widget): QMainWindow.__init__(self) self.setWindowTitle("Backend Discord GUI") grad = QPalette() gradient = QConicalGradient(QPointF(700, -10), 195) gradient.setColorAt(0.0, QColor(30, 30, 30)) gradient.setColorAt(0.5, QColor(50, 50, 50)) gradient.setColorAt(0.97, QColor(50, 13, 150)) gradient.setColorAt(1.0, QColor(106, 13, 173)) gradient.setSpread(QGradient.RepeatSpread) grad.setBrush(QPalette.Window, QBrush(gradient)) self.setPalette(grad) # Status Bar self.statusbar = self.statusBar() self.statusbar.showMessage("Preparing Window...") qtRectangle = self.frameGeometry() centerPoint = QDesktopWidget().availableGeometry().center() qtRectangle.moveCenter(centerPoint) self.move(qtRectangle.topLeft()) # Menu self.menu = self.menuBar() file_menu = self.menu.addMenu("File") new_bot_proj = QAction("New Bot Project", self) new_bot_proj.setShortcut("Ctrl+P") new_bot_proj.setStatusTip('Create a new Bot') new_bot_proj.triggered.connect(self.do_nothing) new_bot_file = QAction("New Bot File", self) new_bot_file.setShortcut("Ctrl+N") new_bot_file.setStatusTip('Create a new Command file') new_bot_file.triggered.connect(self.do_nothing) new_int_play = QAction("New Interactive Playground", self) new_int_play.setStatusTip('Create a Test App') new_int_play.triggered.connect(self.do_nothing) open_bot_proj = QAction("Open Bot Project", self) open_bot_proj.setShortcut("Ctrl+O") open_bot_proj.setStatusTip('Open a Bot Project') open_bot_proj.triggered.connect(self.do_nothing) open_bot_file = QAction("Open Bot File", self) open_bot_file.setStatusTip('Open a Command file') open_bot_file.triggered.connect(self.do_nothing) open_bot_iplay = QAction("Open Interactive Playground", self) open_bot_iplay.setStatusTip('Open a Test App') open_bot_iplay.triggered.connect(self.do_nothing) add_bot_file = QAction("Add Bot File", self) add_bot_file.setStatusTip('Add existing Command file') add_bot_file.triggered.connect(self.do_nothing) save_bot_proj = QAction("Save Bot Project", self) save_bot_proj.setStatusTip('Save a Bot Project') save_bot_proj.triggered.connect(self.do_nothing) save_bot_file = QAction("Save Bot File", self) save_bot_file.setStatusTip('Save a Command file') save_bot_file.triggered.connect(self.do_nothing) save_all = QAction("Save All", self) save_all.setShortcut("Ctrl+S") save_all.triggered.connect(self.do_nothing) close_editor = QAction("Close Editor", self) close_editor.setStatusTip('Close the editor only') close_editor.triggered.connect(self.do_nothing) close_workspace = QAction("Close Workspace", self) close_workspace.setShortcut("Ctrl+Q") close_workspace.setStatusTip('Close everything') close_workspace.triggered.connect(self.do_nothing) file_menu.addAction(new_bot_proj) file_menu.addAction(new_bot_file) file_menu.addAction(new_int_play) file_menu.addSeparator() file_menu.addAction(open_bot_proj) file_menu.addAction(open_bot_file) file_menu.addAction(open_bot_iplay) file_menu.addAction(add_bot_file) file_menu.addSeparator() file_menu.addAction(save_bot_proj) file_menu.addAction(save_bot_file) file_menu.addAction(save_all) file_menu.addSeparator() file_menu.addAction(close_editor) file_menu.addAction(close_workspace) edit_menu = self.menu.addMenu("Edit") find_file = QAction("Find File", self) find_file.setShortcut("Ctrl+F") find_file.setStatusTip("Find a Command") find_file.triggered.connect(self.do_nothing) file_settings = QAction("Open Find Settings", self) file_settings.setShortcut("Ctrl+Shift+S") file_settings.setStatusTip("Find a Command") file_settings.triggered.connect(self.do_nothing) toggle_file = QAction("Toggle File", self, checkable=True) toggle_file.setStatusTip("Toggles a Command file to be used") toggle_file.setChecked(True) toggle_file.triggered.connect(self.do_nothing) delete_file = QAction("Delete File", self) delete_file.setShortcut("Ctrl+Backspace") delete_file.setStatusTip("Delete a Command file") delete_file.triggered.connect(self.do_nothing) remove_file = QAction("Remove File", self) remove_file.setStatusTip("Removes a Command file from workspace") remove_file.triggered.connect(self.do_nothing) edit_menu.addAction(find_file) edit_menu.addAction(file_settings) edit_menu.addAction(toggle_file) edit_menu.addSeparator() edit_menu.addAction(delete_file) edit_menu.addAction(remove_file) viewMenu = self.menu.addMenu('View') command_palette = QAction("Command Palette", self) command_palette.setShortcut("Ctrl+Shift+P") command_palette.setStatusTip("Delete a Command file") command_palette.triggered.connect(self.do_nothing) open_view = QAction("Open View", self) open_view.setStatusTip("Delete a Command file") open_view.triggered.connect(self.do_nothing) appearance_settings = QAction("Appearance Settings", self) appearance_settings.setStatusTip("Delete a Command file") appearance_settings.triggered.connect(self.do_nothing) output_console = QAction("Output Console", self) output_console.setStatusTip("Delete a Command file") output_console.triggered.connect(self.do_nothing) debug_console = QAction("Debug Console", self) debug_console.setStatusTip("Delete a Command file") debug_console.triggered.connect(self.do_nothing) error_log = QAction("Error Log", self) error_log.setStatusTip("Delete a Command file") error_log.triggered.connect(self.do_nothing) view_logs = QAction("View All Logs", self) view_logs.setStatusTip("Delete a Command file") view_logs.triggered.connect(self.do_nothing) viewStatAct = QAction('View statusbar', self, checkable=True) viewStatAct.setStatusTip('View statusbar') viewStatAct.setChecked(True) viewStatAct.triggered.connect(self.toggleMenu) viewMenu.addAction(command_palette) viewMenu.addAction(open_view) viewMenu.addSeparator() viewMenu.addAction(appearance_settings) viewMenu.addSeparator() viewMenu.addAction(output_console) viewMenu.addAction(debug_console) viewMenu.addAction(error_log) viewMenu.addAction(view_logs) viewMenu.addSeparator() viewMenu.addAction(viewStatAct) runMenu = self.menu.addMenu('Run') start = QAction("Start", self) start.setShortcut("Ctrl+R") start.setStatusTip("Begin to start Command") start.triggered.connect(self.do_nothing) stop = QAction("Stop", self) stop.setShortcut("Ctrl+T") stop.setStatusTip("Terminate the Command") stop.triggered.connect(self.do_nothing) test_file = QAction("Test File", self) test_file.setStatusTip("Test the Command open on test server") test_file.triggered.connect(self.do_nothing) test_server = QAction("Test Server Connect", self) test_server.setShortcut("Ctrl+Shift+R") test_server.setStatusTip("Test server connection") test_server.triggered.connect(self.do_nothing) test_ping = QAction("Test Activity Ping", self) test_ping.setStatusTip("Test Bot API connection") test_ping.triggered.connect(self.do_nothing) test_commands = QAction("Test Ping Commands", self) test_commands.setStatusTip("Test all commands received") test_commands.triggered.connect(self.do_nothing) open_test_logs = QAction("View Test Logs", self) open_test_logs.setStatusTip("Open the logs for testing") open_test_logs.triggered.connect(self.do_nothing) runMenu.addAction(start) runMenu.addAction(stop) runMenu.addSeparator() runMenu.addAction(test_file) runMenu.addAction(test_server) runMenu.addAction(test_ping) runMenu.addAction(test_commands) runMenu.addAction(open_test_logs) terminalMenu = self.menu.addMenu('Terminal') start_bot = QAction("Start Bot", self) start_bot.setStatusTip("Begin to start Bot") start_bot.triggered.connect(self.do_nothing) stop_bot = QAction("Stop Bot", self) stop_bot.setStatusTip("Terminate the Bot") stop_bot.triggered.connect(self.do_nothing) terminal_logs = QAction("View Terminal Logs", self) terminal_logs.setStatusTip("Opens the Terminal logs") terminal_logs.triggered.connect(self.do_nothing) python_discord = QAction("Build Task as Python Discord", self) python_discord.setStatusTip( "Builds the Bot in Python Programming Language") python_discord.triggered.connect(self.do_nothing) javascript_discord = QAction("Build Task as Javascript Discord", self) javascript_discord.setStatusTip( "Builds the Bot in Javascript Programming Language") javascript_discord.triggered.connect(self.do_nothing) discordGUI_discord = QAction("Build Task as Discord-GUI", self) discordGUI_discord.setShortcut("Ctrl+Shift+W") discordGUI_discord.setStatusTip( "Builds the Bot in Discord-GUI Readable Language") discordGUI_discord.triggered.connect(self.do_nothing) build_errors = QAction("View Build Errors", self) build_errors.setStatusTip("Opens the Build Error Log") build_errors.triggered.connect(self.do_nothing) terminalMenu.addAction(start_bot) terminalMenu.addAction(stop_bot) terminalMenu.addSeparator() terminalMenu.addAction(terminal_logs) terminalMenu.addSeparator() terminalMenu.addAction(python_discord) terminalMenu.addAction(javascript_discord) terminalMenu.addAction(discordGUI_discord) terminalMenu.addAction(build_errors) windowMenu = self.menu.addMenu('Window') hide = QAction("Hide", self) hide.setStatusTip("Hide the Window") hide.triggered.connect(self.do_nothing) minimise = QAction("Minimise", self) minimise.setStatusTip("Minimise the Window") minimise.triggered.connect(self.do_nothing) maximise = QAction("Maximise", self) maximise.setStatusTip("Maximise the Window") maximise.triggered.connect(self.do_nothing) settings = QAction("Discord-GUI Settings", self) settings.setShortcut("Ctrl+L") settings.setStatusTip("Opens Discord-GUI's Settings") settings.triggered.connect(self.do_nothing) directory = QAction("Open Discord-GUI Directory", self) directory.setStatusTip("Goto the Discord-GUI Directory") directory.triggered.connect(self.do_nothing) windowMenu.addAction(hide) windowMenu.addAction(minimise) windowMenu.addAction(maximise) windowMenu.addSeparator() windowMenu.addAction(settings) windowMenu.addAction(directory) helpMenu = self.menu.addMenu('Help') welcome = QAction("Welcome", self) welcome.setStatusTip("Displays Welcome Message") welcome.triggered.connect(self.do_nothing) int_play = QAction("Interactive Playground", self) int_play.setStatusTip("Displays Interactive Playground Help") int_play.triggered.connect(self.do_nothing) docs = QAction("Documentation", self) docs.setStatusTip("Redirects to the Documentation of the app") docs.triggered.connect(self.do_nothing) keys_shorts = QAction("Keyboard Shortcuts", self) keys_shorts.setStatusTip("Displays Keyboard Shortcuts") keys_shorts.triggered.connect(self.do_nothing) report_issue = QAction("Report Issue", self) report_issue.setStatusTip("Redirects to Reporting an Issue") report_issue.triggered.connect(self.do_nothing) more_help = QAction("More Help", self) more_help.setStatusTip("Redirects to More Help Page") more_help.triggered.connect(self.do_nothing) helpMenu.addAction(welcome) helpMenu.addAction(int_play) helpMenu.addAction(docs) helpMenu.addSeparator() helpMenu.addAction(keys_shorts) helpMenu.addAction(report_issue) helpMenu.addAction(more_help) self.setCentralWidget(widget)
def center(self): self.setGeometry( QStyle.alignedRect(Qt.LeftToRight, Qt.AlignCenter, self.size(), QDesktopWidget().availableGeometry()))
class MainWindow(QMainWindow): def __init__(self, title="", icon="", object_name="MainWindow"): """ Template for main window that sets window size and placement, creates menu and status bars, and handles menu signals. :param title: str; Name to be displayed at the top of the window :param icon: str; file path to icon image file :param object_name: str; Name of main window object """ super().__init__() self.setObjectName(object_name) self.screen = QDesktopWidget().availableGeometry() self.setup_template(title) if icon: self.setWindowIcon(QIcon(icon)) self.menu_list = self.menu() self.menu_bar = QMenuBar(self) self.menu_heads = {} self.menu_items = {} self.setup_menu(object_name) self.menu_signals() self.status_bar = QStatusBar(self) self.setStatusBar(self.status_bar) def menu(self): """ Re-implement this function to define the window menu Lists all of the menu operations available in formats: {"Menu head": ["Menu item"]} {"Menu head 1": ["Menu item under 1"], "Menu head 2": ["Menu item under 2"]} {"Menu head": ["Menu item 1", "Menu item 2"]} {"Menu head": [["Menu item 1, ["Menu subitem 1", "Menu subitem 2"]], "Menu item 2"]} Notice that if subitems are desired, the format is to replace "Menu item" with ["Menu item", [subitems]] For a line between menu items, specify five dashes, e.g. {"Menu head": ["Menu item 1", "-----", "Menu item 2"]} """ menu = { "File": ["Close"], "Example": [ "Item", ["Item with subitems", ["Subitem 1", "Subitem 2"]], "-----", "Another item" ] } return menu def menu_operations(self, head, item, subitem=None): """ Re-implement this function to define what happens when each menu item is selected. :param head: str, menu head name as defined in self.menu() :param item: str, menu item name as defined in self.menu() :param head: str, menu subitem name, if applicable, as defined in self.menu() """ if head == "File": if item == "Close": self.close() def setup_template(self, title): """Sets up window size and title""" self.resize(self.screen.width() - 150, self.screen.height() - 150) # Sets window size 150 px from screen edge self.centre_on_screen() self.setWindowTitle(title) def centre_on_screen(self): """Centers the screen on the desktop""" centre = self.screen.center() x, y = centre.x() - self.size().width() / 2, centre.y( ) - self.size().height() / 2 x = 0 if x < 0 else x y = 0 if y < 0 else y self.move(x, y) def menu_signals(self): """Interprets the selection of a menu item or subitem and sends the appropriate signal via menu_connections""" for head, option in self.menu_items.items(): for item, widget in option.items(): if type( widget ) == list: # Open a side menu for any menu item with a list of subitems for subitem, subwidget in widget[1].items(): subwidget.triggered.connect( self.menu_connections(head, item, subitem)) else: widget.triggered.connect(self.menu_connections(head, item)) def menu_connections(self, head, item, subitem=None): """Redirects menu signals to the menu_operations function in the main window class. Leave this.""" return lambda: self.menu_operations(head, item, subitem) def setup_menu(self, object_name): """Builds a dictionary of menu item instances based on the menu items specified in menu method""" for head, items in self.menu_list.items(): self.menu_heads[head] = QMenu(self.menu_bar) self.menu_bar.addAction(self.menu_heads[head].menuAction()) self.menu_items[head] = {} for item in items: if type(item) == str: if item == "-----": self.menu_heads[head].addSeparator() else: self.menu_items[head][item] = QAction(self) self.menu_heads[head].addAction( self.menu_items[head][item]) elif type(item) == list: root = item[0] self.menu_items[head][root] = [] self.menu_items[head][root].append( QMenu(self.menu_heads[head])) self.menu_heads[head].addAction( self.menu_items[head][root][0].menuAction()) self.menu_items[head][root].append({}) for subitem in item[1]: self.menu_items[head][root][1][subitem] = QAction(self) self.menu_items[head][root][0].addAction( self.menu_items[head][root][1][subitem]) self.setMenuBar(self.menu_bar) _translate = QCoreApplication.translate for menu_head, widget in self.menu_heads.items(): widget.setTitle(_translate(object_name, menu_head)) for menu_head, menu_item in self.menu_items.items(): for item, widget in menu_item.items(): if type(widget) == list: widget[0].setTitle(_translate(object_name, item)) for subitem, subwidget in widget[1].items(): subwidget.setText(_translate(object_name, subitem)) else: if item != '-----': widget.setText(_translate(object_name, item))
max_silence_duration, start_offset, stop_offset) frame1.hide() frame2.show() if __name__ == "__main__": app = QApplication([]) # Creation of windows frame1 = GenericParamWindow() frame2 = SpecificParamWindow() frame1.setWindowTitle(SOFTWARE_NAME) frame2.setWindowTitle(SOFTWARE_NAME) # Moving frames to center of the screen bottom_right = QDesktopWidget().availableGeometry().bottomRight() x_max = bottom_right.x() y_max = bottom_right.y() frame1_width = min(frame1.width() + 0, x_max) frame1_height = min(frame1.height() + 200, y_max) # workaround because "height()" # seem to underestimate real height frame1.move((x_max - frame1_width) / 2, (y_max - frame1_height) / 2) frame2_width = min(frame2.width() + 0, x_max) frame2_height = min(frame2.height() + 400, y_max) # workaround because "height()" # seem to underestimate real height frame2.move((x_max - frame2_width) / 2, (y_max - frame2_height) / 2) # Connexions of frames frame1.nextWindow.connect(to_frame2)
class MyWindow(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): global signal super(MyWindow, self).__init__(parent) self.setupUi(self) self.window_list = [] self.timer = QTimer() self.timer.timeout.connect(self.pop_msg) self.init() self.timer.start(1500) # 2 seconds # self.popupMsg('hihi') # for testing the danmaku def change_transparent(self): self.setWindowOpacity(self.transparent_slider.value() / 100.0) def pop_msg(self): if not self.Msg_queue.empty(): tmp = self.Msg_queue.get() str = tmp.text color = tmp.color self.popupMsg(str, color) else: pass def add_to_queue(self, str, color): tmp = store_info(str, color) self.Msg_queue.put(tmp) # generating the danmaku (產生彈幕) def popupMsg(self, str, color): color = color # 以白色來顯示 bold = self self.textEdit.insertHtml("<p style='color:white;'>" + str + "</p>") self.textEdit.append('') w = scrollTextLabel(str, self.screenRect, self.scale, self.speed, self.line, color, self.isBold.isChecked()) self.window_list.append(w) if self.line == 0: self.line = 1 else: self.line = 0 w.show() def init(self): self.setWindowFlags( Qt.FramelessWindowHint | Qt.WindowCloseButtonHint) # default setting self.screen_num = 0 # default setting is main screen self.line = 0 ####### try: read_file = open("record.json", "r") dic_data = json.load(read_file) read_file.close() self.speed = dic_data['speed'] self.scale = dic_data['scale'] if self.scale == 20: self.checkBox_1.setCheckState(Qt.Checked) elif self.scale == 25: self.checkBox_2.setCheckState(Qt.Checked) elif self.scale == 30: self.checkBox_3.setCheckState(Qt.Checked) else: self.checkBox_2.setCheckState(Qt.Checked) self.transparent_slider.setValue(dic_data['transparent']) if dic_data['bold']: self.isBold.setChecked(Qt.Checked) except: self.checkBox_2.setCheckState(Qt.Checked) # for scale middle (中) self.speed = 50 # between 50 ~ 120 self.scale = 25 # 20 25 30 self.transparent_slider.setValue(100) self.Speed_Slider.setValue(self.speed) self.is_save = True self.Qrcode_msg = MyPopup() self.Qrcode_msg.hide() self.serverThread = serverThread(self.window()) self.serverThread.start() self.public_url = ngrok.connect(8888) self.Qrcode_msg.setLink(self.public_url) self.textEdit.setReadOnly(True) self.textEdit.insertHtml( "<p style='color:red;'>--------------------------Connected!--------------------------</p>") self.textEdit.append('') self.Msg_queue = queue.Queue() self.desktopWidget = QDesktopWidget(QApplication.desktop) self.screenRect = self.desktopWidget.screenGeometry(self.screen_num) screen = QDesktopWidget().screenGeometry(0) size = self.geometry() self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2) self.detect_screen() self.btn_detect_sreen.clicked.connect(self.detect_screen) # when the server gets the msg from the client, then pop up the danmaku # sig is the global signal # signal.sig.connect(self.popupMsg) signal.sig.connect(self.add_to_queue) self.onBindingUI() # self.setting_info() def save(self): if self.auto_save.isChecked(): self.is_save = True else: self.is_save = False def write(self): fp = open("record.json", "w") data = {'speed': self.speed, 'scale': self.scale, 'bold': self.isBold.isChecked(), 'transparent': self.transparent_slider.value()} ret = json.dumps(data) fp.write(ret) fp.close() def setting_info(self): print('speed ' + str(self.speed)) print ('scale ' + str(self.scale)) print ('bold ' + str(self.isBold.isChecked())) print ('transparent ' + str(self.transparent_slider.value())) def onBindingUI(self): ###init ui default setting and connect the signals with ui self.auto_save.setChecked(Qt.Checked) self.auto_save.clicked.connect(self.save) self.checkBox_1.stateChanged.connect(self.checkbox1_changed) self.checkBox_2.stateChanged.connect(self.checkbox2_changed) self.checkBox_3.stateChanged.connect(self.checkbox3_changed) self.Speed_Slider.valueChanged.connect(self.change_label_speed) self.Speed_Slider.setMaximum(120) self.Speed_Slider.setMinimum(50) self.btn_close.clicked.connect(self.close_the_app) self.transparent_slider.setTickInterval(100) self.transparent_slider.setMinimum(50) self.transparent_slider.setMaximum(100) self.transparent_slider.valueChanged.connect(self.change_transparent) # self.cbb_screen.currentIndexChanged.connect(self.set_screen_current_index) self.btn_qrcode.clicked.connect(self.qrcode_msg_show) self.btn_testing.clicked.connect(self.preview) ##美化 ui self.setWindowOpacity(self.transparent_slider.value() / 100.0) dark_stylesheet = qdarkstyle.load_stylesheet_pyside2() self.setStyleSheet(dark_stylesheet) self.setFixedSize(640, 600) def detect_screen(self): self.cbb_screen.clear() screen_count = self.desktopWidget.screenCount() for index in range(screen_count): self.cbb_screen.addItem('第' + str(index + 1) + "螢幕") def close_the_app(self): self.reply = QMessageBox.information(self, "User Interface", "Are you sure you want to quit?", QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if self.reply == QMessageBox.Yes: if self.is_save: self.write() ngrok.disconnect(self.public_url) self.serverThread.stop() self.Qrcode_msg.close() self.close() def set_screen_current_index(self): self.screen_num = self.cbb_screen.currentIndex() self.screenRect = self.desktopWidget.screenGeometry(self.screen_num) def preview(self): self.w = scrollTextLabel('測試', self.screenRect, self.scale, self.speed, 0, 'Blue', self.isBold.isChecked()) def qrcode_msg_show(self): size = self.Qrcode_msg.geometry() self.Qrcode_msg.move(self.screenRect.x() + (self.screenRect.width() - size.width()) / 2, self.screenRect.y() + (self.screenRect.height() - size.height()) / 2) self.Qrcode_msg.show() def checkbox1_changed(self): if self.checkBox_1.checkState() == Qt.Checked: self.checkBox_2.setCheckState(Qt.Unchecked) self.checkBox_3.setCheckState(Qt.Unchecked) self.set_checkbox_val() def checkbox2_changed(self): if self.checkBox_2.checkState() == Qt.Checked: self.checkBox_1.setCheckState(Qt.Unchecked) self.checkBox_3.setCheckState(Qt.Unchecked) self.set_checkbox_val() def checkbox3_changed(self): if self.checkBox_3.checkState() == Qt.Checked: self.checkBox_1.setCheckState(Qt.Unchecked) self.checkBox_2.setCheckState(Qt.Unchecked) self.set_checkbox_val() def set_checkbox_val(self): if self.checkBox_1.checkState() == Qt.Checked: self.scale = 30 # 大 if self.checkBox_2.checkState() == Qt.Checked: self.scale = 25 # 中 if self.checkBox_3.checkState() == Qt.Checked: self.scale = 20 # 小 def change_label_speed(self): self.speed = self.Speed_Slider.value() def mousePressEvent(self, event): if event.button() == Qt.LeftButton: self.m_drag = True self.m_DragPosition = event.globalPos() - self.pos() event.accept() self.setCursor(QCursor(Qt.OpenHandCursor)) def mouseMoveEvent(self, QMouseEvent): if Qt.LeftButton and self.m_drag: self.move(QMouseEvent.globalPos() - self.m_DragPosition) QMouseEvent.accept() def mouseReleaseEvent(self, QMouseEvent): self.m_drag = False self.setCursor(QCursor(Qt.ArrowCursor))
def __init__(self): super().__init__(None, Qt.WindowStaysOnTopHint) self.stdout = StreamOutput() self.stderr = StreamError() self.exec = StreamInput() self.frame = QFrame() self.setCentralWidget(self.frame) self.screen = QDesktopWidget().screenGeometry() self.setGeometry(self.screen) self.grid = QGridLayout() self.frame.setLayout(self.grid) self.map = SimulatedFieldMap() # -- setting splitters splitter_bottom = QSplitter(Qt.Horizontal) # STDIN, STDOUT splitter_main = QSplitter(Qt.Vertical) # Map ((STDIN,STDOUT), STDERR) # -------------- # -- top -- frame = QFrame() grid = QGridLayout() frame.setLayout(grid) splitter_main.addWidget(frame) grid.addWidget(self.map, 0, 0, 10, 1) slider_zoom = QSlider(Qt.Horizontal) slider_zoom.setMinimum(100) slider_zoom.setMaximum(1000) grid.addWidget(slider_zoom, 1, 1) sp = QSizePolicy() sp.setVerticalPolicy(QSizePolicy.Maximum) label = QLabel("Zoom") label.setSizePolicy(sp) grid.addWidget(label, 0, 1) zoom_label = QLabel("1") zoom_label.setSizePolicy(sp) slider_zoom.valueChanged.connect(lambda n: zoom_label.setText(str(n / 100))) grid.addWidget(zoom_label, 2, 1, Qt.AlignHCenter) splitter_main.addWidget(frame) # ------ # -- bottom left -- box = QVBoxLayout() frame = QFrame() frame.setLayout(box) box.addWidget(QLabel('Exec')) box.addWidget(self.exec) splitter_bottom.addWidget(frame) # ------- # -- bottom middle -- box = QVBoxLayout() frame = QFrame() frame.setLayout(box) splitter_bottom.addWidget(frame) box.addWidget(QLabel('Output')) box.addWidget(self.stdout) # ------- # -- bottom right -- box = QVBoxLayout() frame = QFrame() frame.setLayout(box) splitter_bottom.addWidget(frame) box.addWidget(QLabel('Error')) box.addWidget(self.stderr) # ------- splitter_main.addWidget(splitter_bottom) self.grid.addWidget(splitter_main, 0, 0) splitter_main.setSizes((self.screen.height() * 0.6, self.screen.height() * 0.4)) splitter_bottom.setSizes((self.map.width / 2, self.map.width / 2, self.stderr.sizeHint().width()))
def centering_window(self): center=self.frameGeometry() center_point=QDesktopWidget().availableGeometry().center() center.moveCenter(center_point) self.move(center.topLeft())
def __init__(self): QWidget.__init__(self) self.theme = 2 screen = QDesktopWidget() logging.info("screen size:" + str(screen.width()) + "," + str(screen.height())) self.m_width = screen.height() / 2 self.m_height = screen.height() / 2 self.resize(self.m_width, self.m_height) # self.setFixedSize(self.m_width, self.m_height) size = self.geometry() self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2) # delete title box self.setWindowFlags(Qt.FramelessWindowHint) # self.setAttribute(Qt.WA_TranslucentBackground) logging.info("login widget size:" + str(self.size())) self.bitmap = QBitmap(self.size()) painter = QPainter(self.bitmap) painter.fillRect(self.rect(), Qt.white) painter.setBrush(QColor(0, 0, 0)) painter.setRenderHint(QPainter.Antialiasing, True) painter.drawRoundedRect(self.rect(), 10, 10) self.setMask(self.bitmap) self.layout = QVBoxLayout(self) self.layout.setContentsMargins(0, 0, 0, self.m_height / 15) self.layout.setSpacing(self.m_height / 15) self.topframe = QFrame(self) self.topframe.setObjectName("topframe") if self.theme == 1: self.topframe.setStyleSheet( "#topframe{background-color:qlineargradient(" "spread:pad," "x1:0,y1:0,x2:1,y2:1," "stop:0 #5efce8," "stop:1 #736efe);}") elif self.theme == 2: self.topframe.setStyleSheet( "#topframe{background-color:qlineargradient(" "spread:pad," "x1:0,y1:0,x2:1,y2:0," "stop:0 #3a6186," "stop:1 #89253e);}") elif self.theme == 3: self.topframe.setStyleSheet( "#topframe{background-color:qlineargradient(" "spread:pad," "x1:0,y1:0,x2:0,y2:1," "stop:0 #19547b," "stop:1 #ffd89b);}") else: self.topframe.setStyleSheet( "#topframe{background-color:qlineargradient(" "spread:pad," "x1:0,y1:0,x2:1,y2:1," "stop:0 #ff8177," "stop:1 #b12a5b);}") self.layout.addWidget(self.topframe) # setup checkbox self.combobox = QComboBox(self) self.combobox.setObjectName("combobox") self.combobox.setFixedSize(self.m_width / 1.5, self.m_height / 10) self.combobox.setStyleSheet( "QComboBox{border: 2px solid gray;" "border-radius:5px;" "background-color:rgb(255, 255, 255);" "color:rgb(0, 0, 0);" "padding: 1px 20px;}" "QComboBox:drop-down{subcontrol-origin: padding;" "subcontrol-position: top right;" "width: 50px;border-left-style:solid;" "border-top-right-radius: 3px;" "border-bottom-right-radius: 3px;" "border-left: 2px solid gray;" "background-color: rgba(100, 25, 100, 0);}" "QComboBox:down-arrow{border-image:url(icon/arrow-1.png);}" "QComboBox:item:selected{background: rgb(232, 241, 250);color: rgb(2, 65, 132);}" "QStyledItemDelegate{border: 100px solid rgb(161,161,161);}") # self.combobox.move(200, 200) self.layout.addWidget(self.combobox, 0, Qt.AlignHCenter) # setup login button self.loginbtn = QPushButton("ENTER", self) self.loginbtn.setObjectName("loginbtn") self.loginbtn.setFixedSize(self.m_width / 1.5, self.m_height / 10) self.loginbtn.setContentsMargins(200, 20, 20, 20) self.loginbtn.clicked.connect(self.login_event) self.loginbtn.setStyleSheet( "QPushButton{border-radius:%dpx;" "background-color:#89253e;" "color:rgb(0, 0, 0);}" "QPushButton:hover{color:rgb(0, 255, 0);}" % (self.m_height / 20)) self.layout.addWidget(self.loginbtn, 0, Qt.AlignHCenter) # setup exit button self.exitbtn = QPushButton(self) # self.exitbtn.setText("Close") self.exitbtn.setToolTip("Close the widget") self.exitbtn.setFixedSize(40, 40) self.exitbtn.setIcon(QIcon("icon/close.png")) self.exitbtn.setIconSize(QSize(40, 40)) self.exitbtn.clicked.connect(self.exit_event) logging.info("topframesize:" + str(self.topframe.size())) self.exitbtn.move(self.width() - 40, 0) # self.exitbtn.setGeometry(self.topframe.width()-40, 0, 100, 40) self.exitbtn.setStyleSheet("background-color: #600") self.exitbtn.setStyleSheet("background-color: transparent") self.exitbtn.isEnabled() self.logoImage = QPixmap("icon/silabslogo.png") self.logo = self.logoImage.scaled(self.m_width / 5, self.m_height / 5, Qt.KeepAspectRatio, Qt.SmoothTransformation) self.logoLable = QLabel(self) self.logoLable.setObjectName("logoLable") self.logoLable.setAlignment(Qt.AlignCenter) self.logoLable.setPixmap(self.logo) self.logoLable.setFixedSize(self.m_width / 4, self.m_height / 4) # self.logo.setScaledContents(True) self.logoLable.setStyleSheet("#logoLable{border: 2px solid gray;" "border-radius:75px;" "background-color:rgb(100, 100, 100);" "color:rgb(0, 0, 0);}") self.logoLable.move(self.m_width / 2 - self.m_width / 8, self.m_height / 6) self.m_drag = False self.m_DragPosition = 0 self.MainWindow = 0
def initUI(self): frame = self.frameGeometry() centerPoint = QDesktopWidget().availableGeometry().center() frame.moveCenter(centerPoint) self.setGeometry(frame)
def get_geometry(self): return QDesktopWidget().availableGeometry(self)
def center(self): qr = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft())
def __init__(self, parent): super(HelpWindow, self).__init__(parent) # Window configurations self.setWindowTitle("Help") self.setGeometry(0, 0, HelpWindow.WINDOW_WIDTH, HelpWindow.WINDOW_HEIGHT) resolution = QDesktopWidget().screenGeometry() self.move((resolution.width() / 2) - (self.frameSize().width() / 2), (resolution.height() / 2) - (self.frameSize().height() / 2)) self.layout = QVBoxLayout(self) self.instructionsLabel = QLabel(self) self.instructionsLabel.setText("1. Adjust the camera to have a clear frontal view of your face.\n\n" "2. Click the start button to open the blink controller window.\n\n" "3. When a category scrolls into the selector, blink to open it.\n\n" "4. When a symbol scrolls into the selector, blink to input it.\n\n" "5. Continue steps 3 and 4 to form a sentence.\n\n" "6. Input the ENTER symbol to output the sentence as speech.\n\n" "7. When finished, click the stop button to close the blink controller.\n\n") self.instructionsLabel.setStyleSheet("font: 10pt") self.instructionsLabel.setAlignment(Qt.AlignTop | Qt.AlignLeft) self.faqLabel = QLabel(self) self.faqLabel.setText("<b>Why is there a face not detected warning when I use the blink controller?</b><br>" "The blink controller is having trouble detecting your face. " "Ensure that your webcam has a clear frontal view of your face and your room" " has sufficient lighting.<br><br>" "<b>How do I input text?</b><br>" "Select a category by blinking when it scrolls into the selector. " "Next, select the word/phrase/letter/number you want to input by blinking " "when it scrolls into the selector.<br><br>" "<b>How do I output speech?</b><br>" "After entering the text you want to say, select the FUNCTIONS category and select " "the ENTER symbol. Your text will be converted to speech.<br><br>" "<b>Why doesn't the application detect my blinks?</b><br>" "Ensure that you make full blinks lasting around 1 second.") self.faqLabel.setStyleSheet("font: 10pt") self.faqLabel.setWordWrap(True) self.faqLabel.setAlignment(Qt.AlignTop | Qt.AlignLeft) self.diagramPixmap = QtGui.QPixmap('resources/controller_diagram.png') self.diagramLabel = QLabel(self) self.diagramLabel.setPixmap(self.diagramPixmap) self.tabs = QTabWidget() self.tab1 = QWidget() self.tab2 = QWidget() self.tab3 = QWidget() self.tabs.setStyleSheet("font: 10pt") self.tabs.addTab(self.tab1, "Instructions For Use") self.tabs.addTab(self.tab2, "Frequently Asked Questions") self.tabs.addTab(self.tab3, "Blink Controller Diagram") self.tab1.layout = QVBoxLayout(self) self.tab1.layout.addWidget(self.instructionsLabel) self.tab1.setLayout(self.tab1.layout) self.tab2.layout = QVBoxLayout(self) self.tab2.layout.addWidget(self.faqLabel) self.tab2.setLayout(self.tab2.layout) self.tab3.layout = QVBoxLayout(self) self.tab3.layout.addWidget(self.diagramLabel) self.tab3.setLayout(self.tab3.layout) self.layout.addWidget(self.tabs) self.setLayout(self.layout) self.show()