コード例 #1
0
 def center_window(self):
     """Puts the field widget in the center of the main window."""
     self.setCentralWidget(self.field_ui)
     screen = QDesktopWidget().screenGeometry()
     size = self.geometry()
     self.move((screen.width() - size.width()) / 2,
               (screen.height() - size.height()) / 2)
コード例 #2
0
    def center(self):

        qr = self.frameGeometry()
        dw = QDesktopWidget()
        cp = dw.availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
コード例 #3
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.show_case_editor_signal.connect(self.show_case_editor, Qt.QueuedConnection)
        ui_dir_path = os.path.dirname(__file__)
        ui_file_path = os.path.join(ui_dir_path, 'mainwindow.ui')
        uic.loadUi(ui_file_path, self)
        # todo 更改窗体大小
        screen = QDesktopWidget().screenGeometry()
        self.resize(screen.width() / 2, screen.height() / 2)
        self.setMinimumSize(700, 350)
        self.setWindowTitle("uitest")
        self.move((screen.width() - self.width()) / 2, (screen.height() - self.height()) / 2)  # draw centered
        # Add tab "Case"
        case_manager_widget = CaseManagerWidget(self.show_case_editor_signal,
                                                self.tester)
        self.tabWidget.addTab(case_manager_widget, "Case")

        # Add tab "Run"
        case_run_widget = RunWidget(self.tester)
        self.tabWidget.addTab(case_run_widget, "Run")

        # Add tab "Report"
        case_report_widget = RunnerEventWidget()
        self.tabWidget.addTab(case_report_widget, "Report")

        # Add tab "Setting"
        case_setting_widget = SettingWidget()
        self.tabWidget.addTab(case_setting_widget, "Setting")

        self.refresh_case_data_signal.connect(case_manager_widget.refresh)
        self.message_box = QMessageBox()
        self.start_rpc_server()
        self.is_editor_close_cancel = False
コード例 #4
0
ファイル: yeahdoclist.py プロジェクト: lycying/seeking
        def __init__(self, parent=None, id="~"):
            """
            init
            """
            QWidget.__init__(self, parent)
            self.setupUi(self)

            # center this window
            screen = QDesktopWidget().screenGeometry()
            size = self.geometry()
            self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2)

            self.id = id
            self.flagBtn = RichFlagButton(self)
            self.linelayout.addWidget(self.flagBtn)
            self.desc = HtmlWYSIWYG()
            self.desc.setMinimumHeight(200)
            self.desclayout.addWidget(self.desc)

            if not self.id == "~":
                restore = YeahdocDatasSupply().bc_read1(self.id)
                self.flagBtn.setIcon(QIcon(getPath("iconDir", "yeahdoc/flag/%s" % str(restore['img']))))
                self.flagBtn.setText(restore['img'])
                self.title.setText(restore['title'])
                self.desc.fill(restore['desc'])

            QObject.connect(self.btn, SIGNAL("clicked (QAbstractButton *)"), self.__evt_btn_click)
コード例 #5
0
ファイル: shortcut.py プロジェクト: Prodesire/SimpleProjects
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.setWindowTitle('Shortcut')
        self.setWindowIcon(QIcon(os.path.join(os.curdir, 'icons/Shortcut.ico')))
        self.resize(300, 400)
        screenRect = QDesktopWidget().screenGeometry()
        self.move((screenRect.width() - self.width()) / 2, (screenRect.height() - self.height()) / 2)

        self.mainWidget = QWidget()
        self.gridlayout = QGridLayout()
        self.mainWidget.setLayout(self.gridlayout)
        self.setCentralWidget(self.mainWidget)

        try:
            configloader = ConfigLoader()
        except ConfigError as e:
            QMessageBox.about(self, 'Config Error', str(e))
            return

        for i, (title, action) in enumerate(configloader.config.items()):
            if 'open' in action[0]:
                button = OpenButton(title, action[1])
            elif 'edit' in action[0]:
                button = EditButton(title, action[1], action[2])
            elif 'cmd' in action[0]:
                button = CmdButton(title, action[1])
            else:
                continue

            colnum = 2
            self.gridlayout.addWidget(button, i / colnum, i % colnum)
コード例 #6
0
 def __init__(self, parent=None):
     QWidget.__init__(self, parent)
     self.setWindowTitle('Center')
     self.resize(250,150)
     screen = QDesktopWidget().screenGeometry()
     size=self.geometry()
     self.move((screen.width()-size.width())/2,(screen.height()-size.height())/2)
コード例 #7
0
ファイル: myterm_qt5.py プロジェクト: gamesun/MyTerm
 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)
コード例 #8
0
ファイル: main.py プロジェクト: harlandu/QtChordii
    def setup_geometry(self):
        geometries = settings.load_window_geometry()
        size = geometries[settings.key_size]
        if not size:
            size = QDesktopWidget().availableGeometry().size() * 4 / 5
        self.resize(size)

        is_full_screen = geometries[settings.key_is_full_screen]
        if is_full_screen:
            self.showFullScreen()

        splitter_sizes = geometries[settings.key_splitter_sizes]
        if not splitter_sizes:
            width = size.width()
            splitter_size = width * .2
            splitter_sizes = [splitter_size, (width - splitter_size) / 2, (width - splitter_size) / 2]
        self.ui.splitter.setSizes(splitter_sizes)

        pos = geometries[settings.key_pos]
        if not pos:
            center_point = QDesktopWidget().availableGeometry().center()
            geometry = self.frameGeometry()
            geometry.moveCenter(center_point)
            pos = geometry.topLeft()
        self.move(pos)
コード例 #9
0
ファイル: clustering.py プロジェクト: xsyann/clustering
 def fitImageToScreen(self, pixmap):
     """Fit pixmap to screen.
     """
     resolution = QDesktopWidget().screenGeometry()
     h, w = resolution.width(), resolution.height()
     w = min(pixmap.width(), w)
     h = min(pixmap.height(), h)
     return pixmap.scaled(QtCore.QSize(w, h), QtCore.Qt.KeepAspectRatio)
コード例 #10
0
ファイル: main.py プロジェクト: littlecodersh/EasierLife
 def init_ui(self):
     self.setWindowOpacity(.7)
     self.setWindowTitle('翻译小能手')
     self.resize(200, 100)
     screen = QDesktopWidget().screenGeometry()
     size = self.geometry()
     self.move((screen.width() - size.width())/2, (screen.height() - size.height())/2)
     self.textEdit = QTextEdit()
     self.setCentralWidget(self.textEdit)
コード例 #11
0
ファイル: window.py プロジェクト: wieloranski/experiNurse
    def center(self):
        """
        Centering main window relative to screen geometry
        """

        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width()-size.width())/2,
                  (screen.height()-size.height())/2)
コード例 #12
0
ファイル: thrawn.py プロジェクト: DubrulleKevin/Thrawn
    def init_ui(self):
        screen = QDesktopWidget().availableGeometry()
        self.resize(screen.width(), self.tconfig.height)
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.move(0, 0)

        command_label = CommandsLabel(self, self.tconfig)

        command_line_edit = CommandLineEdit(self, command_label,
                                            self.tconfig)
コード例 #13
0
ファイル: pluginhelp.py プロジェクト: lycying/seeking
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.setupUi(self)

        # center this window
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2)

        self.title.setText("<img width='48' src='%s'/><b>%s-%s</b>" % (getPath("iconDir", "logo.png"), Name, Version))
コード例 #14
0
ファイル: __main__.py プロジェクト: dpgeorge/puppy
 def autosize_window(self):
     screen = QDesktopWidget().screenGeometry()
     w = int(screen.width() * 0.8)
     h = int(screen.height() * 0.8)
     self.resize(w, h)
     size = self.geometry()
     self.move(
         (screen.width() - size.width()) / 2,
         (screen.height() - size.height()) / 2
     )
コード例 #15
0
 def display_window(self):
     #
     self.setGeometry(0, 0, 500, 500)
     resolution = QDesktopWidget().screenGeometry()
     self.move((resolution.width() / 2) - (self.frameSize().width() / 2),
               (resolution.height() / 2) - (self.frameSize().height() / 2))
     self.setWindowTitle('Eight Puzzle')
     self.setWindowIcon(QIcon('Images/eight_puzzle.ico'))
     self.setStyleSheet('background-color: #363B57;')
     self.show()
コード例 #16
0
ファイル: main.py プロジェクト: lordmauve/mu
 def autosize_window(self):
     """
     Makes the editor 80% of the width*height of the screen and centres it.
     """
     screen = QDesktopWidget().screenGeometry()
     w = int(screen.width() * 0.8)
     h = int(screen.height() * 0.8)
     self.resize(w, h)
     size = self.geometry()
     self.move((screen.width() - size.width()) / 2,
               (screen.height() - size.height()) / 2)
コード例 #17
0
    def init_ui(self):
        """
        init ui, include: resize window
        :return:
        """
        screen = QDesktopWidget().screenGeometry()
        self.resize(screen.width() / 2, screen.height() / 2)
        self.init_btn_icon()

        self.id_line_edit.hide()  # hide line_edit
        self.case_name_line_edit.setPlaceholderText("Case Name")
コード例 #18
0
ファイル: help.py プロジェクト: roderickmackenzie/gpvdm
	def move_window(self):
		shape=QDesktopWidget().screenGeometry()

		w=shape.width()
		h=shape.height()
		win_w=self.frameGeometry().width()
		win_h=self.frameGeometry().height()

		x=w-win_w
		y=50
		self.move(x,y)
コード例 #19
0
ファイル: progress.py プロジェクト: roderickmackenzie/gpvdm
    def start(self):
        shape = QDesktopWidget().screenGeometry()

        w = shape.width()
        h = shape.height()
        win_w = self.frameGeometry().width()
        win_h = self.frameGeometry().height()

        x = w - win_w
        y = 0
        self.move(x, y)
        self.show()
コード例 #20
0
ファイル: main.py プロジェクト: thesmartwon/OpenChess-Python
    def initUI(self):
        # Look and feel
        antiAliasedFont = QApplication.font()
        antiAliasedFont.setStyleStrategy(QFont.PreferAntialias)
        QApplication.setFont(antiAliasedFont)

        self.setWindowTitle('Open Chess')
        path = constants.RESOURCES_PATH + '/icon.png'
        self.setWindowIcon(QIcon(path))

        # Geometry
        """This will make the window the correct aspect ratio"""
        screenGeo = QDesktopWidget().availableGeometry()
        idealWidth = constants.IDEAL_RESOLUTION['width']
        idealHeight = constants.IDEAL_RESOLUTION['height']
        # TODO: maybe there is a good way to get this value?
        guessedFrame = 2
        titlebarHeight = QApplication.style().pixelMetric(
                            QStyle.PM_TitleBarHeight) + guessedFrame
        widthDisparity = screenGeo.width() - idealWidth
        heightDisparity = screenGeo.height() - idealHeight
        if widthDisparity < 0 and widthDisparity < heightDisparity:
            width = idealWidth + widthDisparity
            ratio = float(idealHeight) / idealWidth
            height = int(ratio * (idealWidth + widthDisparity))
            self.setGeometry(0, 0, width - guessedFrame * 2,
                             height - titlebarHeight)
        elif heightDisparity < 0 and heightDisparity < widthDisparity:
            ratio = float(idealWidth) / idealHeight
            width = int(ratio * (idealHeight + heightDisparity))
            height = idealHeight + heightDisparity
            self.setGeometry(0, 0, width - guessedFrame * 2,
                             height - titlebarHeight)
        else:
            self.setGeometry(0, 0, idealWidth, idealHeight)
        print("window geometry is", self.geometry())

        # Widget
        self.centralWidget = CentralWidget(self)
        self.setCentralWidget(self.centralWidget)

        self.createActions()
        self.createMenus()

        # Center the window on the desktop
        # TODO: Add option for setting startup xy and saving layout in general
        # qr = self.frameGeometry()
        # cp = QDesktopWidget().geometry().center()
        # qr.moveCenter(cp)
        frameGeo = self.geometry()
        frameGeo.setHeight(frameGeo.height() + titlebarHeight + guessedFrame)
        frameGeo.setWidth(frameGeo.width() + guessedFrame * 2)
        self.move(QDesktopWidget().screenGeometry().center() - frameGeo.center())
コード例 #21
0
ファイル: player.py プロジェクト: mandeepbhutani/Mosaic
def main():
    """Create an instance of the music player and use QApplication to show the GUI.

    QDesktopWidget() is used to move the application to the center of the user's screen.
    """
    application = QApplication(sys.argv)
    window = MusicPlayer()
    desktop = QDesktopWidget().availableGeometry()
    width = (desktop.width() - window.width()) / 2
    height = (desktop.height() - window.height()) / 2
    window.show()
    window.move(width, height)
    sys.exit(application.exec_())
コード例 #22
0
ファイル: visualize.py プロジェクト: aagnone3/audio_analysis
def init_gui():
    pg.setConfigOptions(antialias=True)
    app = QtGui.QApplication([])
    app = app.instance()

    win = pg.QtGui.QMainWindow()
    dims = QDesktopWidget().availableGeometry(win)
    win.setWindowTitle('Audio Visualization')
    cw = QtGui.QWidget()
    win.setCentralWidget(cw)
    layout = QtGui.QVBoxLayout()
    cw.setLayout(layout)
    win.resize(int(0.7 * dims.width()), int(0.7 * dims.height()))
    return app, win, layout
コード例 #23
0
ファイル: main.py プロジェクト: aq1/Hospital-Helper-2
    def _set_sys_attributes(self):
        """
        Set sys attributes like window titile.
        Disable OS-specific buttons.
        Remove borders.
        """

        self.setWindowFlags(Qt.FramelessWindowHint)

        self.setWindowTitle('Hospital Helper')
        dw = QDesktopWidget()
        w = min(1300, dw.geometry().size().width() * 0.75)
        self.setFixedSize(w, w * 0.6)
        qr = self.frameGeometry()
        cp = dw.availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
コード例 #24
0
    def __init__(self, parent):
        super(EditScreenshot, self).__init__(parent= parent)
        self.parent = parent
        self.painter = QPainter()
        orgSize = self.parent.screenPixmap.size()
        availableSize = QDesktopWidget().availableGeometry().size()
        print("imagesize: " + str(orgSize) + " availableSize: " + str(availableSize))
        if orgSize.width() > availableSize.width() or orgSize.height() > availableSize.height():
            image = self.parent.screenPixmap.scaled(availableSize, Qt.KeepAspectRatio, Qt.SmoothTransformation).toImage()
        else:
            image = self.parent.screenPixmap.toImage()

        self.imageHolder = ImageHolder(image)
        self.imageHolder.resize(image.size())
        self.imageHolder.setMinimumSize(image.size())
        self.imageHolder.show()

        mainLayout = QVBoxLayout()

        closeBtn = QPushButton("Close")
        closeBtn.clicked.connect(self.close)
        saveBtn = QPushButton("Save Changes")
        saveBtn.clicked.connect(self.saveChanges)

        scroll = QScrollArea()
        scroll.setWidgetResizable(True)
        scroll.setWidget(self.imageHolder)

        btnLayout = QHBoxLayout()
        btnLayout.addStretch()
        btnLayout.addWidget(saveBtn)
        btnLayout.addWidget(closeBtn)

        mainLayout.addLayout(btnLayout)
        mainLayout.addWidget(scroll)

        save = QShortcut(QKeySequence("Ctrl+s"), self)
        save.activated.connect(self.saveChanges)

        self.setLayout(mainLayout)
        self.resize(QDesktopWidget().availableGeometry().size())
        self.setWindowTitle("Edit Screenshot")
コード例 #25
0
ファイル: config.py プロジェクト: wkoot/imperialism-remake
 def check_resolution(self):
     logging.debug('[ENTER] check_resolution(), resolution=%s' % self.resolution)
     # check resolution min, max...
     w, h = parse_resolution(self.resolution)
     if w != -1 and h != -1:
         minw, minh = MINIMUM_RESOLUTION
         screen = QDesktopWidget().screenGeometry()
         maxw, maxh = screen.width(), screen.height()
         logging.debug('check_resolution() => current width=%d, current_height=%d, min width=%d, '
                       'min height=%d, max width=%d, max height=%d' % (w, h, minw, minh, maxw, maxh))
         if w < minw or h < minh:
             msg = 'Bad resolution (width must be superior to %d and height must be superior to %d) (current %d x %d)' % (
                 minw, minh, w, h)
             self.errors.append(msg)
             logging.error(msg)
         if w > maxw or h > maxh:
             msg = 'Bad resolution (width must be inferior to screen width resolution %d and height must be inferior to screen height resolution %d) (current %d x %d)' % (
                 maxw, maxh, w, h)
             self.errors.append(msg)
             logging.error(msg)
     logging.debug('[EXIT] check_resolution(), resolution=%s' % self.fullscreen)
コード例 #26
0
ファイル: add_case.py プロジェクト: IfengAutomation/uitester
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.dBCommandLineHelper = DBCommandLineHelper()
        ui_dir_path = os.path.dirname(__file__)
        ui_file_path = os.path.join(ui_dir_path, 'add_case.ui')
        uic.loadUi(ui_file_path, self)

        screen = QDesktopWidget().screenGeometry()
        self.resize(screen.width() / 5 * 2, screen.height() / 5 * 2)

        self.search_button = SearchButton()
        self.tag_names_line_edit = TagLineEdit("tag_names_line_edit", self.search_button)
        self.tag_names_line_edit_adapter()
        self.tag_list = None

        self.result_widget = RunnerTableWidget(self.dBCommandLineHelper.query_case_all(), [])
        self.result_table_layout.insertWidget(0, self.result_widget)

        self.message_box = QMessageBox()

        self.search_button.clicked.connect(self.search_event)
        self.selectcasebtn.clicked.connect(self.select_event)
        self.casecancelbtn.clicked.connect(self.close)
コード例 #27
0
	def set_window(self,window,name):
		global wlist
		for i in range(0,len(wlist)):
			if wlist[i].name==name:
				shape=QDesktopWidget().screenGeometry()

				desktop_w=shape.width()
				desktop_h=shape.height()

				w=window.width()
				h=window.height()

				x=int(wlist[i].x)
				y=int(wlist[i].y)
				if (x+w>desktop_w):
					x=0
					print("Reset with")
				if (y+h>desktop_h):
					y=0
					print("Reset height")

				window.move(x,y)
				break
コード例 #28
0
ファイル: tray_icon.py プロジェクト: ismlsmile/nimbus
class BackgroundToolBar(QToolBar):
    def __init__(self, *args, **kwargs):
        super(BackgroundToolBar, self).__init__(*args, **kwargs)
        self.setIconSize(QSize(22, 22))
        self.shownOnce = False
        self.desktopWidget = QDesktopWidget()
        self.setWindowFlags(Qt.FramelessWindowHint|Qt.WindowStaysOnTopHint)
    def halfScreenHeight(self):
        return int((self.desktopWidget.height()-self.height())/2)
    def halfScreenWidth(self):
        return int((self.desktopWidget.width()-self.width())/2)
    def show(self):
        super(BackgroundToolBar, self).show()
        if not self.shownOnce:
            self.move(self.desktopWidget.width()-self.width(), self.halfScreenHeight())
            self.shownOnce = True
    def mousePressEvent(self, ev):
        if ev.button() != Qt.LeftButton:
            return QToolBar.mousePressEvent(self, ev)
        else:
            if not QApplication.instance().keyboardModifiers() in (Qt.ControlModifier, Qt.ShiftModifier, Qt.AltModifier):
                QApplication.setOverrideCursor(Qt.SizeAllCursor)
            self.mouseX = ev.globalX()
            self.origX = self.x()
            self.mouseY = ev.globalY()
            self.origY = self.y()
    def mouseMoveEvent(self, ev):
        if self.mouseX and self.mouseY and not self.isMaximized():
            self.move(self.origX + ev.globalX() - self.mouseX,
self.origY + ev.globalY() - self.mouseY)
    def mouseReleaseEvent(self, ev):
        QApplication.restoreOverrideCursor()
        x = False
        y = False
        if self.x() + self.width() > self.desktopWidget.width():
            self.move(self.desktopWidget.width()-self.width(), self.y())
            x = True
        elif self.x() < 0:
            self.move(0, self.y())
            x = True
        if x and self.halfScreenHeight() - 64 <= self.y() <= self.halfScreenHeight() + 64:
                self.move(self.x(), self.halfScreenHeight())
        if self.y() < 0:
            self.move(self.x(), 0)
            y = True
        elif self.y() + self.height() > self.desktopWidget.height():
            self.move(self.x(), self.desktopWidget.height()-self.height())
            y = True
        if y and self.halfScreenWidth() - 64 <= self.x() <= self.halfScreenWidth() + 64:
            self.move(self.halfScreenWidth(), self.y())
        return QToolBar.mouseReleaseEvent(self, ev)
コード例 #29
0
ファイル: wallpaper.py プロジェクト: gimu/hitagi-reader.py
    def set_as_wallpaper(self, option):
        """Set current image as wallpaper."""

        # TODO: mac version, testing

        path = QStandardPaths.writableLocation(QStandardPaths.TempLocation)
        image = self.model.get_image()
        desktop_geometry = QDesktopWidget().screenGeometry()

        # Scale image according to option
        if option == 2:
            # Fit to desktop width
            image = image.scaledToWidth(desktop_geometry.width(), Qt.SmoothTransformation)
        elif option == 3:
            # Fit to desktop height
            image = image.scaledToHeight(desktop_geometry.height(), Qt.SmoothTransformation)

        image.save(path + "/hr_wallpaper.bmp") # Save new image
                
        if os.name == 'nt': # Windows
            import win32api, win32con, win32gui

            if self.model.get_image_path() is not None:
                tiled = "1" if option == 1 else "0"
                
                key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER,"Control Panel\\Desktop",0,win32con.KEY_SET_VALUE)
                win32api.RegSetValueEx(key, "WallpaperStyle", 0, win32con.REG_SZ, "0")
                win32api.RegSetValueEx(key, "TileWallpaper", 0, win32con.REG_SZ, tiled)
                win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, path, win32con.SPIF_UPDATEINIFILE | win32con.SPIF_SENDCHANGE)
            
        else: # Linux
            if self.model.image_path is not None:
                wallpaper_option = 'wallpaper' if option == 0 else 'centered'

                call('gconftool-2 -t str -s /desktop/gnome/background/picture_filename'.split() + [path + "/hr_wallpaper.bmp"], stdout=PIPE, stderr=PIPE)
                call('gconftool-2 -t str -s /desktop/gnome/background/picture_options'.split() + [wallpaper_option], stdout=PIPE, stderr=PIPE)
コード例 #30
0
    def __init__(self):
        super().__init__()
        #Window settings
        self.availableGeometry = app.desktop().availableGeometry()
        self.screenGeometry = QDesktopWidget().screenGeometry(-1)
        self.left = 0
        self.top = 0
        self.minWidth = 0
        self.minHeight = 0
        self.maxWidth = self.availableGeometry.width()
        self.maxHeight = self.availableGeometry.height()
        self.width = self.maxWidth
        self.height = self.maxHeight
        self.opacity = 0.3
        self.color = QColor(255,255,255)  #Set RGB colours later
        self.taking_screenshot = False #Boolean. Set to True when screenshot process is occuring
        self.statusText = "X1: {} Y1: {} | X2: {} Y2: {} | Width: {} Height: {}"
        
        #Step Multipliers
        self.stepMultiplier = 10
        self.stepBigMultipler = 10
        self.stepSize = 1 #number of pixels to move the window by

        #Mouse cursor
        self.begin = QPoint(0,0)
        self.end = QPoint(0,0)
        self.x_compensate = self.availableGeometry.x() - self.screenGeometry.x()
        self.y_compensate = self.availableGeometry.y() - self.screenGeometry.y()
        self.begin_x_definitive = None
        self.begin_y_definitive = None
        self.end_x_definitive = None
        self.end_y_definitive = None
        self.screenshot_width = None
        self.screenshot_height = None

        self.initUI()
コード例 #31
0
ファイル: snake.py プロジェクト: balwinder5911/01_Snake

if __name__ == "__main__":
    # Start QW Application
    app = qw.QApplication(sys.argv)

    # Create Display Widget to contain
    display = qw.QLabel()
    display.resize(500, 500)
    # display.move(500, 0)

    # ----- Window -----
    main_window = qw.QMainWindow()
    main_window.setGeometry(0, 0, 1000, 500)
    frame_geometry = main_window.frameGeometry()
    center = QDesktopWidget().availableGeometry().center()
    frame_geometry.moveCenter(center)
    main_window.move(frame_geometry.topLeft())
    main_window.setWindowTitle("Snake - much extreme, much niceness")

    # Assign Event Handler
    main_window.keyPressEvent = move_event

    widget = Form(main_window)
    main_window.show()

    # Create Standard Game Settings
    gameSettings = Settings(int(widget.le_speed.text()),
                            int(widget.le_size.text()),
                            int(widget.le_zoom.text()),
                            int(widget.le_loop.text()),
コード例 #32
0
 def center(self):  # 主窗口居中显示函数
     screen = QDesktopWidget().screenGeometry()
     size = self.geometry()
     self.move((screen.width() - size.width()) / 2,
               (screen.height() - size.height()) / 2)
コード例 #33
0
def moveCenter(self):
    geom = self.frameGeometry()
    cnt = QDesktopWidget().availableGeometry().center()
    geom.moveCenter(cnt)
    self.move(geom.topLeft())
コード例 #34
0
ファイル: PlottingWindow.py プロジェクト: kendall-s/HyPro2_py
    def init_ui(self):
        self.setFont(QFont('Segoe UI'))

        self.setGeometry(0, 0, 780, 820)
        qtRectangle = self.frameGeometry()
        centerPoint = QDesktopWidget().availableGeometry().center()
        qtRectangle.moveCenter(centerPoint)
        self.move(qtRectangle.topLeft())

        self.setWindowTitle('HyPro - Plotting Window')

        self.qvbox_layout = QVBoxLayout()
        self.qvbox_frame_holder = QFrame()
        self.qvbox_frame_holder.setLayout(self.qvbox_layout)
        self.grid_layout = QGridLayout()

        self.main_menu = self.menuBar()
        self.file_menu = self.main_menu.addMenu('File')
        self.edit_menu = self.main_menu.addMenu('Edit')

        export = QAction(QIcon(':/assets/archivebox.svg'), 'Export Plot', self)
        export.triggered.connect(self.export_plot)
        self.file_menu.addAction(export)

        copy = QAction(QIcon(':/assets/newdoc.svg'), 'Copy', self)
        copy.triggered.connect(self.copy_plot)
        self.edit_menu.addAction(copy)

        self.run_list_label = QLabel('Select Run:', self)
        self.run_list = QListWidget(self)
        self.run_list.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.run_list.setMaximumWidth(120)

        self.show_bad_data = QCheckBox('Show bad data', self)

        self.mark_bad_data = QCheckBox('Mark bad data', self)

        self.apply_button = QPushButton('Apply', self)

        self.figure = plt.figure()
        self.figure.set_tight_layout(tight=True)
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setParent(self)

        self.main_plot = self.figure.add_subplot(111)

        for x in self.main_plot.get_xticklabels():
            x.set_fontsize(12)
        for y in self.main_plot.get_yticklabels():
            y.set_fontsize(12)

        self.grid_layout.addWidget(self.canvas, 0, 1)
        self.grid_layout.addWidget(self.qvbox_frame_holder, 0, 0)

        self.qvbox_layout.addWidget(self.run_list_label)
        self.qvbox_layout.addWidget(self.run_list)
        self.qvbox_layout.addWidget(self.show_bad_data)
        self.qvbox_layout.addWidget(self.mark_bad_data)
        self.qvbox_layout.addWidget(self.apply_button)

        self.centralWidget().setLayout(self.grid_layout)
コード例 #35
0
    def initUI(self):
        """
        Sets up the GUI for the application
        """
        # Set initial size of window and placement of window
        self.resize(800, 400)

        # Set title and icon for window
        self.setWindowTitle('3D Audio For Museum Exhibits')
        self.setWindowIcon(QIcon('images/icon.png'))

        # Center the window
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

        # Set a grid for widgets to fall in line with
        grid = QGridLayout()
        self.setLayout(grid)

        # Customize ToolTip
        QToolTip.setFont(QFont('SansSerif', 10))

        # Customize play button
        play_btn = QPushButton('Play')
        play_btn.setToolTip('Begin playback of 3D audio')
        play_btn.resize(100, 33)
        play_btn.clicked.connect(self.hrtfWrapper)

        # Customize stop button
        stop_btn = QPushButton('Stop')
        stop_btn.setToolTip('Stop playback of 3D audio')
        stop_btn.resize(100, 33)

        # Customize canvas
        canvas = QPixmap('images/canvas.jpg')
        canvas_lbl = QLabel(self)
        canvas_lbl.setPixmap(canvas)

        # Customize radio buttons
        radio_one = QRadioButton("1 - Rice Cooking")
        radio_one.setChecked(True)
        self.radio_buttons.append(radio_one)

        radio_two = QRadioButton("2 - Steak Searing")
        self.radio_buttons.append(radio_two)

        radio_three = QRadioButton("3 - Plantains Frying")
        self.radio_buttons.append(radio_three)

        # Add button widgets to grid
        grid.addWidget(QWidget(), 1, 1, 1, 3)  # empty space
        grid.addWidget(canvas_lbl, 2, 1, 3, 3)  # <---canvas
        grid.addWidget(QWidget(), 5, 1, 1, 3)  # empty space
        grid.addWidget(play_btn, 5, 4)  # play button
        grid.addWidget(stop_btn, 5, 5)  # stop button
        grid.addWidget(radio_one, 1, 4)  # first radio button
        grid.addWidget(radio_two, 2, 4)  # second radio button
        grid.addWidget(radio_three, 3, 4)  # third radio button
        grid.addWidget(QWidget(), 1, 5, 4, 1)  # empty space

        # Show the window
        self.show()
コード例 #36
0
 def center_window(self):
     qtRectangle = self.frameGeometry()
     centerPoint = QDesktopWidget().availableGeometry().center()
     qtRectangle.moveCenter(centerPoint)
     self.move(qtRectangle.topLeft())
コード例 #37
0
ファイル: ui.py プロジェクト: Rohitimb/mycodepractice
lookup_btn = QPushButton('LCMt_sku_Lookup', mainwidget)
total_btn = QPushButton('LCM_sku_Total', mainwidget)
skuread_btn = QPushButton('LCM_sku_read', mainwidget)
metricread_btn = QPushButton('LCM_metric_read', mainwidget)
metricadd_btn = QPushButton('LCM_metric_add', mainwidget)
lookup_table_choice = QComboBox(mainwidget)

passwid = QWidget()
name_lbl = QLabel('Enter Username', passwid)
pass_lbl = QLabel('Enter Password', passwid)
submit_btn = QPushButton('Login!', passwid)
name_lineedit = QLineEdit(passwid)
pass_lineedit = QLineEdit(passwid)
invalid_pass_lbl = QLabel('', passwid)

desk = QDesktopWidget()
screen = desk.screenGeometry()
print(type(screen))
w = screen.width()
h = screen.height()
print(screen.width())
print(screen.height())

mainwidget.setFixedSize(800, 495)
mainwidget.move((w - mainwidget.width()) / 2, (h - mainwidget.height()) / 2)
mainwidget.setWindowTitle('Py Utility for DB access')


def checkPasswordandConnect():
    global users
    global passwords
コード例 #38
0
 def screen_size(self):
     """
     Returns an (width, height) tuple with the screen geometry.
     """
     screen = QDesktopWidget().screenGeometry()
     return screen.width(), screen.height()
コード例 #39
0
 def center(self):
     rect = self.frameGeometry()
     rect.moveCenter(QDesktopWidget().availableGeometry().center())
     self.move(rect.topLeft())
コード例 #40
0
ファイル: splash.py プロジェクト: DevotionZhu/PyQGIS
 def move_center(self):
     # 获取屏幕分辨率
     screen = QDesktopWidget().screenGeometry()
     size = self.geometry()
     self.move((screen.width() - size.width()) / 2,
               (screen.height() - size.height()) / 2)
コード例 #41
0
 def center(self):
     qr = self.frameGeometry()  # 창의 위치와 크기정보 확인
     cp = QDesktopWidget().availableGeometry().center()  # 모니터 화면의 가운데 위치 확인
     qr.moveCenter(cp)  # 창의 직사각형 (Left top) 위치를 중앙으로 이동
     self.move(qr.topLeft()
               )  # 창의 직사각형 (Left top) 위치를 Left top으로 이동하여 결과적으로 정 중아에 위치
コード例 #42
0
 def center(self):
     qr = self.frameGeometry()  # 창의 위치와 크기 정보를 얻는다.
     cp = QDesktopWidget().availableGeometry().center(
     )  # 모니터 화면의 가운데 위치를 파악
     qr.moveCenter(cp)  # 창의 직사각형 위치를 화면 중심의 위치로 이동
     self.move(qr.topLeft())  # 현재 창을, qr의 위치로 이동시킨다.
コード例 #43
0
 def center(self):
     qr = self.frameGeometry()
     cp = QDesktopWidget().availableGeometry().center()
     qr.moveCenter(cp)
     self.move(qr.topLeft())
コード例 #44
0
 def center(self):
     geometry = QDesktopWidget().screenGeometry()
     size = self.geometry()
     self.move((geometry.width() - size.width()) / 2,
               (geometry.height() - size.height()) / 2)
コード例 #45
0
import sys

from PyQt5.QtWidgets import QApplication, QDesktopWidget

from ui.main_window import MainWindow

if __name__ == "__main__":

    app = QApplication(sys.argv)

    window = MainWindow()

    if len(app.arguments()) > 1:
        window.openFile(app.arguments()[1])
    else:
        window.resize(QDesktopWidget().availableGeometry().size() * 0.75)
    window.show()
    sys.exit(app.exec_())
コード例 #46
0
ファイル: 25_CenterForm.py プロジェクト: gxg0504/pyqt5
 def center(self):
     screen = QDesktopWidget().screenGeometry()
     size = self.geometry()
     NewLeft = (screen.width() - size.width())/2
     NewTop = (screen.height() - size.height())/2
     self.move(NewLeft,NewTop)
コード例 #47
0
 def center(self):
     '''centers the window on the screen'''
     screen = QDesktopWidget().screenGeometry()
     size = self.geometry()
     self.move((screen.width() - size.width()) / 2,
               (screen.height() - size.height()) / 2)
コード例 #48
0
ファイル: main.py プロジェクト: HTMLProgrammer2001/PyQT
    def center(self):
        fr = self.frameGeometry()
        qr = QDesktopWidget().availableGeometry().center()

        fr.moveCenter(qr)
        self.move(fr.topLeft())
コード例 #49
0
    def setupUi(self, MainWindow):
        resolution = QDesktopWidget().screenGeometry(self)
        # MainWindow.setGeometry(QRect(0,0,0,0))
        MainWindow.setFixedSize(resolution.size().width()*0.99, resolution.size().height()*0.90)#1200 800
        # self.setWindowState(Qt.WindowMaximized)
        print("resol : ", MainWindow.size())

        #메인 화면 색상py
        self.setStyleSheet("color: black;"
                        "background-color: white;")

        font = QFont()
        font.setFamily("NanumGothic")
        MainWindow.setFont(font)
        self.centralwidget = QWidget(MainWindow)
        self.label = QLabel(self.centralwidget)
        self.label.setGeometry(QRect(20, 20, 130, 35))
        font = QFont()
        font.setFamily("NanumGothic")
        font.setPointSize(18)
        font.setBold(True)
        font.setWeight(75)
        self.label.setFont(font)
        self.button_add = QPushButton(self.centralwidget)
        self.button_add.setGeometry(QRect(MainWindow.size().width()*0.05, MainWindow.size().height() - 80, 131, 34))
        #버튼 스타일 변경
        self.button_add.setStyleSheet(staticValues.blueButtonStyleSheet)
        self.button_add.setFont(staticValues.buttonFont)

        self.button_modi = QPushButton(self.centralwidget)
        self.button_modi.setGeometry(QRect(MainWindow.size().width()*0.20, MainWindow.size().height() - 80, 131, 34))
        self.button_modi.setStyleSheet(staticValues.blueButtonStyleSheet)
        self.button_modi.setFont(staticValues.buttonFont)

        self.button_del = QPushButton(self.centralwidget)
        self.button_del.setGeometry(QRect(MainWindow.size().width()*0.35, MainWindow.size().height() - 80, 131, 34))
        self.button_del.setStyleSheet(staticValues.redButtonStyleSheet)
        self.button_del.setFont(staticValues.buttonFont)

        self.button_upload = QPushButton(self.centralwidget)
        self.button_upload.setGeometry(QRect(MainWindow.size().width()*0.7, MainWindow.size().height() - 80, 131, 34))
        self.button_upload.setStyleSheet(staticValues.grayButtonStyleSheet)
        self.button_upload.setFont(staticValues.buttonFont)

        self.tabWidget = QTabWidget(self.centralwidget)
        self.tabWidget.setGeometry(QRect(10, 70, MainWindow.size().width()-15, MainWindow.size().height() - 180))
        self.tab = QWidget()
        self.tab.layout = QVBoxLayout()
        self.tabWidget.addTab(self.tab, "회원 목록")
        self.tableWidget = QTableWidget(self.tab)
        self.tableWidget.setGeometry(QRect(0, 0, self.tabWidget.size().width()-5, self.tabWidget.size().height()-25))
        self.tableWidget.setColumnCount(13)
        self.tableWidget.setRowCount(0)
        self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)

        self.tableWidget.setHorizontalHeaderLabels(["회원 ID", "단톡방", "코인명", "구매", "입금", "판매", "출근"
        , "보유잔량", "총구매금액", "총판매금액", "수익", "평단가", "지갑주소"])

        self.tab2 = QWidget()
        self.tab2.layout = QVBoxLayout()
        self.tabWidget.addTab(self.tab2, "중복 회원")
        self.tableWidget2 = QTableWidget(self.tab2)
        self.tableWidget2.setGeometry(QRect(0, 20, self.tabWidget.size().width()-5, self.tabWidget.size().height()-45))
        self.tableWidget2.setColumnCount(3)
        self.tableWidget2.setRowCount(0)
        self.tableWidget2.setSelectionBehavior(QAbstractItemView.SelectRows)
        
        self.tableWidget.setHorizontalHeaderLabels(["회원 ID", "현재 단톡방", "중복 단톡방"])
        
        
        self.edit_search = QLineEdit(self.centralwidget)
        self.edit_search.setGeometry(QRect(MainWindow.size().width()-280, 35, 200, 30))
        self.edit_search.setStyleSheet(staticValues.solidStyleSheet)
        

        self.button_search = QPushButton(self.centralwidget)
        self.button_search.setGeometry(QRect(MainWindow.size().width()-80, 35, 70, 30))
        self.button_search.setStyleSheet(staticValues.grayButtonStyleSheet)
        self.button_search.setFont(staticValues.buttonFont)

        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        self.tabWidget.setCurrentIndex(0)
        QMetaObject.connectSlotsByName(MainWindow)
コード例 #50
0
    def __init__(self, parent=None):
        super().__init__()
        self.setWindowTitle(self.tr("Welcome Pisi GNU/Linux"))
        self.setFixedSize(700, 475)
        self.setWindowIcon(QIcon(":/images/pisilinux-welcome.svg"))
        self.setLayout(QVBoxLayout())
        self.layout().setSpacing(0)
        self.layout().setContentsMargins(0, 0, 0, 0)
        self.setStyleSheet("QPushButton {border: none; text-align: left; color:\
        black;} QLabel {color:black;}")

        x = (QDesktopWidget().width() - self.width()) // 2
        y = (QDesktopWidget().height() - self.height()) // 2
        self.move(x, y)

        # The header code:

        self.headerWidget = QWidget()
        self.headerWidget.setFixedHeight(80)
        self.headerWidget.setLayout(QHBoxLayout())
        self.headerWidget.setStyleSheet("background-image:\
        url(:/images/background.png);")
        self.layout().addWidget(self.headerWidget)

        self.pisiWhiteLogo = QLabel()
        self.pisiWhiteLogo.setFixedSize(64, 64)
        self.pisiWhiteLogo.setScaledContents(True)
        self.pisiWhiteLogo.setPixmap(
            QIcon(":/images/pisi-white.svg").pixmap(self.pisiWhiteLogo.size()))
        self.headerWidget.layout().addWidget(self.pisiWhiteLogo)

        self.pisiTextLabel = QLabel()
        self.pisiTextLabel.setFixedSize(157, 48)
        self.pisiTextLabel.setScaledContents(True)
        self.pisiTextLabel.setPixmap(QPixmap(":/images/pisi-text.png"))
        self.headerWidget.layout().addWidget(self.pisiTextLabel)

        self.headerWidget.layout().addItem(
            QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Expanding))

        self.versionLabel = QLabel()
        font = self.versionLabel.font()
        font.setPointSize(12)
        self.versionLabel.setFont(font)
        self.versionLabel.setText(
            "{} - {}".format(
                QSysInfo.productVersion(), QSysInfo.currentCpuArchitecture()))
        self.versionLabel.setStyleSheet("color: white; font-weight: bold;")
        self.headerWidget.layout().addWidget(self.versionLabel)

        # The middle area code:

        self.contentWidget = QWidget()
        self.contentWidget.setLayout(QVBoxLayout())
        self.contentWidget.setStyleSheet("background-color: white;")
        self.layout().addWidget(self.contentWidget)

        self.meetingLabel = QLabel()
        self.meetingLabel.setText(
            self.tr("Welcome to Pisi GNU/Linux!"
                    " Thank you for joining our community!\n\n"
                    "As Pisi GNU/Linux developers,"
                    " we hope you enjoy using Pisi GNU/Linux."
                    " The following links will guide you while"
                    " using Pisi GNU/Linux. Please do not"
                    " hesitate to inform about your experiences,"
                    " suggestions and errors you have encountered."))

        self.meetingLabel.setWordWrap(True)
        font = self.meetingLabel.font()
        font.setPointSize(10)
        self.meetingLabel.setFont(font)
        self.meetingLabel.setAlignment(Qt.AlignHCenter)
        self.meetingLabel.setStyleSheet("color: black;")
        self.contentWidget.layout().addWidget(self.meetingLabel)

        self.mainLayout = QHBoxLayout()
        self.contentWidget.layout().addLayout(self.mainLayout)

        vlayoutI = QVBoxLayout()

        self.docsHeader = QLabel()
        font = self.docsHeader.font()
        font.setPointSize(14)
        font.setBold(True)
        self.docsHeader.setFont(font)
        self.docsHeader.setAlignment(Qt.AlignHCenter)
        self.docsHeader.setText(self.tr("Documents"))
        vlayoutI.addWidget(self.docsHeader)

        self.installationDocButton = QPushButton()
        self.installationDocButton.setFixedWidth(160)
        self.installationDocButton.setCursor(Qt.PointingHandCursor)
        self.installationDocButton.setText(self.tr("Installation Guide"))
        self.installationDocButton.setIcon(QIcon(":/images/guide.svg"))
        self.installationDocButton.setIconSize(QSize(32, 32))
        vlayoutI.addWidget(self.installationDocButton)

        self.releaseNotesButton = QPushButton()
        self.releaseNotesButton.setFixedWidth(160)
        self.releaseNotesButton.setCursor(Qt.PointingHandCursor)
        self.releaseNotesButton.setText(self.tr("Release Notes"))
        self.releaseNotesButton.setIcon(QIcon(":/images/info.svg"))
        self.releaseNotesButton.setIconSize(QSize(32, 32))
        vlayoutI.addWidget(self.releaseNotesButton)

        self.wikiButton = QPushButton()
        self.wikiButton.setFixedWidth(160)
        self.wikiButton.setCursor(Qt.PointingHandCursor)
        self.wikiButton.setText(self.tr("Pisi GNU/Linux Wiki"))
        self.wikiButton.setIcon(QIcon(":/images/wikipedia-logo.svg"))
        self.wikiButton.setIconSize(QSize(32, 32))
        vlayoutI.addWidget(self.wikiButton)

        vlayoutII = QVBoxLayout()

        self.supportHeader = QLabel()
        font = self.supportHeader.font()
        font.setPointSize(14)
        font.setBold(True)
        self.supportHeader.setFont(font)
        self.supportHeader.setAlignment(Qt.AlignHCenter)
        self.supportHeader.setText(self.tr("Support"))
        vlayoutII.addWidget(self.supportHeader)

        self.forumButton = QPushButton()
        self.forumButton.setFixedWidth(160)
        self.forumButton.setCursor(Qt.PointingHandCursor)
        self.forumButton.setText(self.tr("Forum"))
        self.forumButton.setIconSize(QSize(32, 32))
        self.forumButton.setIcon(QIcon(":/images/forum.svg"))
        vlayoutII.addWidget(self.forumButton)

        self.chatButton = QPushButton()
        self.chatButton.setFixedWidth(160)
        self.chatButton.setCursor(Qt.PointingHandCursor)
        self.chatButton.setText(self.tr("Chat Rooms"))
        self.chatButton.setIcon(QIcon(":/images/chat.svg"))
        self.chatButton.setIconSize(QSize(32, 32))
        vlayoutII.addWidget(self.chatButton)

        self.bugsButton = QPushButton()
        self.bugsButton.setFixedWidth(160)
        self.bugsButton.setCursor(Qt.PointingHandCursor)
        self.bugsButton.setText(self.tr("Bug Report"))
        self.bugsButton.setIcon(QIcon(":/images/bug.svg"))
        self.bugsButton.setIconSize(QSize(32, 32))
        vlayoutII.addWidget(self.bugsButton)

        vlayoutIII = QVBoxLayout()

        self.installationHeader = QLabel()
        font = self.installationHeader.font()
        font.setPointSize(14)
        font.setBold(True)
        self.installationHeader.setFont(font)
        self.installationHeader.setAlignment(Qt.AlignHCenter)
        self.installationHeader.setText(self.tr("Installation"))
        vlayoutIII.addWidget(self.installationHeader)

        # TODO: Also for YALI
        self.calamaresButton = QPushButton()
        self.calamaresButton.setFixedWidth(160)
        self.calamaresButton.setCursor(Qt.PointingHandCursor)
        self.calamaresButton.setText(self.tr("Start Installation"))
        self.calamaresButton.setIcon(QIcon(":/images/calamares.svg"))
        self.calamaresButton.setIconSize(QSize(32, 32))
        vlayoutIII.addWidget(self.calamaresButton)

        self.joinUsButton = QPushButton()
        self.joinUsButton.setFixedWidth(160)
        self.joinUsButton.setCursor(Qt.PointingHandCursor)
        self.joinUsButton.setText(self.tr("Join Us"))
        self.joinUsButton.setIcon(QIcon(":/images/joinus.svg"))
        self.joinUsButton.setIconSize(QSize(32, 32))
        vlayoutIII.addWidget(self.joinUsButton)

        self.donateButton = QPushButton()
        self.donateButton.setFixedWidth(160)
        self.donateButton.setCursor(Qt.PointingHandCursor)
        self.donateButton.setText(self.tr("Ev"))
        self.donateButton.setIcon(QIcon(":/images/ev.svg"))
        self.donateButton.setIconSize(QSize(32, 32))
        vlayoutIII.addWidget(self.donateButton)

        self.mainLayout.addLayout(vlayoutI)
        self.mainLayout.addLayout(vlayoutII)
        self.mainLayout.addLayout(vlayoutIII)

        self.noteLabel = QLabel()
        font = self.noteLabel.font()
        font.setPointSize(12)
        font.setBold(True)
        self.noteLabel.setFont(font)
        self.noteLabel.setText(self.tr("Note: The password is \"live\"."))
        self.noteLabel.setAlignment(Qt.AlignHCenter)
        self.noteLabel.setMinimumSize(250, 50)
        self.noteLabel.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Maximum)
        self.contentWidget.layout().addWidget(self.noteLabel)

        # The footer code:

        self.footerWidget = QWidget()
        self.footerWidget.setFixedHeight(50)
        self.footerWidget.setLayout(QHBoxLayout())
        self.footerWidget.setStyleSheet(
            "background-image: url(:/images/background.png);")
        self.layout().addWidget(self.footerWidget)

        self.facebookButton = QPushButton()
        self.facebookButton.setFixedSize(36, 36)
        self.facebookButton.setIconSize(QSize(36, 36))
        self.facebookButton.setIcon(QIcon(":/images/facebook.svg"))
        self.facebookButton.setCursor(Qt.PointingHandCursor)
        self.facebookButton.setToolTip(self.tr("Facebook Page"))
        self.footerWidget.layout().addWidget(self.facebookButton)

        self.twitterButton = QPushButton()
        self.twitterButton.setFixedSize(36, 36)
        self.twitterButton.setIconSize(QSize(36, 36))
        self.twitterButton.setIcon(QIcon(":/images/twitter.svg"))
        self.twitterButton.setCursor(Qt.PointingHandCursor)
        self.twitterButton.setToolTip(self.tr("Twitter Page"))
        self.footerWidget.layout().addWidget(self.twitterButton)

        self.googleButton = QPushButton()
        self.googleButton.setFixedSize(36, 36)
        self.googleButton.setIconSize(QSize(36, 36))
        self.googleButton.setIcon(QIcon(":/images/google-plus.svg"))
        self.googleButton.setCursor(Qt.PointingHandCursor)
        self.googleButton.setToolTip(self.tr("Google+ Page"))
        self.footerWidget.layout().addWidget(self.googleButton)

        self.instagramButton = QPushButton()
        self.instagramButton.setFixedSize(36, 36)
        self.instagramButton.setIconSize(QSize(36, 36))
        self.instagramButton.setIcon(QIcon(":/images/instagram.svg"))
        self.instagramButton.setCursor(Qt.PointingHandCursor)
        self.instagramButton.setToolTip(self.tr("Instagram Page"))
        self.footerWidget.layout().addWidget(self.instagramButton)

        self.githubButton = QPushButton()
        self.githubButton.setFixedSize(36, 36)
        self.githubButton.setIconSize(QSize(36, 36))
        self.githubButton.setIcon(QIcon(":/images/github-logo.svg"))
        self.githubButton.setCursor(Qt.PointingHandCursor)
        self.githubButton.setToolTip(self.tr("GitHub Page"))
        self.footerWidget.layout().addWidget(self.githubButton)

        self.slackButton = QPushButton()
        self.slackButton.setFixedSize(36, 36)
        self.slackButton.setIconSize(QSize(36, 36))
        self.slackButton.setIcon(QIcon(":/images/Slack.png"))
        self.slackButton.setCursor(Qt.PointingHandCursor)
        self.slackButton.setToolTip(self.tr("Slack Page"))
        self.footerWidget.layout().addWidget(self.slackButton)

        self.footerWidget.layout().addItem(
            QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Expanding))

        self.startupCheckBox = QCheckBox()
        self.startupCheckBox.setChecked(
            os.path.exists(os.path.join(os.environ["HOME"],
                                        ".config",
                                        "autostart",
                                        "pisilinux-welcome.desktop")))
        font = self.startupCheckBox.font()
        font.setBold(True)
        self.startupCheckBox.setFont(font)
        self.startupCheckBox.setText(self.tr("Show on startup"))
        self.startupCheckBox.setStyleSheet("color: white;")
        self.footerWidget.layout().addWidget(self.startupCheckBox)

        self.facebookButton.clicked.connect(self.facebookPage)
        self.twitterButton.clicked.connect(self.twitterPage)
        self.googleButton.clicked.connect(self.googlePage)
        self.instagramButton.clicked.connect(self.instagramPage)
        self.githubButton.clicked.connect(self.githubPage)
        #self.slackButton.clicked.connect(self.slackPage)

        #self.releaseNotesButton.clicked.connect(self.releaseNotes)
        self.wikiButton.clicked.connect(self.wikiPage)
        self.forumButton.clicked.connect(self.forumPage)
        self.chatButton.clicked.connect(self.chatPages)
        #self.joinUsButton.clicked.connect(self.joinUsPage)
        #self.donateButton.clicked.connect(self.donatePage)
        self.startupCheckBox.clicked.connect(self.startupState)
        self.bugsButton.clicked.connect(self.issuesPage)
コード例 #51
0
    ########## Window Setup ##########
    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(
            _translate("MainWindow", "Replotter       (created by I.T.Booth)"))

        self.FrameLabel.setText(_translate("MainWindow", "Frames Processed"))
        self.nLabel.setText(_translate("MainWindow", "n ="))
        self.rLabel.setText(_translate("MainWindow", "r ="))
        self.sLabel.setText(_translate("MainWindow", "s ="))

        self.PlotButton.setText(_translate("MainWindow",
                                           "Plot Interactive 3D"))


########## Execute above protocol ##########
if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    app.setStyle('Fusion')
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    ag = QDesktopWidget().availableGeometry()
    sg = QDesktopWidget().screenGeometry()
    widget = MainWindow.geometry()
    x = 0.1 * (ag.width() - widget.width())
    y = 0.5 * ag.height() - widget.height()
    MainWindow.move(x, y)
    MainWindow.show()
    sys.exit(app.exec_())
コード例 #52
0
 def showEvent(self, event):
     geom = self.frameGeometry()
     geom.moveCenter(QDesktopWidget().availableGeometry().center())
     self.setGeometry(geom)
     super(LcncDialog, self).showEvent(event)
コード例 #53
0
 def wn_move_center(self, x_it):
     nu_cp = QDesktopWidget().availableGeometry().center()  # center point
     nu_fg = x_it.frameGeometry()
     nu_fg.moveCenter(nu_cp)
     x_it.move(nu_fg.topLeft())
コード例 #54
0
class App(QWidget):
    def __init__(self):
        super().__init__()
        self.title = 'Danmu Screen'
        self.DanMu = []
        self.initUI()

    def initUI(self):
        # Set Geometry
        self.setWindowTitle(self.title)
        self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground, True)
        self.setAttribute(Qt.WA_TransparentForMouseEvents, True)
        self.screen = QDesktopWidget().screenGeometry()
        self.resize(self.screen.width(), self.screen.height())

        # Read Ass File
        fname = self.openFileNameDialog()
        self.StyleList, self.DanmuList = danmu.readAss(fname)
        print(len(self.DanmuList))

        # Go run
        self.shiftTime = 0  # in sec
        self.t0 = time.time()
        self.currentDanMuID = 0

        # for i in range(5):
        #     self.sendOne(self.DanmuList[i])
        # self.tick()
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.tick)
        self.timer.start(200)

    def openFileNameDialog(self):
        options = QFileDialog.Options()
        #options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getOpenFileName(
            self,
            "QFileDialog.getOpenFileName()",
            "",
            "Ass Files (*.ass);; Xml Files (*.xml);; All Files (*.*)",
            options=options)
        return fileName

    def sendOne(self, danmu):
        # Danmu: ass.event
        TOP_MARGIN = -50
        IN_MARGIN = 0.7
        #
        dura = (danmu.end - danmu.start) * 1000

        fontMetrics = QFontMetrics(QFont(danmu.fontname, danmu.fontsize))
        fontwidth = fontMetrics.width(danmu.text)
        fontheight = fontMetrics.height()

        startX = danmu.startX * self.screen.width() - fontwidth / 2
        endX = danmu.endX * self.screen.width() - fontwidth / 2

        if danmu.type != 3:
            startY = danmu.startY * self.screen.height(
            ) * IN_MARGIN + TOP_MARGIN
            endY = danmu.endY * self.screen.height() * IN_MARGIN + TOP_MARGIN
        else:
            startY = danmu.startY * self.screen.height()
            endY = danmu.endY * self.screen.height()

        newD = QLabel(danmu.text, self)
        newD.setAttribute(Qt.WA_TransparentForMouseEvents, True)
        newD.setStyleSheet(
            "font-family:{}; font-size: {}pt; color: {};opacity:0;".format(
                danmu.fontname, danmu.fontsize, danmu.color))
        newD.show()  # NB
        self.fly(newD, dura, (startX, startY), (endX, endY))

    def fly(self, label, duration, sv, ev):
        anim = QPropertyAnimation(label, b"pos")
        did = len(self.DanMu)
        self.DanMu.append(anim)
        self.DanMu[did].setDuration(duration)
        self.DanMu[did].setStartValue(QPoint(*sv))
        self.DanMu[did].setEndValue(QPoint(*ev))
        self.DanMu[did].setEasingCurve(QEasingCurve.Linear)
        self.DanMu[did].start()

        self.DanMu[did].finished.connect(label.deleteLater)

    def tick(self):
        now = time.time()
        elps = now - self.t0 + self.shiftTime
        waitTime = self.DanmuList[self.currentDanMuID].start
        while elps >= waitTime:
            self.sendOne(self.DanmuList[self.currentDanMuID])
            self.currentDanMuID += 1
            waitTime = self.DanmuList[self.currentDanMuID].start
            # Output logging
            hours, rem = divmod(waitTime, 3600)
            minutes, seconds = divmod(rem, 60)
            print(self.currentDanMuID, ("{:0>2}:{:0>2}:{:05.2f}".format(
                int(hours), int(minutes), seconds)))

    def keyPressEvent(self, event):
        super(App, self).keyPressEvent(event)
        if event.text() == ',':
            if self.currentDanMuID > 5:
                self.shiftTime -= 2
                now = self.DanmuList[self.currentDanMuID].start
                while now - self.DanmuList[self.currentDanMuID - 3] < 2:
                    self.DanMu.remove(self.DanMu[-1])
                    self.DanMu.remove(self.DanMu[-2])
                    self.DanMu.remove(self.DanMu[-3])
                    self.currentDanMuID -= 3

        elif event.text() == '.':
            self.shiftTime += 2
            now = self.DanmuList[self.currentDanMuID].start
            while self.DanmuList[self.currentDanMuID + 5].start - now < 2:
                self.currentDanMuID += 5

        elif event.key() == Qt.Key_Space:
            i, okpressed = QInputDialog.getInt(self, "Please input progress",
                                               "percentage:", 0, 0, 100, 1)
            if okpressed:
                self.currentDanMuID = int(len(self.DanmuList) * (i / 100))
                self.shiftTime = self.DanmuList[self.currentDanMuID].start
コード例 #55
0
class App(QWidget):
    cleanupEvent = pyqtSignal()

    def __init__(self, resources):
        super().__init__()
        self.versionNumber = '1.2.7'
        self.title = 'Monkey See Monkey Do   v'+self.versionNumber
        self.left = 10
        self.top = 80
        self.width = 640
        self.height = 100
        self.folderName = ''
        self.imageList = []
        self.numImages = 0
        self.currentImageNumber = 0
        self.currentTotalImageNumber = 0
        self.hotSpotFilename = 'hotspots.json'
        self.hotSpotFile = None
        self.hotSpotSize = 50
        self.currentHotSpot = None
        self.startTime = None
        self.endTime = None
        self.robot = []
        self.screen = QDesktopWidget().availableGeometry()
        self.platform = platform.name()
        self.resources = resources
        print(self.screen)
        print('Operating System: ', self.platform)
        print('Screen: width:', self.screen.width(), 'height:', self.screen.height())
        self.initUI()

    def initUI(self):

        self.readConfig()

        self.portLabel = QLabel('Port(s): ', self)
        self.portDisplay = QLineEdit(self)
        self.portDisplay.setEnabled(False)
        self.portRefreshButton = QPushButton(self)
        self.portRefreshButton.setToolTip('Press to detect port of connected base station')
        self.portRefreshButton.clicked.connect(self.refreshPorts)
        self.portRefreshButton.setIcon(QIcon(self.resources['imgRefresh']))
        self.portRefreshButton.setFixedWidth(24)

        self.settingsButton = QPushButton()
        self.settingsButton.setToolTip('Open the Settings Dialog')
        self.settingsButton.setIcon(QIcon(self.resources['imgSettings']))
        self.settingsButton.setMaximumWidth(24)
        self.settingsButton.clicked.connect(self.openSettings)

        self.connected = False
        self.refreshPorts()
        if self.showReferenceCreator:
            self.referenceCreator = QPushButton('Create Reference', self)
            self.referenceCreator.setToolTip('Create a reference file from the selected image set')
            self.referenceCreator.clicked.connect(self.createReferenceFile)
            self.referenceCreator.setEnabled(False)

        self.folderButton = QPushButton('Select Folder', self)
        self.folderButton.setToolTip('Select the folder that contains the content you would like to play')
        self.folderButton.clicked.connect(self.folderButtonClicked)

        self.folderLabel = QLabel('Selected Folder:', self)

        self.selectedFolder = QLineEdit(self)
        self.selectedFolder.setEnabled(False)

        self.numLevelsLabel = QLabel('Number of Levels:', self)
        self.numLevelsDisplay = QLineEdit(self)
        self.numLevelsDisplay.setEnabled(False)

        self.numImagesLabel = QLabel('Number of Images:', self)
        self.numImagesDisplay = QLineEdit(self)
        self.numImagesDisplay.setEnabled(False)

        self.startLabel = QLabel('Press "Start" to begin game', self)

        self.startButton = QPushButton('Start', self)
        self.startButton.setToolTip('Start Game')
        self.startButton.clicked.connect(self.startButtonClicked)
        self.startButton.setEnabled(False)

        self.hboxPort = QHBoxLayout()
        self.hboxPort.addWidget(self.portLabel)
        self.hboxPort.addWidget(self.portDisplay)
        self.hboxPort.addWidget(self.portRefreshButton)
        self.hboxPort.addWidget(self.settingsButton)

        self.hbox = QHBoxLayout()
        self.hbox.addWidget(self.folderLabel)
        self.hbox.addWidget(self.selectedFolder)

        self.hboxNumLevels = QHBoxLayout()
        self.hboxNumLevels.addWidget(self.numLevelsLabel)
        self.hboxNumLevels.addWidget(self.numLevelsDisplay)

        self.hboxNumImages = QHBoxLayout()
        self.hboxNumImages.addWidget(self.numImagesLabel)
        self.hboxNumImages.addWidget(self.numImagesDisplay)

        self.vbox = QVBoxLayout()
        self.vbox.addLayout(self.hboxPort)
        self.vbox.addWidget(self.folderButton)
        self.vbox.addLayout(self.hbox)
        self.vbox.addLayout(self.hboxNumLevels)
        self.vbox.addLayout(self.hboxNumImages)
        if self.showReferenceCreator:
            self.vbox.addWidget(self.referenceCreator)
        self.vbox.addWidget(self.startLabel)
        self.vbox.addWidget(self.startButton)
        self.vbox.addStretch(4)

        self.startPage = QWidget()
        self.startPage.setLayout(self.vbox)

        self.scene = QGraphicsScene()
        self.graphicsView = GraphicsView(self.scene)
        self.graphicsView.itemClickedEvent.connect(self.hotSpotClickedHandler)
        self.graphicsView.keyPressed.connect(self.keyPressedHandler)

        self.graphicsLayout = QVBoxLayout()
        self.graphicsLayout.addWidget(self.graphicsView)
        self.graphicsLayout.setContentsMargins(0, 0, 0, 0)

        self.gamePage = QWidget()
        self.gamePage.setLayout(self.graphicsLayout)

        self.stackedLayout = QStackedLayout()
        self.stackedLayout.addWidget(self.startPage)
        self.stackedLayout.addWidget(self.gamePage)
        self.stackedLayout.setCurrentIndex(0)

        self.setLayout(self.stackedLayout)
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.setWindowIcon(QIcon(self.resources['icoMSMD']))
        self.cleanupEvent.connect(self.cleanupStuff)
        self.show()
        self.bringToFront()

    def readConfig(self):
        self.config = configparser.ConfigParser()
        fileCheck = self.config.read(self.resources['fileConfig'])
        if(fileCheck == []):
            QMessageBox.critical(self, 'Config Error!', 'config.ini was not found', QMessageBox.Ok)
        self.robotSettings = self.config['robot']
        self.appSettings = self.config['app']

        # robot settings
        self.upgradeTrigger = self.robotSettings['upgradeTrigger']
        self.upgradeMode = self.robotSettings['upgradeMode']
        self.minPowerToMove = self.robotSettings['minPowerToMove']
        self.maxPowerToMove = self.robotSettings['maxPowerToMove']

        # app settings
        self.showReferenceCreator = int(self.appSettings.get('showReferenceCreator', '1'))
        self.timeLimitMultiplier = float(self.appSettings.get('time_limit_multiplier', '1'))
        self.levelToUnlock = int(self.appSettings.get('level_to_unlock', '0'))

    def writeConfig(self):
        self.robotSettings['upgradeTrigger'] = self.upgradeTrigger
        self.robotSettings['upgradeMode'] = self.upgradeMode
        self.robotSettings['minPowerToMove'] = self.minPowerToMove
        self.robotSettings['maxPowerToMove'] = self.maxPowerToMove

        self.appSettings['level_to_unlock'] = str(self.levelToUnlock)
        with open(self.resources['fileConfig'], 'w') as configFile:
            self.config.write(configFile)

    def openSettings(self):
        try:
            SettingsIn = {
                'upgradeTrigger': 'hotspot',
                'upgradeMode': 'left',
                'minPowerToMove': '80'}
            self.settingsWindow = Settings(self.robotSettings)
            self.settingsWindow.Closing.connect(self.settingsClosed)
            self.settingsWindow.show()
            self.setDisabled(True)
        except:
            print('ERROR - Setting.py Load Failed!')

    def settingsClosed(self, message):
        if(message == 'Abort'):
            print('Settigns Aborted!')
        elif(message == 'Closed'):
            print('Settings Closed!')
            # Set New Settings
            newSettings = self.settingsWindow.getSettings()
            self.upgradeTrigger = newSettings['upgradeTrigger']
            self.upgradeMode = newSettings['upgradeMode']
            self.minPowerToMove = newSettings['minPowerToMove']
            self.maxPowerToMove = newSettings['maxPowerToMove']
            self.writeConfig()
        else:
            print('ERROR - Unknown message returned from Settings.py Window!')
        self.setDisabled(False)

    def bringToFront(self):
        self.setWindowState(self.windowState() & ~Qt.WindowMinimized | Qt.WindowActive)
        self.activateWindow()

    def refreshPorts(self):
        if(self.connected):
            for baseStation in self.robot:
                baseStation.close()
        comPorts = self.findPorts()
        if(comPorts):
            self.robot = []
            self.portDisplayText = ''
            for i, port in enumerate(comPorts):
                self.robot.append(serial.Serial(port))
                self.robot[i].baudrate = 115200
                self.robot[i].timeout = 0.05
                self.portDisplayText += (port + '  ')
            self.portDisplay.setText(self.portDisplayText)
            self.connected = True
        else:
            self.robot = []
            self.connected = False

    def folderButtonClicked(self):
        # get folder with content in it from user
        self.folderName = QFileDialog.getExistingDirectory(self, "Select Folder Location for Recorded Content")
        print(self.folderName)
        if os.path.isdir(self.folderName):  # If it is a valid folder
            self.numLevels = 0
            self.numTotalImages = 0
            self.listOfFilesInSelectedFolder = os.listdir(self.folderName)
            self.folderList = []
            self.folderListNameOnly = []
            for name in self.listOfFilesInSelectedFolder:
                fullFileName = os.path.join(self.folderName, name)
                if os.path.isdir(fullFileName):
                    result = self.loadLevel(fullFileName)  # load each level to make sure it is valid
                    if(result < 0):  # if the folder is not a valid level, quit this function
                        return
                    self.folderList.append(fullFileName)
                    self.folderListNameOnly.append(name)
                    self.numLevels += 1
                    self.numTotalImages += result
            self.folderListNameOnly = sorted(self.folderListNameOnly)  # sort the resulting list of level folders (they should be named in order they will be played in)
            if(self.numLevels > 0):
                # multiLevel game selected
                self.loadLevel(self.folderList[0])  # load the first level
                self.numLevelsDisplay.setText(str(self.numLevels))  # display the number of levels in the selected folder
            else:
                # single level selected
                result = self.loadLevel(self.folderName)  # try to load the single level selected
                if(result < 0):  # if level is invalid, quit this function
                    return
                self.numTotalImages = result
                self.numLevelsDisplay.setText('1')
            if(self.levelToUnlock>self.numLevels):
                if(self.numLevels == 0):
                    self.levelToUnlock = 0
                else:
                    self.levelToUnlock = self.numLevels-1
            self.currentLevel = 0
            self.numImagesDisplay.setText(str(self.numTotalImages))
            self.startButton.setEnabled(True)
            if self.showReferenceCreator:
                self.referenceCreator.setEnabled(True)
            self.selectedFolder.setText(self.folderName)
        else:
            QMessageBox.warning(self, 'Folder Error!', 'The folder does not exist!\nPlease select a valid folder', QMessageBox.Ok)

    def loadLevel(self, levelToLoad):
        try:
            print('Trying to load '+levelToLoad)
            self.hotSpotFile = open(levelToLoad+os.path.sep+self.hotSpotFilename, 'r')
            self.hotSpotDict = json.load(self.hotSpotFile)
            self.numHotSpotRecords = len(self.hotSpotDict)
            # self.hotSpotCsv = csv.reader(self.hotSpotFile)
            # next(self.hotSpotCsv)
            # self.numHotSpotRecords = sum(1 for row in self.hotSpotCsv)
            # self.hotSpotFile.seek(0)
            # next(self.hotSpotCsv) #skip column labels on first line
            self.hotSpotFile.close()
            buildScanCodeTranslationTable(self.hotSpotDict)
        except IOError:
            QMessageBox.critical(self, 'Error: No hotspots.json', 'hotspots.json does not exist\nA Hot Spot file is required to play the game. Please select a complete and valid content folder', QMessageBox.Ok)
            self.selectedFolder.setText('Error: No hotspots.json')
            return -1
        self.imageList = []
        try:
            for imageFile in sorted((imfile for imfile in os.listdir(levelToLoad) if imfile.endswith('.png'))):

                self.imageList.append(QImage(levelToLoad+os.path.sep+imageFile))

        except IOError:
            QMessageBox.critical(self, 'Error: images reading', 'Images could not be read\nPlease select a complete and valid content folder', QMessageBox.Ok)
            return -1
        self.numImages = len(self.imageList)-1
        if(self.numImages != self.numHotSpotRecords):
            QMessageBox.critical(self, 'Error: Image Hotspot Mismatch', 'Error: number of images in level "'+str(levelToLoad)+'" do not match the number of hot spot records', QMessageBox.Ok)
            return -1
        return self.numImages

    def startButtonClicked(self):
        print('start')
        self.stackedLayout.setCurrentIndex(1)
        self.paintImageIndex(0)
        self.showMaximized()

        if(self.upgradeTrigger == 'level'):
            self.setPower((int(self.minPowerToMove)*100)//255)

        self.startTime = time.time()

    def paintImageIndex(self, imageNumber):
        if(self.upgradeTrigger == 'hotspot'):
            powerLevel = (self.currentTotalImageNumber/(self.numTotalImages-1))*100
            print('power:', powerLevel, '  currentTotalImageNum:', self.currentTotalImageNumber, '  numTotalImages:', self.numTotalImages)
            self.setPower(powerLevel)
        self.scene.clear()
        print('current image number:', imageNumber)
        self.nextHotSpotInput = self.hotSpotDict[str(self.currentImageNumber).zfill(6)]
        print('nextHotSpotInput', self.nextHotSpotInput)
        self.currentPixmap = QPixmap.fromImage(self.imageList[imageNumber]).copy(QRect(0, 0, 1920, 1020)).scaled(self.screen.width(), self.screen.height(), aspectRatioMode=Qt.IgnoreAspectRatio)

        self.scene.addPixmap(self.currentPixmap)

        self.currentInputModifiers = self.simplifyModifierList(self.nextHotSpotInput['modifiers'])

        if(self.nextHotSpotInput['type'] == 'mouse'):
            commandString = ''
            if self.currentInputModifiers != []:
                commandString += 'Press '
            for mod in self.currentInputModifiers:
                commandString += mod + ' + '
            commandString += 'Click '
            self.currentMouseButton = self.nextHotSpotInput['button']
            if(self.currentMouseButton == 'right'):
                pen = QPen(QColor(0, 0, 255, 128))
                commandString += 'right mouse button'
            elif(self.currentMouseButton == 'left'):
                pen = QPen(QColor(255, 0, 0, 128))
                commandString += 'left mouse button'
            elif(self.currentMouseButton == 'middle'):
                pen = QPen(QColor(0, 255, 0, 128))
                commandString += 'scroll wheel (middle mouse button)'
            else:
                pen = QPen(QColor(0, 0, 0, 128))
            xScale = self.screen.width()/1920
            yScale = self.screen.height()/1020
            if(xScale > yScale):
                minScale = yScale
            else:
                minScale = xScale
            scaledHotSpotSize = self.hotSpotSize*minScale
            xPosition = self.nextHotSpotInput['position'][0]*xScale
            yPosition = self.nextHotSpotInput['position'][1]*yScale
            # adjust yPosition
            yPosition += 30
            print('next hotspot pos x %s y %s' % (xPosition, yPosition))
            brush = QBrush(QColor(180, 180, 180, 100))
            self.currentHotSpot = QGraphicsEllipseItem()
            self.currentHotSpot.setRect(xPosition-scaledHotSpotSize/2, yPosition-scaledHotSpotSize/2, scaledHotSpotSize, scaledHotSpotSize)
            self.currentHotSpot.setBrush(brush)
            self.currentHotSpot.setPen(pen)
            self.scene.addItem(self.currentHotSpot)
            self.currentInputKey = -1
        elif(self.nextHotSpotInput['type'] == 'key'):
            # print('key')
            self.currentInputKey = self.nextHotSpotInput['scancode']
            commandString = 'Press '
            for mod in self.currentInputModifiers:
                commandString += mod
                commandString += ' + '
            commandString += self.nextHotSpotInput['name']
            self.currentHotSpot = 'not a hotspot'
        else:
            QMessageBox.critical(self, 'Error: hotSpotInput type is incorrect. got: "'+self.nextHotSpotInput['type']+'"  expected: "key" or "mouse"', QMessageBox.Ok)

        self.setWindowTitle(self.title + '       ' + commandString)

    def playSound(self):

        class SoundThread(QThread):
            signal = pyqtSignal('PyQt_PyObject')

            def __init__(self, soundFilename):
                super().__init__()

                self.soundFilename = soundFilename

            def run(self):

                # define stream chunk
                chunk = 1024

                # open a wav format music
                f = wave.open(self.soundFilename, "rb")
                # instantiate PyAudio
                p = pyaudio.PyAudio()
                # open stream
                stream = p.open(format=p.get_format_from_width(f.getsampwidth()),
                                channels=f.getnchannels(),
                                rate=f.getframerate(),
                                output=True)
                # read data
                data = f.readframes(chunk)

                # play stream
                while data:
                    stream.write(data)
                    data = f.readframes(chunk)

                # stop stream
                stream.stop_stream()
                stream.close()

                # close PyAudio
                p.terminate()
                self.signal.emit(soundFilename)

        subFolder = ''
        if self.folderListNameOnly:
            subFolder = '%s%s' % (self.folderListNameOnly[self.currentLevel], os. path.sep)
        soundFilename = '%s%s%ssound%s.wav'% (self.folderName, os.path.sep, subFolder, self.currentImageNumber)

        if not os.path.isfile(soundFilename):
            return
        try:
            self.soundThread = SoundThread(soundFilename)
            self.soundThread.signal.connect(self.soundFinished)
            self.soundThread.start()
        except:
            print('something when wrong with the sound thread')

    def soundFinished(self, soundFile):
        print('finished playing %s' % soundFile)

    def hotSpotClickedHandler(self, itemClicked, modifiers, mouseButton):

        print('itemClicked %s, self.currentHotSpot %s, mouseButton %s' % (itemClicked, self.currentHotSpot, mouseButton))

        if itemClicked is self.currentHotSpot:
            if self.checkModifierMatch(modifiers):
                if self.checkButtonMatch(mouseButton):
                    # print('clicked on hot spot!')

                    self.playSound()

                    self.currentImageNumber += 1
                    self.currentTotalImageNumber += 1
                    if self.currentImageNumber >= self.numImages:
                        self.levelCompleted()
                    else:
                        self.paintImageIndex(self.currentImageNumber)
                else:
                    # print('wrong mouse button clicked')
                    pass
            else:
                # print("modifiers don't match")
                pass
        else:
            # print('wrong spot clicked')
            pass

    def checkButtonMatch(self, pressedMouseButton):
        if pressedMouseButton == Qt.LeftButton:
            pressedMouseButtonString = 'left'
        if pressedMouseButton == Qt.RightButton:
            pressedMouseButtonString = 'right'
        if pressedMouseButton == Qt.MiddleButton:
            pressedMouseButtonString = 'middle'

        return self.currentMouseButton == pressedMouseButtonString

    def keyPressedHandler(self, nativeScanCode, keyText, modifiers):
        print('scanCode %s, currentInputKey %s' % (nativeScanCode, self.currentInputKey))
        if (nativeScanCode == self.currentInputKey) and self.checkModifierMatch(modifiers):
            # print('pressed correct key (or key combination)')

            self.playSound()

            self.currentImageNumber += 1
            self.currentTotalImageNumber += 1
            if self.currentImageNumber >= self.numImages:
                self.levelCompleted()
            else:
                self.paintImageIndex(self.currentImageNumber)
        else:
            # print('wrong key or key combination pressed')
            pass

    def checkModifierMatch(self, pressedModifiers):
        modifierTextList = []
        if(pressedModifiers & Qt.ShiftModifier):
            modifierTextList.append('shift')
        if(pressedModifiers & Qt.AltModifier):
            modifierTextList.append('alt')

        # handle key differences for mac
        if(self.platform in ['Windows', 'Linux']):
            if(pressedModifiers & Qt.ControlModifier):
                modifierTextList.append('ctrl')
            if(pressedModifiers & Qt.MetaModifier):
                modifierTextList.append('win')
        else:
            if(pressedModifiers & Qt.ControlModifier):
                modifierTextList.append('cmd')  # on the mac this is the command key
            if(pressedModifiers & Qt.MetaModifier):
                modifierTextList.append('ctrl')  # on the mac this is the control key
        return set(modifierTextList) == set(self.currentInputModifiers)

    def simplifyModifierList(self, modifierList):
        tempSet = set()
        for item in modifierList:
            if item == 'left shift':
                tempSet.add('shift')
            elif item == 'right shift':
                tempSet.add('shift')
            elif item == 'left ctrl':
                tempSet.add('ctrl')
            elif item == 'right ctrl':
                tempSet.add('ctrl')
            elif item == 'left alt':
                tempSet.add('alt')
            elif item == 'right alt':
                tempSet.add('alt')
            else:
                tempSet.add(item)
        return list(tempSet)

    def levelCompleted(self):
        self.levelTime = time.time()-self.startTime
        print('completed level: ', self.currentLevel+1)

        if(self.upgradeTrigger == 'level'):
            powerLevel = (self.currentLevel/(self.numLevels-1))*100
            self.setPower(powerLevel)

        timeToBeat = (self.currentTotalImageNumber)*self.timeLimitMultiplier
        if(self.currentLevel == self.levelToUnlock):
            print('unlockLevel?')
            # if the level was completed fast enough to move on
            if(self.levelTime <= timeToBeat):
                print('levelUnlocked')
                # (next level is all levels compounded...)
                # if the level completed was the last level
                if(self.currentLevel >= self.numLevels-1):
                    self.gameCompleted()
                else:
                    # move level to unlock up to next level
                    self.levelToUnlock += 1
                    # otherwise ask the user if they want to play the next
                    # level or quit
                    buttonReply = QMessageBox.question(
                        self,
                        'You Beat Level ' + str(self.currentLevel+1),
                        'You Beat the level!\nYou completed the level in ' + "%.2f" % self.levelTime + ' seconds out of ' + "%.2f" % timeToBeat + '\nPlay next level?',
                        QMessageBox.Yes | QMessageBox.Cancel)
                    if(buttonReply == QMessageBox.Cancel):
                        # quit game and go back to home screen
                        self.returnToHomeScreen()
                    else:
                        # restart (but with next level unlocked)
                        self.currentLevel = 0
                        self.currentImageNumber = 0
                        self.currentTotalImageNumber = 0
                        self.loadLevel(self.folderList[self.currentLevel])
                        self.paintImageIndex(0)
            else:
                print('levelFailed')
                # display dialog; complete in X time to advance to next level.  Replay?  Quit?
                buttonReply = QMessageBox.information(self, 'Too Slow...', 'You were not fast enough.\nYou completed the level in ' + "%.2f" % (self.levelTime) + ' seconds\nFinish in ' + "%.2f" % timeToBeat + ' seconds or less to move on.', QMessageBox.Ok | QMessageBox.Cancel)
                if(buttonReply == QMessageBox.Cancel):
                    # quit game and go back to home screen
                    self.returnToHomeScreen()
                else:
                    # restart
                    self.currentLevel = 0
                    self.currentImageNumber = 0
                    self.currentTotalImageNumber = 0
                    self.loadLevel(self.folderList[self.currentLevel])
                    self.paintImageIndex(0)
            self.startTime = time.time()
        else:
            # play next level
            self.currentLevel += 1
            self.currentImageNumber = 0
            self.loadLevel(self.folderList[self.currentLevel])
            self.paintImageIndex(0)

    def returnToHomeScreen(self):
        print('returning to home screen')
        self.setWindowTitle(self.title)
        self.scene.clear()
        self.currentHotSpot = None
        self.currentImageNumber = 0
        self.currentTotalImageNumber = 0
        self.stackedLayout.setCurrentIndex(0)
        self.showNormal()
        if(self.numLevels > 0):
            self.loadLevel(self.folderList[0])
        else:
            self.loadLevel(self.folderName)
        self.currentLevel = 0

    def gameCompleted(self):
        self.endTime = time.time()
        timeToBeat = (self.currentTotalImageNumber)*self.timeLimitMultiplier
        self.scene.clear()
        self.currentHotSpot = None
        self.currentImageNumber = 0
        self.currentTotalImageNumber = 0
        self.currentPixmap = None
        self.currentPixmap = QPixmap.fromImage(self.imageList[self.numImages]).copy(QRect(0, 0, 1920, 1020)).scaled(self.screen.width(), self.screen.height(), aspectRatioMode=Qt.IgnoreAspectRatio)
        self.scene.addPixmap(self.currentPixmap)
        buttonReply = QMessageBox.information(self, 'You Win!', 'Congradulations, You Won!\nYou completed the game in ' + "%.2f" % (self.endTime-self.startTime) + ' seconds out of ' "%.2f" % timeToBeat, QMessageBox.Ok)
        if buttonReply == QMessageBox.Ok:
            self.setWindowTitle(self.title)
            self.stackedLayout.setCurrentIndex(0)
            self.showNormal()
            if(self.numLevels > 0):
                self.loadLevel(self.folderList[0])
            else:
                self.loadLevel(self.folderName)
            self.currentLevel = 0

    def findPorts(self):
        ports = list(serial.tools.list_ports.comports())
        comPortsList = []
        # microcontrollerPort = None
        for port in ports:
            if 'Silicon Labs' in str(port[1]):
                comPortsList.append(port[0])
        return comPortsList

    def setPower(self, powerLevel):
        if(powerLevel > 100):
            raise ValueError('powerLevel cannot be set above 100')
        if(powerLevel < 0):
            raise ValueError('powerLevel cannot be set below 0')

        minPower = int(self.minPowerToMove)
        mode = self.upgradeMode
        leftPower = minPower
        rightPower = minPower
        maxPower = int(self.maxPowerToMove)
        if(mode == "left"):
            if(powerLevel <= 50):
                leftPower = self.interpolate(powerLevel, 0, 100, minPower, maxPower)
                rightPower = self.interpolate(powerLevel, 0, 50, minPower, maxPower)
            else:
                leftPower = self.interpolate(powerLevel, 0, 100, minPower, maxPower)
                rightPower = self.interpolate(powerLevel, 50, 100, minPower, maxPower)
        elif(mode == "right"):
            if(powerLevel <= 50):
                rightPower = self.interpolate(powerLevel, 0, 100, minPower, maxPower)
                leftPower = self.interpolate(powerLevel, 0, 50, minPower, maxPower)
            else:
                rightPower = self.interpolate(powerLevel, 0, 100, minPower, maxPower)
                leftPower = self.interpolate(powerLevel, 50, 100, minPower, maxPower)
        elif(mode == "both"):
            leftPower = self.interpolate(powerLevel, 0, 100, minPower, maxPower)
            rightPower = leftPower
        elif(mode == "distance"):
            # add fuel to the robot "tank"
            pass

        else:
            raise ValueError('upgradeMode in config.ini does not match any accepted value')

        iLP = int(leftPower)
        iRP = int(rightPower)

        # desiredPowerLevel -= 45
        if self.robot:
            print('connected to BaseStation, attempting to set power to', powerLevel, '   L:', leftPower, 'R:', rightPower)
            for baseStation in self.robot:
                baseStation.write(bytes([0, 0, iLP, iRP])+b'\n')
                baseStation.write(bytes([0, 0, iLP, iRP])+b'\n')
        else:
            print('BaseStation not connected, cannot change power level')

    def interpolate(self, inputValue, inputMin, inputMax, outputMin, outputMax):
        ratio = (inputValue - inputMin)/(inputMax - inputMin)
        outputValue = (outputMax - outputMin) * ratio + outputMin
        return outputValue

    def closeEvent(self, event):
        print('emitting cleanup event')
        try:
            self.settingsWindow.Abort()
        except:
            print('ERROR - Could not properly close settings window!')
        self.cleanupEvent.emit()

    def cleanupStuff(self):
        if self.robot:
            for baseStation in self.robot:
                baseStation.close()
        print('closing')

    def createReferenceFile(self):
        referenceFolder = QFileDialog.getExistingDirectory(self, "Select Folder Location for Reference")
        self.startTime = time.time()
        if os.path.isdir(referenceFolder):

            if(self.numLevels > 0):
                # multiLevel game selected
                print('multiLevelGame Reference started')
                for i in range(0, self.numLevels):
                    # create folder to hold level in reference file
                    levelFolderName = referenceFolder+os.path.sep+self.folderListNameOnly[i]
                    os.mkdir(levelFolderName)

                    self.loadLevel(self.folderList[i])

                    # start msmd level
                    self.stackedLayout.setCurrentIndex(1)
                    self.showMaximized()
                    time.sleep(0.2)

                    for j in range(0, self.numImages):
                        print('next image: '+str(j))
                        self.paintImageIndex(j)
                        QApplication.processEvents()

                        time.sleep(0.05)
                        imageName = str(self.currentImageNumber).zfill(6)
                        pyautogui.screenshot(levelFolderName+os.path.sep+imageName+'.png')

                        self.currentImageNumber += 1
                        self.currentTotalImageNumber += 1

                    self.currentImageNumber = 0
            else:
                print('singleLevelGame Reference Started')
                self.loadLevel(self.folderName)
                self.stackedLayout.setCurrentIndex(1)
                self.showMaximized()

                for j in range(0, self.numImages):
                    print('next image: '+str(j))
                    self.paintImageIndex(j)
                    QApplication.processEvents()

                    time.sleep(0.05)
                    imageName = str(self.currentImageNumber).zfill(6)
                    pyautogui.screenshot(levelFolderName+os.path.sep+imageName+'.png')

                    self.currentImageNumber += 1
                    self.currentTotalImageNumber += 1

                self.currentImageNumber = 0

            self.gameCompleted()
コード例 #56
0
 def pp2_move_center():
     pu2_cp = QDesktopWidget().availableGeometry().center()
     pu2_fg = self.frameGeometry()
     pu2_fg.moveCenter(pu2_cp)
     self.move(pu2_fg.topLeft())
コード例 #57
0
def moveToScreenCenter(widget):
    frame = widget.frameGeometry()
    frame.moveCenter(QDesktopWidget().availableGeometry().center())
    widget.move(frame.topLeft())
コード例 #58
0
ファイル: debug_window.py プロジェクト: viniciusjb/tribler
    def __init__(self, settings, tribler_version):
        self._logger = logging.getLogger(self.__class__.__name__)
        QMainWindow.__init__(self)

        self.core_cpu_plot = None
        self.gui_cpu_plot = None
        self.initialized_cpu_plot = False
        self.cpu_plot_timer = None

        self.core_memory_plot = None
        self.gui_memory_plot = None
        self.initialized_memory_plot = False
        self.memory_plot_timer = None

        self.tribler_version = tribler_version
        self.profiler_enabled = False
        self.toggling_profiler = False

        uic.loadUi(get_ui_file_path('debugwindow.ui'), self)
        self.setWindowTitle("Tribler debug pane")

        connect(self.window().toggle_profiler_button.clicked,
                self.on_toggle_profiler_button_clicked)

        self.window().debug_tab_widget.setCurrentIndex(0)
        self.window().ipv8_tab_widget.setCurrentIndex(0)
        self.window().tunnel_tab_widget.setCurrentIndex(0)
        self.window().dht_tab_widget.setCurrentIndex(0)
        self.window().system_tab_widget.setCurrentIndex(0)
        connect(self.window().debug_tab_widget.currentChanged,
                self.tab_changed)
        connect(self.window().ipv8_tab_widget.currentChanged,
                self.ipv8_tab_changed)
        connect(self.window().tunnel_tab_widget.currentChanged,
                self.tunnel_tab_changed)
        connect(self.window().dht_tab_widget.currentChanged,
                self.dht_tab_changed)
        connect(self.window().events_tree_widget.itemClicked,
                self.on_event_clicked)
        connect(self.window().system_tab_widget.currentChanged,
                self.system_tab_changed)
        self.load_general_tab()

        self.window().open_files_tree_widget.header().setSectionResizeMode(
            0, QHeaderView.Stretch)

        # Enable/disable tabs, based on settings
        self.window().debug_tab_widget.setTabEnabled(2, settings is not None)
        self.window().debug_tab_widget.setTabEnabled(
            3, settings and settings['ipv8']['enabled'])
        self.window().system_tab_widget.setTabEnabled(
            3, settings and settings['resource_monitor']['enabled'])
        self.window().system_tab_widget.setTabEnabled(
            4, settings and settings['resource_monitor']['enabled'])

        # Refresh logs
        connect(self.window().log_refresh_button.clicked,
                lambda _: self.load_logs_tab())
        connect(self.window().log_tab_widget.currentChanged,
                lambda index: self.load_logs_tab())

        # IPv8 statistics enabled?
        self.ipv8_statistics_enabled = settings['ipv8']['statistics']

        # Libtorrent tab
        self.init_libtorrent_tab()

        # Position to center
        frame_geometry = self.frameGeometry()
        screen = QDesktopWidget().screenNumber(QDesktopWidget().cursor().pos())
        center_point = QDesktopWidget().screenGeometry(screen).center()
        frame_geometry.moveCenter(center_point)
        self.move(frame_geometry.topLeft())

        # Refresh timer
        self.refresh_timer = None
        self.rest_request = None
        self.ipv8_health_widget = None

        # GUI resource monitor
        self.resource_monitor = GuiResourceMonitor()
        self.resource_monitor.start()
コード例 #59
0
    def setupUi(self, MainWindow):

        resolution = QDesktopWidget().screenGeometry(self)
        print("resol : ", resolution.size())
        MainWindow.resize(resolution)
        #메인 화면 색상py
        self.setStyleSheet("color: black;" "background-color: white;")

        font = QFont()
        font.setFamily("NanumGothic")
        MainWindow.setFont(font)
        self.centralwidget = QWidget(MainWindow)
        self.label = QLabel(self.centralwidget)
        self.label.setGeometry(QRect(20, 20, 101, 31))
        font = QFont()
        font.setFamily("NanumGothic")
        font.setPointSize(18)
        font.setBold(True)
        font.setWeight(75)
        self.label.setFont(font)
        self.button_add = QPushButton(self.centralwidget)
        self.button_add.setGeometry(QRect(60, 730, 131, 34))
        #버튼 스타일 변경
        self.button_add.setStyleSheet(staticValues.blueButtonStyleSheet)
        self.button_add.setFont(staticValues.buttonFont)

        self.button_modi = QPushButton(self.centralwidget)
        self.button_modi.setGeometry(QRect(260, 730, 131, 34))
        self.button_modi.setStyleSheet(staticValues.blueButtonStyleSheet)
        self.button_modi.setFont(staticValues.buttonFont)

        self.button_del = QPushButton(self.centralwidget)
        self.button_del.setGeometry(QRect(460, 730, 131, 34))
        self.button_del.setStyleSheet(staticValues.redButtonStyleSheet)
        self.button_del.setFont(staticValues.buttonFont)

        self.button_upload = QPushButton(self.centralwidget)
        self.button_upload.setGeometry(QRect(790, 730, 131, 34))
        self.button_upload.setStyleSheet(staticValues.grayButtonStyleSheet)
        self.button_upload.setFont(staticValues.buttonFont)

        self.tabWidget = QTabWidget(self.centralwidget)
        self.tabWidget.setGeometry(QRect(40, 70, 1121, 621))
        self.tab = QWidget()
        self.tab.layout = QVBoxLayout()
        self.tabWidget.addTab(self.tab, "회원 목록")
        self.tableWidget = QTableWidget(self.tab)
        self.tableWidget.setGeometry(QRect(0, 0, 1111, 591))
        self.tableWidget.setObjectName("회원 목록")
        self.tableWidget.setColumnCount(13)
        self.tableWidget.setRowCount(0)
        self.tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)

        self.tableWidget.setHorizontalHeaderLabels([
            "회원 ID", "단톡방", "코인명", "구매", "입금", "판매", "출근", "보유잔량", "총구매금액",
            "총판매금액", "수익", "평단가", "지갑주소"
        ])
        # self.tableView = QTableWidget()
        # self.tableView.setColumnCount(5)
        # self.tableView.setRowCount(3)

        # self.tab.layout.addWidget(self.tableView)
        # self.tab.setLayout(self.tab.layout)
        # self.tab_2 = QWidget()
        # self.tabWidget.addTab(self.tab_2, "")
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        self.tabWidget.setCurrentIndex(0)
        QMetaObject.connectSlotsByName(MainWindow)
コード例 #60
0
    def initUI(self):

        # 选择文件

        btn = QPushButton('选择文件', self)
        btn.setToolTip('选择要上传的图片文件')
        btn.resize(btn.sizeHint())
        btn.move(20, 10)
        btn.clicked.connect(self.file_select)

        # 文件路径
        fp = QLabel("文件名称", self)
        fp.move(20, 80)

        self.qle = QLineEdit(self)
        self.qle.setReadOnly(True)
        self.qle.setFixedWidth(270)
        self.qle.move(80, 80)

        # 服务商选择按钮
        self.qiniu = QRadioButton("七牛", self)
        self.qiniu.setToolTip("上传到七牛")
        self.oss = QRadioButton("OSS", self)
        self.oss.setToolTip("上传到阿里云OSS")

        self.oss.move(25, 40)
        self.qiniu.move(125, 40)

        # 截图上传
        self.cb = QPushButton("截图上传", self)
        self.cb.setToolTip("选中会自动从剪贴板读取截图,以便上传")
        self.cb.resize(115, 35)
        self.cb.move(225, 40)
        self.cb.clicked.connect(self.jietu)

        # 复制按钮
        cbtn = QPushButton("复制MD链接", self)
        cbtn.setToolTip("复制上一个上传成功的图片Markdown链接")
        cbtn.resize(cbtn.sizeHint())
        cbtn.move(225, 10)
        cbtn.clicked.connect(self.copy_markdown_url)

        # 上传按钮
        ubtn = QPushButton("开始上传", self)
        ubtn.setToolTip("根据选择的文件和服务商上传图片,上传成功后会自动复制URL到剪贴板")
        ubtn.resize(ubtn.sizeHint())
        ubtn.move(120, 10)
        ubtn.clicked.connect(self.upload)

        # 日志区域
        self.qte = QTextEdit(self)
        self.qte.move(20, 120)
        self.qte.setFixedWidth(330)
        self.qte.setFixedHeight(300)
        self.qte.setReadOnly(True)
        self.qte.setText("日志信息:")

        # 绘制窗口
        self.setFixedSize(370, 440)

        # 窗口居中
        self.frameGeometry().moveCenter(
            QDesktopWidget().availableGeometry().center())

        self.setWindowTitle('File Upload')
        self.show()
        self.load_config()