class SplashScreen: def __init__(self, parent, image=None, after=None): self.app = parent image = QPixmap(image) image = image.scaled(500, 500, Qt.KeepAspectRatio, Qt.SmoothTransformation) self.splash = QSplashScreen( image, Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint) self.splash.setMask(image.mask()) self.after = after def set_after(self, after): self.after = after def __enter__(self): self.splash.show() self.app.processEvents() return self def __exit__(self, exc_type, exc_value, traceback): self.after.show() self.splash.finish(self.after) def status_update(self, msg): self.splash.showMessage(msg, alignment=Qt.AlignHCenter, color=QColor(235, 239, 242)) self.app.processEvents()
def run(): app = QApplication(sys.argv) app.setWindowIcon(QIcon(':/icons/windows/deeplisten-logo.png')) # splash screen # Create and display the splash screen splash_pix = QPixmap(':/icons/windows/start.png') splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) splash.show() app.processEvents() # Simulate something that takes time time.sleep(1) mw = MainWindow() mw.show() splash.finish(mw) ##setup stylesheet # import qdarkstyle # app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5()) sys.exit(app.exec_())
def welcomeExactDialog(app, settingsObject, mainwindow): # Create and display the about screen splash_pix = QPixmap(ARTWORK_DIR_NAME+'ExactWelcomeScreen.png') splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) btn = QPushButton('Enable EXACT', splash) btn.move(140, 320) btn.clicked.connect(partial(enableAndClose, splash, settingsObject,mainwindow)) btn = QPushButton('Disable EXACT',splash) btn.move(350, 320) btn.clicked.connect(partial(disableAndClose, splash, settingsObject,mainwindow)) # layout.addWidget(btn, 1,1) # splash.showMessage('Version %s\n'%version, alignment = Qt.AlignHCenter + Qt.AlignBottom, color=Qt.black) splash.setMask(splash_pix.mask()) splash.show() splash.mousePressEvent = partial(closeDlg, splash) start = time() while splash.isActiveWindow() & (time() - start < 10): sleep(0.001) app.processEvents() if (splash.isActiveWindow()): splash.close()
def main(): app = QApplication(sys.argv) app.setStyle('cleanlooks') app.setApplicationName("Linguistica") # Get screen resolution # Why do we need to know screen resolution? # Because this information is useful for setting the size of particular # widgets, e.g., the webview for visualizing the word neighbor manifold # (the bigger the webview size, the better it is for visualization!) resolution = app.desktop().screenGeometry() screen_width = resolution.width() screen_height = resolution.height() # create and display splash screen splash_image_path = os.path.join(os.path.dirname(__file__), 'lxa_splash_screen.png') splash_image = QPixmap(splash_image_path) splash_screen = QSplashScreen(splash_image, Qt.WindowStaysOnTopHint) splash_screen.setMask(splash_image.mask()) splash_screen.show() app.processEvents() time.sleep(2) # launch graphical user interface form = MainWindow(screen_height, screen_width, __version__) form.show() splash_screen.finish(form) app.exec_()
def run(image_path = None): # Global exceptions sys.excepthook = excepthook app = QApplication(sys.argv) # Splash screen splash_pix = QPixmap('resources/splash.jpg') splash = QSplashScreen(splash_pix) splash.setMask(splash_pix.mask()) splash.show() app.processEvents() # Load translation locale_code = SettingsModel().get('Language', 'code') if locale_code != "en_US": # Standard language # Standard translator for the generated GUI translator = QTranslator() translator.load('localization/' + locale_code + '.qm') app.installTranslator(translator) # Translator for various GUI elements translator_2 = QTranslator() translator_2.load('localization/' + locale_code + '_2.qm') app.installTranslator(translator_2) # Start m = Hitagi(image_path) # Pass image path splash.finish(m) sys.exit(app.exec())
def splash(self): pixmap = QPixmap(".\\gui\\pyspec_less_ugly_shorter.png") smallerPixmap = pixmap.scaled(256, 256, Qt.KeepAspectRatio, Qt.SmoothTransformation) splash = QSplashScreen(smallerPixmap, Qt.WindowStaysOnTopHint) splash.setMask(smallerPixmap.mask()) splash.setWindowFlag(Qt.WindowStaysOnTopHint) splash.show() self.processEvents() self.init_logging() self.processEvents() log.info("Initialization of views, models, controllers...") time.sleep(2) self.processEvents() self.mainModel = MainModel() self.mainCtrl = MainController() self.mainWindow = MainWindow(self.mainModel, self.mainCtrl) self.mainWindow.setWindowTitle("PySpec Software") self.mainWindow.setAttribute(Qt.WA_AlwaysStackOnTop) self.processEvents() log.info("Initialization completed.") self.processEvents() self.mainWindow.show() log.info("This is the MAIN THREAD")
def main(args=None): # supply path to qgis install location QgsApplication.setPrefixPath("/usr", True) # create a reference to the QgsApplication # setting the second argument to True enables the IquaView GUI, # which we need to do since this is a custom application qgs = QgsApplication([], True) # init splash screen splash_pix = QPixmap(':/resources/iquaview.png') splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) light_blue = QColor(165, 197, 192) dark_blue = QColor(11, 52, 70) # adding progress bar progress_bar = QProgressBar(splash) p = progress_bar.palette() p.setColor(QPalette.Highlight, light_blue) p.setColor(QPalette.HighlightedText, dark_blue) progress_bar.setPalette(p) progress_bar.setMaximum(10) progress_bar.setGeometry(0, splash_pix.height() - 50, splash_pix.width(), 20) splash.show() splash.showMessage("Initializing interface...", Qt.AlignBottom | Qt.AlignCenter, light_blue) # progress bar... for i in range(1, 11): progress_bar.setValue(i) t = time() if i == 5: splash.showMessage("Loading providers...", Qt.AlignBottom | Qt.AlignCenter, light_blue) # load providers qgs.initQgis() LOGGER.info(qgs.showSettings()) if i == 10: # exec iquaview window window = MainWindow() window.setWindowIcon(QIcon(":/resources/iquaview_vector.svg")) splash.showMessage("IQUAview ready!", Qt.AlignBottom | Qt.AlignCenter, light_blue) while time() < t + 0.1: qgs.processEvents() window.showMaximized() splash.finish(window) qgs.exec_() window.deleteLater() # when app terminates, call exitQgis() to remove the provider and layer registries from memory qgs.exitQgis()
def activateSplashScreen(): splash_pix = QPixmap( repr(os.path.dirname(os.path.realpath(sys.argv[0]))).replace( "\\\\", "/").replace("\'", "") + "/pics/splash.png") splash = QSplashScreen(splash_pix) splash.setMask(splash_pix.mask()) splash.show() time.sleep(2) return splash
def show_splash(self): image = QPixmap(':/loading_image') splash = QSplashScreen(image) splash.setAttribute(Qt.WA_DeleteOnClose) splash.setMask(image.mask()) splash.show() QCoreApplication.processEvents() Parser([]) splash.finish(self)
class waitsplash(): def __init__(self): path_here = os.path.realpath(__file__) imfile = os.path.join(os.path.split(path_here)[0], 'loading.png') splash_pix = QPixmap(imfile) self.splash = QSplashScreen(splash_pix) #, Qt.WindowStaysOnTopHint) self.splash.setMask(splash_pix.mask()) self.splash.show() QApplication.processEvents() def close(self): self.splash.close()
def launch_data_downloader(path): app = QApplication(sys.argv) splash_pix = QPixmap('icons/xigmanas_conf_backup_icon.svg') splash = QSplashScreen(splash_pix) splash.setMask(splash_pix.mask()) splash.show() config_dict = configparser.ConfigParser() if not os.path.exists(os.path.join(path, 'xigmanas_backup.ini')): config_dict['LOG'] = {'level': 'INFO', 'path': ''} config_dict['OPTIONS'] = { 'language': 'english', 'check_update': 'False' } config_dict['CREDENTIALS'] = { 'password': '', 'username': '', 'folder': '', 'target': '', 'target_port': '22' } with open(os.path.join(path, 'xigmanas_backup.ini'), 'w') as configfile: config_dict.write(configfile) config_dict.read(os.path.join(path, 'xigmanas_backup.ini')) path_exist = True if not config_dict.get('LOG', 'path'): log_filename = os.path.join(path, 'xigmanas_backup_log.out') else: path_exist = os.path.isdir(config_dict.get('LOG', 'path')) if path_exist: log_filename = os.path.join(config_dict.get('LOG', 'path'), 'xigmanas_backup_log.out') else: log_filename = os.path.join(path, 'xigmanas_backup_log.out') logging.getLogger('').handlers = [] logging.basicConfig(filename=log_filename, level=getattr(logging, config_dict.get('LOG', 'level')), filemode='w', format='%(asctime)s : %(levelname)s : %(message)s') formatter = logging.Formatter('%(levelname)s : %(message)s') console = logging.StreamHandler() console.setLevel(logging.DEBUG) console.setFormatter(formatter) logging.getLogger('').addHandler(console) logging.info('*****************************************') logging.info('XigmaNAS Conf Backup ' + _backup_version + ' is starting ...') logging.info('*****************************************') ui = MainWindow(path, config_dict) ui.show() splash.finish(ui) sys.exit(app.exec_())
def main(): """The main routine.""" environ["LIBOVERLAY_SCROLLBAR"] = "0" parser = argparse.ArgumentParser( prog=__title__, description=__title__ + ' is a 2d RPG game maker.', epilog=__copyright__ + ", " + __license__ +".") parser.add_argument('-v', '--version', action='store_true', default=False, help='get software version.') parser.add_argument('-c', '--clean', action='store_true', default=False, help='cleans software settings.') parser.add_argument('-p', '--palette', action='store_true', default=False, help='loads exclusively the palette editor.') parser.add_argument('mapfile', nargs='?', default='check_no_map', help='a single .map.json file') args = parser.parse_args() if args.clean == True: settings = QSettings("FGMK", "fgmkEditor") for key in settings.allKeys(): settings.remove(key) #guarantee to eliminate all settings.sync() #writes to disk exit() if args.palette == True: a = QApplication([]) m = palette_editor.main() a.processEvents() m.show() m.raise_() exit(a.exec_()) if args.version == True: print(__title__ + " v " + __version__ ) exit() a = QApplication([]) start = time() splash_pix = Editor.Icon() splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) splash.show() while time() - start < 1: sleep(0.001) a.processEvents() mw_arg=[] if 'mapfile' in args: mw_arg = [args.mapfile] mw = Editor.MainWindow(mw_arg) a.processEvents() mw.show() splash.finish(mw) mw.raise_() mw.afterInit() exit(a.exec_())
def main(): app = QApplication(sys.argv) # Create and display the splash screen splash_pix = QPixmap("./res/logo.png") splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) splash.show() time.sleep(2) registration_window = RegistrationWindow() registration_window.show() splash.finish(registration_window) sys.exit(app.exec_())
def showSplash(self): # Create and display the splash screen splash_pix = QPixmap( 'C:\\Users\\vcone\\Desktop\\Cosas\\CS\\Software2\\GUI test\\pick-tool-team13-the-bombs\\loading.png' ) splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) # Show a message at the center of the dialog splash.showMessage("Cleansing", 0x0084) splash.show() app.processEvents() # Simulate something that takes time time.sleep(2) splash.finish(self)
def splashScreen(app, version) -> QSplashScreen: # This first part is for loading the splash screen before anything else # Create and display the splash screen splash_pix = QPixmap(ARTWORK_DIR_NAME + 'SplashScreen.png') splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.showMessage('Version %s\n' % version, alignment=Qt.AlignHCenter + Qt.AlignBottom, color=Qt.black) splash.setMask(splash_pix.mask()) splash.show() app.processEvents() return splash
def main(): app = QApplication(sys.argv) # Create and display the splash screen splash_pix = PyQt5.QtGui.QPixmap("./res/logo.png") splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) splash.show() time.sleep(1) management_panel = ManagementPanel() management_panel.show() splash.finish(management_panel) sys.exit(app.exec_())
def initStartupProgressBar(): splash_pix = QPixmap(300, 100) splash_pix.fill(QtCore.Qt.white) painter = QPainter(splash_pix) font = QFont("Times", 30) painter.setFont(font) painter.drawText(20, 65, "Loading all libs") painter.end() splash = QSplashScreen(splash_pix, QtCore.Qt.WindowStaysOnTopHint) progressBar = QProgressBar(splash) progressBar.setGeometry(splash.width() / 10, 8 * splash.height() / 10, 8 * splash.width() / 10, splash.height() / 10) splash.setMask(splash_pix.mask()) splash.show() return splash, progressBar
def get_splash(app): """ Get the splash screen for the application But check to see if the image even exists :param app: :return: """ dir = '../images/' if os.path.exists(dir + 'robot.png'): splash_pix = QPixmap(dir + 'robot.png') # default app_icon = QtGui.QIcon(dir + 'robot.png') app.setWindowIcon(app_icon) splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) splash.show() time.sleep(0.6) app.processEvents()
def main(splash=True): import os import pkg_resources import sys import time from PyQt5.QtWidgets import QApplication app = QApplication(sys.argv) # Note: # Having the image file *not* in a submodule of FooQt # seems to cause the splash to display earlier, because # presumably `pkg_resources` internally imports modules. imdir = pkg_resources.resource_filename("fooqt", "img") if splash: from PyQt5.QtWidgets import QSplashScreen from PyQt5.QtGui import QPixmap splash_path = os.path.join(imdir, "splash.png") splash_pix = QPixmap(splash_path) splash = QSplashScreen(splash_pix) splash.setMask(splash_pix.mask()) splash.show() # make sure Qt really displays the splash screen time.sleep(.07) app.processEvents() from PyQt5 import QtCore, QtGui from .gui import FooQt time.sleep(1) # Set Application Icon icon_path = os.path.join(imdir, "icon.png") app.setWindowIcon(QtGui.QIcon(icon_path)) # Use dots as decimal separators QtCore.QLocale.setDefault(QtCore.QLocale(QtCore.QLocale.C)) window = FooQt() window.show() window.raise_() if splash: splash.finish(window) sys.exit(app.exec_())
def show_splash_screen(): from PyQt5.QtWidgets import QSplashScreen from PyQt5.QtGui import QPixmap, QColor from PyQt5.QtCore import Qt # create and display the splash screen splash_pix = QPixmap('assets/splash.jpg') splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) splash.showMessage('Loading...', alignment=Qt.AlignCenter | Qt.AlignBottom, color=QColor(Qt.white)) splash.show() return splash
def show_splash_screen(): """ displays splash screen before loading main window""" splash_pix = QPixmap("res/logo.png") splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) progress_bar = QProgressBar(splash) progress_bar.setMaximum(20) progress_bar.setGeometry(130, splash_pix.height() - 50, splash_pix.width() - 240, 20) progress_bar.setStyleSheet(""" QProgressBar { border: 1px solid #252323; border-radius: 6px; text-align: center; position: center; background-color: #252323; font-size: 1px; } QProgressBar::chunk { background-color: #04B97F; border-radius: 9px; margin-right: 23px; width: 20px; }""") splash.show() timer = QElapsedTimer() timer.start() time.sleep(1) for c in range(20): progress_bar.setValue(c) t = time.time() while time.time() < t + 0.3: app.processEvents() time.sleep(1) splash.close()
def launch_prosim_updater(path): app = QApplication(sys.argv) splash_pix = QPixmap('icons\splash_screen.svg') splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) splash.show() config_dict = configparser.ConfigParser() if not os.path.exists(os.path.join(path, 'prosim_updater.ini')): config_dict['LOG'] = {'level': 'DEBUG', 'path': ''} config_dict['OPTIONS'] = {'language':'english', 'check_update':'False', 'terminate_processes':'False', 'relaunch_processes':'False'} with open(os.path.join(path, 'prosim_updater.ini'), 'w') as configfile: config_dict.write(configfile) config_dict.read(os.path.join(path, 'prosim_updater.ini')) if not config_dict['OPTIONS'].get('language'): config_dict.set('OPTIONS', 'language', 'english') with open(os.path.join(path, 'prosim_updater.ini'), 'w') as configfile: config_dict.write(configfile) if not config_dict.get('LOG', 'path'): log_filename = os.path.join(path, 'prosim_creator_log.out') else: log_filename = os.path.join(config_dict.get('LOG', 'path'),'prosim_creator_log.out') logging.getLogger('').handlers = [] logging.basicConfig(filename = log_filename, level = getattr(logging, config_dict.get('LOG', 'level')), filemode = 'w', format = '%(asctime)s : %(levelname)s : %(message)s') formatter = logging.Formatter('%(levelname)s : %(message)s') console = logging.StreamHandler() console.setLevel(logging.DEBUG) console.setFormatter(formatter) logging.getLogger('').addHandler(console) logging.info('*****************************************') logging.info('Prosim737 Updater ' + _updater_version + ' is starting ...') logging.info('*****************************************') translations = read_translations() ui = MainWindow(path, config_dict, translations) ui.show() splash.finish(ui) sys.exit(app.exec_())
def main(splash=True): import os import pkg_resources import sys from PyQt5.QtWidgets import QApplication app = QApplication(sys.argv) imdir = pkg_resources.resource_filename("dcoraid", "img") if splash: from PyQt5.QtWidgets import QSplashScreen from PyQt5.QtGui import QPixmap from PyQt5.QtCore import QEventLoop splash_path = os.path.join(imdir, "splash.png") splash_pix = QPixmap(splash_path) splash = QSplashScreen(splash_pix) splash.setMask(splash_pix.mask()) splash.show() app.processEvents(QEventLoop.AllEvents, 300) import warnings from requests.packages.urllib3.exceptions import SubjectAltNameWarning # Ignore SubjectAltNameWarning for certificates in medical branding, # because they will show up in the dclab-compress-warnings log. warnings.filterwarnings("ignore", category=SubjectAltNameWarning) from PyQt5 import QtCore, QtGui from .gui import DCORAid # Set Application Icon icon_path = os.path.join(imdir, "icon.png") app.setWindowIcon(QtGui.QIcon(icon_path)) # Use dots as decimal separators QtCore.QLocale.setDefault(QtCore.QLocale(QtCore.QLocale.C)) window = DCORAid() if splash: splash.finish(window) sys.exit(app.exec_())
def main(): """ Main app loop :return: """ app = QApplication(sys.argv) # splash screen img_path = resource_path('splash.jpg') splash_img = QPixmap(img_path) splash = QSplashScreen(splash_img, QtCore.Qt.WindowStaysOnTopHint) splash.setMask(splash_img.mask()) splash.show() # do what we need to do version = get_game_version() # go forth with app app.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling) SPM = StellarisProfilesManager(db=db, game_version=version) splash.finish(SPM) sys.exit(app.exec_())
def main(fileName=None): app = QApplication(sys.argv) app.setOrganizationName("ErwinJr") app.setOrganizationDomain("princetonuniversity.github.io/ErwinJr2") app.setApplicationName("ErwinJr2") app.setWindowIcon(QIcon(os.path.join(basePath, 'images', 'EJpng256.png'))) # Create and display the splash screen splash_pix = QPixmap(os.path.join(basePath, 'images', 'splash.png')) splash = QSplashScreen(splash_pix) splash.setMask(splash_pix.mask()) splash.show() form = MainWindow(fileName) form.show() splash.finish(form) if sys.platform.startswith('win'): # The default font for win is not consistent with the OS app.setFont(QApplication.font("QMenu")) app.exec_()
def aboutDialog(app, version): # Create and display the about screen splash_pix = QPixmap(ARTWORK_DIR_NAME + 'AboutScreen.png') splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.showMessage('Version %s\n' % version, alignment=Qt.AlignHCenter + Qt.AlignBottom, color=Qt.black) splash.setMask(splash_pix.mask()) splash.show() splash.mousePressEvent = partial(closeDlg, splash) start = time() while splash.isActiveWindow() & (time() - start < 10): sleep(0.001) app.processEvents() if (splash.isActiveWindow()): splash.close()
def main(splash=True): import os import pkg_resources import sys import time from PyQt5.QtWidgets import QApplication from PyQt5.QtCore import QEventLoop app = QApplication(sys.argv) imdir = pkg_resources.resource_filename("dckit", "img") if splash: from PyQt5.QtWidgets import QSplashScreen from PyQt5.QtGui import QPixmap splash_path = os.path.join(imdir, "splash.png") splash_pix = QPixmap(splash_path) splash = QSplashScreen(splash_pix) splash.setMask(splash_pix.mask()) splash.show() # make sure Qt really displays the splash screen time.sleep(.07) app.processEvents(QEventLoop.AllEvents, 300) from PyQt5 import QtCore, QtGui from .main import DCKit # Set Application Icon icon_path = os.path.join(imdir, "icon.png") app.setWindowIcon(QtGui.QIcon(icon_path)) # Use dots as decimal separators QtCore.QLocale.setDefault(QtCore.QLocale(QtCore.QLocale.C)) window = DCKit() if splash: splash.finish(window) sys.exit(app.exec_())
def main(splash=True): import os import pkg_resources import sys from PyQt5.QtWidgets import QApplication from PyQt5.QtCore import QEventLoop # import before creating application import pyqtgraph # noqa: F401 app = QApplication(sys.argv) imdir = pkg_resources.resource_filename("shapeout2", "img") if splash: from PyQt5.QtWidgets import QSplashScreen from PyQt5.QtGui import QPixmap splash_path = os.path.join(imdir, "splash.png") splash_pix = QPixmap(splash_path) splash = QSplashScreen(splash_pix) splash.setMask(splash_pix.mask()) splash.show() # make sure Qt really displays the splash screen app.processEvents(QEventLoop.AllEvents, 300) from PyQt5 import QtCore, QtGui from .gui import ShapeOut2 # Set Application Icon icon_path = os.path.join(imdir, "icon.png") app.setWindowIcon(QtGui.QIcon(icon_path)) # Use dots as decimal separators QtCore.QLocale.setDefault(QtCore.QLocale(QtCore.QLocale.C)) window = ShapeOut2(*app.arguments()[1:]) if splash: splash.finish(window) sys.exit(app.exec_())
def start(self): #register signal handler signal.signal(signal.SIGINT, signal.SIG_DFL) #show splash screen splash = None if self.splash is not None: splash = QSplashScreen(self.splash) splash.setMask(self.splash.mask()) splash.show() #init modules if self.splash is not None: splash.showMessage("\n\n Importing utils...") self.init_utils(pre=True) if self.splash is not None: splash.showMessage("\n\n Importing devices...") self.init_devices() if self.splash is not None: splash.showMessage("\n\n Importing controllers...") self.init_controllers() if self.splash is not None: splash.showMessage("\n\n Importing widgets...") self.init_widgets() if self.splash is not None: splash.showMessage("\n\n Importing actions...") self.init_actions() if self.splash is not None: splash.showMessage("\n\n Importing utils...") self.init_utils(post=True) if self.splash is not None: splash.showMessage("\n\n finished...") splash.finish(self.janus.widgets["mainwindow"]) #start application self.init_done.emit() self.processEvents() self.janus.widgets["mainwindow"].show() retCode = self.exec_() sys.exit(retCode)
from PyQt5.QtCore import Qt, QCoreApplication # from PyQt5.QtWidgets import QToolTip from PyQt5.QtGui import QPixmap, QImage, QFont # from urllib.request import Request, urlopen # from urllib.error import URLError, HTTPError from vk_ui import Ui_MainWindow from vk_settings_ui import Ui_Form from add_ui import Ui_FormUrl from downloading_ui import Ui_FormDownload app = QApplication(sys.argv) image = QPixmap('./pic/111.jpg') splash = QSplashScreen(image) splash.setAttribute(QtCore.Qt.WA_DeleteOnClose) splash = QSplashScreen(image, Qt.WindowStaysOnTopHint) splash.setMask(image.mask()) font = QFont(splash.font()) font.setPointSize(font.pointSize() + 5) splash.setFont(font) splash.show() app.processEvents() # time.sleep(2) # splash.showMessage(splash.tr('Processing %1...{0}'),QtCore.Qt.AlignBottom | QtCore.Qt.AlignLeft, QtCore.Qt.white) # QtCore.QThread.msleep(1000) # QApplication.processEvents() for count in range(1, 6): # splash.showMessage(splash, str(count),QtCore.Qt.AlignBottom | QtCore.Qt.AlignLeft, QtCore.Qt.blue) splash.showMessage('Loading: ' + str(count), QtCore.Qt.AlignTop | QtCore.Qt.AlignLeft, QtCore.Qt.white) # print(str(count)) #
except IOError: pass # GUI message error_box = QMessageBox() error_box.setWindowTitle("Error occured") error_box.setText(str(notice) + str(msg)) error_box.exec_() if __name__ == "__main__": import sys # Global exceptions sys.excepthook = excepthook app = QApplication(sys.argv) # Splash screen splash_pix = QPixmap('resources/splash.jpg') splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) splash.show() app.processEvents() # Start m = Hitagi() splash.finish(m) sys.exit(app.exec())
class MainWindow(QMainWindow,Ui_MainWindow): def __init__(self): super(MainWindow, self).__init__() self.start_logo() self.setupUi(self) self.sysencoding =sys.stdout.encoding #self.centralWidget = PyPreviewer(self) #self.setCentralWidget(self.centralWidget) self.setupEditor() self.setWindowIcon(QIcon('PyPreviewer.ico')) #메뉴 이벤트 생성 self.createEvent() self.dirty = False self.plainTextEdit_2.textChanged.connect(self.setDirty) self.fileName = None self.plainTextEdit_2.setTabStopWidth(35) self.plainTextEdit_2.setPlainText("# -*- coding: utf-8 -*-\n# 반갑습니다~\n# #은 파이썬에서 주석입니다.\nprint(\"이 부분은 출력창입니다.\")\nprint(\"구구단 예제\")\nfor i in range(2,10):\n\tprint(i,\"단\")\n\tfor j in range(2,10):\n\t\tprint(i,\"X\", j, \"=\", i*j)\n# 파이썬 실행은 아래 실행버튼을 눌러주세요.\n# 파이썬 학습 관련 및 예제는 왼쪽 화면을 이용하시기 바랍니다.") #web view #self.exampleView.load(QUrl("http://www.google.com")) self.startfilepath=os.getcwd() +"/PyStudy_web/Main.html" self.exampleView.load(QUrl.fromLocalFile(self.startfilepath)) self.locationEdit = QLineEdit(self) self.locationEdit.setSizePolicy(QSizePolicy.Expanding, self.locationEdit.sizePolicy().verticalPolicy()) self.locationEdit.returnPressed.connect(self.changeLocation) toolBar = QToolBar() self.addToolBar(toolBar) self.insertToolBarBreak(toolBar) toolBar.addAction(self.exampleView.pageAction(QWebPage.Back)) toolBar.addAction(self.exampleView.pageAction(QWebPage.Forward)) toolBar.addAction(self.action_myHome) toolBar.addAction(self.exampleView.pageAction(QWebPage.Reload)) #toolBar.addAction(self.exampleView.pageAction(QWebPage.Stop)) toolBar.addWidget(self.locationEdit) #사용자 입력 파이썬 파일 실행 print ('Connecting process') self.process = QProcess(self) self.process.setProcessChannelMode(QProcess.SeparateChannels) self.process.setInputChannelMode(QProcess.ManagedInputChannel) self.process.readyReadStandardOutput.connect(self.stdoutReady) self.process.readyReadStandardError.connect(self.stderrReady) self.process.started.connect(lambda: print('ExampleProgramStarted!')) self.process.finished.connect(lambda:print('ExampleProgramFinished!')) print('Starting process') #self.process.start('python', ['ExampleTest.py']) def start_logo(self): img_logo = QPixmap('pystudylogo.png') self.splash = QSplashScreen(img_logo, Qt.WindowStaysOnTopHint) self.splash.setMask(img_logo.mask()) self.splash.show() time.sleep(1.8) self.splash.close() def show_logo(self): img_logo = QPixmap('pystudylogo.png') self.splash = QSplashScreen(img_logo, Qt.WindowStaysOnTopHint) self.splash.setMask(img_logo.mask()) self.splash.show() self.splash.repaint() def createEvent(self): self.ProgramRunButton.clicked.connect(self.clickAction_ProgramRunButton) self.ProgramStopButton.clicked.connect(self.clickAction_ProgramStopButton) self.actionRun.triggered.connect(self.clickAction_ProgramRunButton) self.actionStop.triggered.connect(self.clickAction_ProgramStopButton) self.ClearButton.clicked.connect(self.clickAction_ProgramEraseButton) self.actionClear.triggered.connect(self.clickAction_ProgramEraseButton) self.actionNew_File.triggered.connect(self.clickAction_fileNew) self.actionFile_Open.triggered.connect(self.clickAction_fileOpen) self.actionFile_Save.triggered.connect(self.clickAction_fileSave) self.actionFile_Save_as.triggered.connect(self.clickAction_fileSaveAs) self.action_example.triggered.connect(self.clickAction_exampleOpen) self.actionPythonHelp.triggered.connect(self.clickAction_PythonHelp) self.actionHelp.triggered.connect(self.clickAction_ProgramHelp) self.MessagepushButton.clicked.connect(self.clickAction_MessagePushButton) self.actionStyleSheet_default.triggered.connect(self.clickAction_styleDefault) self.actionStyleSheet_Black.triggered.connect(self.clickAction_styleBlack) self.actionStyleSheet_Load.triggered.connect(self.clickAction_styleLoad) self.actionAbout_PyStudy.triggered.connect(self.show_logo) self.action_myHome.triggered.connect(self.go_myHome) self.action_exit.triggered.connect(self.close) def setDirty(self): #'On change of text in textEdit window, set the flag "dirty" to True'' if self.dirty: return True self.dirty = True self.updateStatus('소스 수정중...') def clearDirty(self): #'''Clear the dirty flag and update status''' self.dirty = False def updateStatus(self, message): if self.fileName is not None: flbase = os.path.basename(self.fileName) self.setWindowTitle("PyStudy Simple Editor - " + flbase + "[*]" ) self.statusBar().showMessage(message, 3000) self.setWindowModified(self.dirty) def clickAction_exampleOpen(self): fname, filter = QFileDialog.getOpenFileName(self, "예제파일 열기창", '.', "HTML File(*.html *.htm)") if not (fname == ""): #self.exampleView.load(QUrl(fname)) self.exampleView.setUrl(QUrl.fromLocalFile(fname)) #self.plainTextEdit_2.setPlainText(codecs.open(fname, "r", "utf-8" ).read()) #self.fileName = fname else: return self.updateStatus('example File opened.') def clickAction_exampleDirectOpen(self,fname): if not (fname == ""): fname = os.getcwd()+r"\\"+fname print(fname) self.exampleView.setUrl(QUrl.fromLocalFile(fname)) else: return self.updateStatus('example File opened.') def clickAction_fileNew(self): #'''Clear the editor window for a new file with name specified in fileSaveAs method.''' self.plainTextEdit_2.clear() self.statusBar().showMessage('새 소스파일 생성', 8000) self.dirty = False self.fileName = None def clickAction_fileOpen(self): fname, filter = QFileDialog.getOpenFileName(self, "소스파일 열기창", '.', "Python File(*.py)") if not (fname == ""): self.plainTextEdit_2.setPlainText(codecs.open(fname, "r", "utf-8" ).read()) self.fileName = fname else: return self.clearDirty() self.updateStatus('File opened.') def clickAction_fileSave(self): if self.fileName is None: return self.clickAction_fileSaveAs() else: fname = self.fileName fl = codecs.open(fname, "w", "utf-8" ) tempText = self.plainTextEdit_2.toPlainText() if tempText: fl.write(tempText) fl.close() self.clearDirty() self.updateStatus('Saved file') return True else: self.statusBar().showMessage('파일 저장 실패 ...', 5000) return False def clickAction_fileSaveAs(self): path = self.fileName if self.fileName is not None else "." fname,filter = QFileDialog.getSaveFileName(self, "다른이름으로 저장", path, "Python File(*.py)") if fname: if "." not in fname: fname += ".py" self.fileName = fname self.clickAction_fileSave() self.statusBar().showMessage('SaveAs file' + fname, 8000) self.clearDirty() def clickAction_ProgramRunButton(self): self.clickAction_fileSave() self.process.start('python', [self.fileName],QIODevice.ReadWrite) def clickAction_ProgramStopButton(self): self.process.kill() self.append_plainTextEdit_3("\n\n프로세스 정지 with exit code "+str(self.process.exitCode())+"\n\n") def clickAction_ProgramEraseButton(self): self.plainTextEdit_3.clear() def append_plainTextEdit_3(self, text): cursor = self.plainTextEdit_3.textCursor() cursor.movePosition(cursor.End) cursor.insertText(text) #self.output.ensureCursorVisible() def stdoutReady(self): if self.sysencoding == "cp949": text = str(self.process.readAllStandardOutput(), "cp949")#독립실행시 elif self.sysencoding == "UTF-8": text = str(self.process.readAllStandardOutput(), "utf-8")#pycharm else: text = str(self.process.readAllStandardOutput(), "cp949")#독립실행시 self.append_plainTextEdit_3(text) def stderrReady(self): if self.sysencoding == "cp949": text = str(self.process.readAllStandardError(), "cp949")#독립실행시 elif self.sysencoding == "UTF-8": text = str(self.process.readAllStandardError(), "utf-8")#pycharm else: text = str(self.process.readAllStandardError(), "cp949")#독립실행시 self.append_plainTextEdit_3(text) def clickAction_PythonHelp(self): temppath=os.path.abspath('..')+r"\파이썬도움말\animation.py" tempoption = os.path.abspath('..')+r"\파이썬도움말" pythonhelp_process=QProcess() pythonhelp_process.start('python', [temppath,tempoption]) pythonhelp_process.started() # TypeError: native Qt signal is not callable def clickAction_MessagePushButton(self): temp = self.messagelineEdit.text() self.append_plainTextEdit_3(temp) self.append_plainTextEdit_3("\n") bArray = QByteArray() if self.sysencoding == "cp949": bArray.append(temp.encode(encoding='cp949',errors='ignore'))#독립실행시 elif self.sysencoding == "UTF-8": bArray.append(temp.encode(encoding='utf-8',errors='ignore'))#pycharm else: bArray.append(temp.encode(encoding='cp949',errors='ignore'))#독립실행시 bArray.append("\n") if( self.process.write(bArray) == -1): print("chlidprocess write error") self.messagelineEdit.clear() def clickAction_styleLoad(self): fname, filter = QFileDialog.getOpenFileName(self, "QT스타일시트파일 불러오기", '.', "Qt-StyleSheet(*.qss)") if fname: file = QFile(fname) file.open(QFile.ReadOnly) styleSheet = file.readAll() styleSheet = str(styleSheet, encoding='utf8') # Python v3. self.setStyleSheet(styleSheet) print ("test") def clickAction_styleDefault(self): self.set_StyleSheet("default") def clickAction_styleBlack(self): self.set_StyleSheet("black") def clickAction_ProgramHelp(self): self.startfilepath=os.getcwd() +"/PyStudy_web/Pystudy.html" self.exampleView.load(QUrl.fromLocalFile(self.startfilepath)) def set_StyleSheet(self, sheetName): if sheetName: file = QFile('stylesheet/%s.qss' % sheetName.lower()) file.open(QFile.ReadOnly) styleSheet = file.readAll() styleSheet = str(styleSheet, encoding='utf8') # Python v3. self.setStyleSheet(styleSheet) def setupEditor(self): font = QFont() font.setFamily('Courier') font.setFixedPitch(True) font.setPointSize(10) self.editor = self.plainTextEdit_2 self.editor.setFont(font) self.highlighter = Highlighter(self.editor.document()) def changeLocation(self): url = QUrl.fromUserInput(self.locationEdit.text()) self.exampleView.load(url) self.exampleView.setFocus() def go_myHome(self): self.exampleView.load(QUrl.fromLocalFile(self.startfilepath)) self.exampleView.setFocus()
def start_ide(app, filenames, projects_path, extra_plugins, linenos): """Load all the settings necessary before loading the UI, and start IDE.""" QCoreApplication.setOrganizationName('NINJA-IDE') QCoreApplication.setOrganizationDomain('NINJA-IDE') QCoreApplication.setApplicationName('NINJA-IDE') app.setWindowIcon(QIcon(":img/icon")) # Check if there is another session of ninja-ide opened # and in that case send the filenames and projects to that session running = ipc.is_running() start_server = not running[0] if running[0] and (filenames or projects_path): sended = ipc.send_data(running[1], filenames, projects_path, linenos) running[1].close() if sended: sys.exit() else: running[1].close() # Create and display the splash screen splash_pix = QPixmap(":img/splash") splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) splash.show() app.processEvents() # Set the cursor to unblinking #if not settings.IS_WINDOWS: #app.setCursorFlashTime(0) #Set the codec for strings (QString) ##QTextCodec.setCodecForCStrings(QTextCodec.codecForName('utf-8')) #Translator qsettings = ide.IDE.ninja_settings() data_qsettings = ide.IDE.data_settings() language = QLocale.system().name() lang = qsettings.value('preferences/interface/language', defaultValue=language, type='QString') + '.qm' lang_path = file_manager.create_path(resources.LANGS, lang) if file_manager.file_exists(lang_path): settings.LANGUAGE = lang_path translator = QTranslator() if settings.LANGUAGE: translator.load(settings.LANGUAGE) app.installTranslator(translator) qtTranslator = QTranslator() qtTranslator.load( "qt_" + language, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(qtTranslator) #Loading Syntax splash.showMessage("Loading Syntax", Qt.AlignRight | Qt.AlignTop, Qt.black) json_manager.load_syntax() #Read Settings splash.showMessage("Loading Settings", Qt.AlignRight | Qt.AlignTop, Qt.black) #Set Stylesheet style_applied = False print(settings.NINJA_SKIN) if settings.NINJA_SKIN not in ('Default'): file_name = ("%s.qss" % settings.NINJA_SKIN) qss_file = file_manager.create_path(resources.NINJA_THEME_DOWNLOAD, file_name) if file_manager.file_exists(qss_file): with open(qss_file) as fileaccess: qss = fileaccess.read() app.setStyleSheet(qss) style_applied = True if not style_applied: if settings.NINJA_SKIN == 'Default': with open(resources.NINJA_THEME) as fileaccess: qss = fileaccess.read() app.setStyleSheet(qss) #Loading Schemes splash.showMessage("Loading Schemes", Qt.AlignRight | Qt.AlignTop, Qt.black) scheme = qsettings.value('preferences/editor/scheme', "default", type='QString') if scheme != 'default': scheme = file_manager.create_path(resources.EDITOR_SKINS, scheme + '.color') if file_manager.file_exists(scheme): resources.CUSTOM_SCHEME = json_manager.parse(open(scheme)) #Loading Shortcuts resources.load_shortcuts() #Loading GUI splash.showMessage("Loading GUI", Qt.AlignRight | Qt.AlignTop, Qt.black) ninjaide = ide.IDE(start_server) #Showing GUI ninjaide.show() #OSX workaround for ninja window not in front try: ninjaide.raise_() except: pass # I really dont mind if this fails in any form #Loading Session Files splash.showMessage("Loading Files and Projects", Qt.AlignRight | Qt.AlignTop, Qt.black) #First check if we need to load last session files if qsettings.value('preferences/general/loadFiles', True, type=bool): #Files in Main Tab files = data_qsettings.value('lastSession/openedFiles', []) tempFiles = [] if files: for file_ in files: fileData = tuple(file_) if fileData: tempFiles.append(fileData) files = tempFiles # Recent Files recent_files = data_qsettings.value('lastSession/recentFiles', []) #Current File current_file = data_qsettings.value( 'lastSession/currentFile', '', type='QString') #Projects projects = data_qsettings.value('lastSession/projects', []) else: files = [] recent_files = [] current_file = '' projects = [] #Include files received from console args file_with_nro = list([(f[0], (f[1] - 1, 0), 0) for f in zip(filenames, linenos)]) file_without_nro = list([(f, (0, 0), 0) for f in filenames[len(linenos):]]) files += file_with_nro + file_without_nro #Include projects received from console args if projects_path: projects += projects_path #FIXME: IMPROVE THIS WITH THE NEW WAY OF DO IT ninjaide.load_session_files_projects(files, projects, current_file, recent_files) #Load external plugins #if extra_plugins: #ninjaide.load_external_plugins(extra_plugins) splash.finish(ninjaide) ninjaide.notify_plugin_errors() ninjaide.show_python_detection()
def start(filenames=None, projects_path=None, extra_plugins=None, linenos=None): app = QApplication(sys.argv) QCoreApplication.setOrganizationName('NINJA-IDE') QCoreApplication.setOrganizationDomain('NINJA-IDE') QCoreApplication.setApplicationName('NINJA-IDE') app.setWindowIcon(QIcon(resources.IMAGES['icon'])) # Check if there is another session of ninja-ide opened # and in that case send the filenames and projects to that session running = ipc.is_running() start_server = not running[0] if running[0] and (filenames or projects_path): sended = ipc.send_data(running[1], filenames, projects_path, linenos) running[1].close() if sended: sys.exit() else: running[1].close() # Create and display the splash screen splash_pix = QPixmap(resources.IMAGES['splash']) splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) splash.show() app.processEvents() # Set the cursor to unblinking if sys.platform != 'win32': app.setCursorFlashTime(0) #Set the codec for strings (QString) print("codec:", QTextCodec.codecForName('utf-8')) #QTextCodec.setCodecForCStrings(QTextCodec.codecForName('utf-8')) #Translator #qsettings = QSettings() qsettings = QSettings(resources.SETTINGS_PATH, QSettings.IniFormat) language = QLocale.system().name() lang = qsettings.value('preferences/interface/language', defaultValue=language, type='QString') + '.qm' lang_path = file_manager.create_path(resources.LANGS, lang) if file_manager.file_exists(lang_path): settings.LANGUAGE = lang_path elif file_manager.file_exists(file_manager.create_path( resources.LANGS_DOWNLOAD, lang)): settings.LANGUAGE = file_manager.create_path( resources.LANGS_DOWNLOAD, lang) translator = QTranslator() if settings.LANGUAGE: translator.load(settings.LANGUAGE) app.installTranslator(translator) qtTranslator = QTranslator() qtTranslator.load("qt_" + language, QLibraryInfo.location(QLibraryInfo.TranslationsPath)) app.installTranslator(qtTranslator) #Loading Syntax splash.showMessage("Loading Syntax", Qt.AlignRight | Qt.AlignTop, Qt.black) json_manager.load_syntax() #Read Settings splash.showMessage("Loading Settings", Qt.AlignRight | Qt.AlignTop, Qt.black) settings.load_settings() #Set Stylesheet style_applied = False if settings.NINJA_SKIN not in ('Default', 'Classic Theme'): file_name = ("%s.qss" % settings.NINJA_SKIN) qss_file = file_manager.create_path(resources.NINJA_THEME_DOWNLOAD, file_name) if file_manager.file_exists(qss_file): with open(qss_file) as f: qss = f.read() app.setStyleSheet(qss) style_applied = True if not style_applied: if settings.NINJA_SKIN == 'Default': with open(resources.NINJA_THEME) as f: qss = f.read() else: with open(resources.NINJA__THEME_CLASSIC) as f: qss = f.read() app.setStyleSheet(qss) #Loading Schemes splash.showMessage("Loading Schemes", Qt.AlignRight | Qt.AlignTop, Qt.black) scheme = qsettings.value('preferences/editor/scheme', "default", type='QString') if scheme != 'default': scheme = file_manager.create_path(resources.EDITOR_SKINS, scheme + '.color') if file_manager.file_exists(scheme): resources.CUSTOM_SCHEME = json_manager.parse(open(scheme)) #Loading Shortcuts resources.load_shortcuts() #Loading GUI splash.showMessage("Loading GUI", Qt.AlignRight | Qt.AlignTop, Qt.black) ide = IDE(start_server) #Showing GUI ide.show() #Loading Session Files splash.showMessage("Loading Files and Projects", Qt.AlignRight | Qt.AlignTop, Qt.black) #Files in Main Tab main_files = qsettings.value('openFiles/mainTab', []) if main_files is not None: mainFiles = list(main_files) else: mainFiles = list() tempFiles = [] for file_ in mainFiles: fileData = list(file_) if fileData: lineno = fileData[1] tempFiles.append((fileData[0], lineno)) mainFiles = tempFiles #Files in Secondary Tab sec_files = qsettings.value('openFiles/secondaryTab', []) if sec_files is not None: secondaryFiles = list(sec_files) else: secondaryFiles = list() tempFiles = [] for file_ in secondaryFiles: fileData = list(file_) lineno = fileData[1] tempFiles.append((fileData[0], lineno)) secondaryFiles = tempFiles # Recent Files recent = qsettings.value('openFiles/recentFiles', []) if recent is not None: recent_files = list(recent) else: recent_files = list() recent_files = [file_ for file_ in recent_files] #Current File current_file = qsettings.value('openFiles/currentFile', '', type='QString') #Projects projects_list = qsettings.value('openFiles/projects', []) if projects_list is not None: projects = list(projects_list) else: projects = list() projects = [project for project in projects] #Include files received from console args file_with_nro = list([(f[0], f[1] - 1) for f in zip(filenames, linenos)]) file_without_nro = list([(f, 0) for f in filenames[len(linenos):]]) mainFiles += file_with_nro + file_without_nro #Include projects received from console args if projects_path: projects += projects_path ide.load_session_files_projects(mainFiles, secondaryFiles, projects, current_file, recent_files) #Load external plugins if extra_plugins: ide.load_external_plugins(extra_plugins) splash.finish(ide) ide.notify_plugin_errors() ide.show_python_detection() sys.exit(app.exec_())
class tempapp(QMainWindow, tempwin): def __init__(self,parent=None): #splash screen initialisation self.splash_pix = QPixmap('data/loading.jpg') self.splash = QSplashScreen(self.splash_pix, QtCore.Qt.WindowStaysOnTopHint) self.splash.setMask(self.splash_pix.mask()) self.splash.show() super(tempapp, self).__init__(parent) self.setupUi(self) def main(self): #launching program self.hide() self.launch() def launch(self): #reading configuration config=open('data/configure') config=config.readlines() envir=main.principal self.result={} for info in range(len(config)) : temp=config[info].split('=') temp[1]=temp[1].split('\n')[0] self.result[temp[0]]=temp[1] if self.result['db']=='' : #if no databatse, asking user for creating/pointing h=QMessageBox(parent=self, text="No DB has been pointed. \nDo you want to create a new database or to load an existing database ?") h.addButton(QPushButton('Close'), QMessageBox.YesRole) h.addButton(QPushButton('Load an Existing DB'), QMessageBox.NoRole) h.addButton(QPushButton('New DB'), QMessageBox.HelpRole) self.splash.hide() tot = h.exec_() if tot==0 : self.terminer() if tot==1 : self.loaddb() if tot==2 : self.newdb() else : #if already configured : checking if the DB still exist if os.path.exists(self.result['db'])==True : None else : #if db do not exist : delete configuration and reboot program self.splash.hide() h=QMessageBox(parent=self, text="Corrupted file or non existent : Deleting configuration") self.result['db']="" new_conf='' for i in self.result : new_conf+='%s=%s\n' % (i,self.result[i]) config=open('data/configure','w') config.write(new_conf) config.close() h.exec_() python = sys.executable os.execl(python, python, * sys.argv) #launching program if all checkpoints are ok self.splash.hide() prog=main.principal() prog.main() sys.exit(app.exec_()) def loaddb (self) : #loading db file fname=QFileDialog.getOpenFileName(self, 'Choose a DB', '/','SQLite Databse (*.sqlite)')[0] if fname=='' : z=QMessageBox(parent=self, text="No DB has been selected, closing program") z.exec_() z.exec_() self.terminer() isvalid=cursor.verif(str(fname)) #checking is the DB is valid if isvalid==False : z=QMessageBox(parent=self, text="Wrong File/File Corruption. \nClosing programm") z.exec_() self.terminer() else : #writiing new configuration self.result['db']=str(fname) new_conf='' for i in self.result : new_conf+='%s=%s\n' % (i,self.result[i]) config=open('data/configure','w') config.write(new_conf) config.close() python = sys.executable os.execl(python, python, * sys.argv) def terminer (self) : #QApplication.quit() #sys.exit(app.exec_()) sys.exit(0) def newdb (self) : #new db creation fname=QFileDialog.getSaveFileName(self, 'Create a DB', '/','SQLite Databse (*.sqlite)')[0] shutil.copy('data/model.sqlite',fname) self.result['db']=str(fname) new_conf='' for i in self.result : new_conf+='%s=%s\n' % (i,self.result[i]) config=open('data/configure','w') config.write(new_conf) config.close() python = sys.executable os.execl(python, python, * sys.argv)
class Example(QMainWindow, Ui_MainWindow): DEBUG = True # Если TRUE, то выводим вспомогательную информацию в консоль result = {} # Variable for JSON photo_avg = [] # Сюда помещаются картинки приблизительно равные размеру, заданному в переменной photo_size photo_date = [] # Сюда помещаются даты, когда были выложены картинки photo_max = [] # Сюда помещаются самые большие картинки current_page = 1 # Текущая страница просмоторщика label = {} # Массив элементов label loading_image = [] # Сюда помещаем список загруженных фото button = {} # Массив кнопок icon = {} # Массив иконок для button pic_date = {} # Массив времени публикации для картинок prev_mode = 0 # Флаг где находимся. 0 - если в превиюхах. 1 - если в режима просмотра большой картинки group_id = 0 # ID группы, которую будем загружать dict_count = {} # Переменная через которую сопоставляется выделенный элемент в listWidget и ID для загрузки first_run = 0 # Если приложение запустилось первый раз, то при нажатии Load загрузить аватарки групп loading_error = False # Флаг удачной загрузки def __init__(self, MainWindow): super().__init__() # Сконфигурировать интерфейс методом из базового класса MainWindow self.setupUi(MainWindow) # Показываем заставку при загрузке self.downloading('Interface is initialized...') self.wait() # Подключить созданные нами слоты к виджетам self.connect_slots() try: fp = open("settings.json", "r") try: self.settings = json.load(fp) finally: fp.close() # Количество загружаемых страниц self.num_pages = self.settings['settings']['pages_load'][0]['num_pages'] # Количество строк self.num_line = self.settings['settings']['preview'][0]['num_line'] # Количество столбцов self.num_column = self.settings['settings']['preview'][0]['num_column'] # Размер preview self.photo_size = self.settings['settings']['preview'][0]['prev_size'] # Путь (каталог на диске) для сохранения изображений self.pic_save_path = self.settings['settings']['pic_save'][0]['path'] # Прокси self.proxy_host = self.settings['settings']['proxies'][0]['host'] self.proxy_port = self.settings['settings']['proxies'][0]['port'] self.proxy_username = self.settings['settings']['proxies'][0]['username'] self.proxy_password = self.settings['settings']['proxies'][0]['password'] if not self.proxy_host: self.proxies = {} self.auth = HTTPProxyAuth('', '') if self.proxy_host and self.proxy_port: self.proxies = {"http": "http://" + self.proxy_host + ":" + self.proxy_port, "https": "https://" + self.proxy_host + ":" + self.proxy_port} self.auth = HTTPProxyAuth('', '') if self.proxy_host and self.proxy_port and self.proxy_username and self.proxy_password: self.proxies = {"http": "http://" + self.proxy_username + ':' + self.proxy_password + '@' + self.proxy_host + ':' + self.proxy_port, "https": "https://" + self.proxy_username + ':' + self.proxy_password + '@' + self.proxy_host + ':' + self.proxy_port,} self.auth = HTTPProxyAuth(self.proxy_username, self.proxy_password) if self.DEBUG: print('Proxy: ' + str(self.proxies)) # Заполняем listVidget группами без аватарки self.group_fill() except IOError: self.statusbar.showMessage('settings.json not found!') self.num_pages = 2 self.num_line = 2 self.num_column = 2 self.photo_size = 50 # self.modalWindowDownloading.close() self.splash.close() # Подключаем слоты к виджетам def connect_slots(self): self.actionLoad.triggered.connect(self.load_pic) self.actionNext.triggered.connect(self.next_pic) self.actionPreview.triggered.connect(self.preview_pic) self.actionRefresh.triggered.connect(self.refresh) self.actionSettings.triggered.connect(self.settings_window) self.actionQuit.triggered.connect(qApp.quit) self.actionAbout.triggered.connect(self.about_vk) self.actionAbout_Qt.triggered.connect(self.about_qt) self.actionHelp.triggered.connect(self.help) self.actionOpen_saving_folder.triggered.connect(self.open_saving_folder) QMainWindow.resizeEvent = self.scale_pic # Заполняем listWidget списком групп def group_fill(self): self.listWidgetMain.clear() # Очищаем listWidgetMain try: fp = open("settings.json", "r") try: self.settings = json.load(fp) finally: fp.close() except IOError: self.statusbar.showMessage('settings.json not found!') # Заполняем listWidget списком групп self.dict = self.settings['vk_groups'] # print('DICT: ' + str(self.dict)) n = 0 self.dict_count = {} # Обнуляем for i in self.dict: self.listWidgetMain.addItem(self.dict[i]) self.dict_count[n] = str(i) n += 1 # Заполняем listWidget аватарками def group_fill_ava(self): self.listWidgetMain.clear() # Очищаем listWidgetMain # Формируем список групп для которых нужно загрузить аватарку и выполняем запрос text = '' for i in range(len(self.dict_count)): text = text + str(self.dict_count[i]) if i < len(self.dict_count) - 1: text = text + ',' # Загружаем, парсим JSON и вытаскиваем аватарки групп url_ava = 'https://api.vk.com/method/groups.getById?v=5.32&group_ids=' + text if self.DEBUG: print('Get JSON Avatars URL: ' + url_ava) self.splash.showMessage('Downloading Avatars', QtCore.Qt.AlignTop | QtCore.Qt.AlignCenter, QtCore.Qt.black) try: response = requests.get(url_ava, proxies=self.proxies, auth=self.auth) except IOError: if self.DEBUG: print('ERROR Loading avatars!') self.group_fill() self.loading_error = True self.splash.close() if self.loading_error == False: result = json.loads(response.text) # Заполняем listWidget аватарками групп loading_ava = [] for i in range(len(self.dict_count)): if self.DEBUG: print(str(i) + ')' + result['response'][i]['photo_50']) self.splash.showMessage(os.path.basename(result['response'][i]['photo_50']), QtCore.Qt.AlignTop | QtCore.Qt.AlignCenter, QtCore.Qt.black) response = requests.get(result['response'][i]['photo_50'], proxies=self.proxies, auth=self.auth) image = QImage() image.loadFromData(response.content) loading_ava.append(image) item = QtWidgets.QListWidgetItem() icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(image), QtGui.QIcon.Normal, QtGui.QIcon.Off) item.setIcon(icon) self.listWidgetMain.addItem(item) # Заполняем listWidget названиями групп n = 0 for i in self.dict: item = self.listWidgetMain.item(n) item.setText(self.dict[i]) # item.setText(str(i) + ':' + self.dict[i]) # self.listWidgetMain.addItem(str(i) + ':' + self.dict[i]) n += 1 # Открываем каталок загрузок в текущем проводнике def open_saving_folder(self): if platform.system() == 'Linux': try: subprocess.check_call(['xdg-open', self.pic_save_path]) except subprocess.CalledProcessError: QMessageBox.critical(window, 'Error','Unable to open dir\n"File->Settings->Path"') # Помощь def help(self): print(self.dict_count) # # self.group_id = self.dict_count[self.listWidgetMain.currentRow()] # print(self.group_id) # # self.downloading() # Увеличение картинки при растяжении окна def scale_pic(self, e): if self.prev_mode == 1: self.big_check() self.label.setPixmap(QtGui.QPixmap(self.image).scaled( self.width_my, self.height_my, QtCore.Qt.KeepAspectRatio)) # Указываем путь для сохранения картинок def tool_button(self, e): print('tool button') fname = QFileDialog.getExistingDirectory(self, 'Dir', self.pic_save_path) if fname: self.lineEdit.setText(fname) # Обновить картинку def refresh(self): print('refresh') # self.load_big() self.big_check() self.label.setPixmap(QtGui.QPixmap(self.image).scaled(self.width_my, self.height_my, QtCore.Qt.KeepAspectRatio)) # self.label.mousePressEvent = self.close_full_pic_view self.actionRefresh.setEnabled(True) def about_vk(self): QMessageBox.about(window, 'About VK Girls', 'VK Girls v.1.0') def about_qt(self): QMessageBox.aboutQt(window) # Загружаем картинки при нажатии кнопки Load def load_pic(self): # Проверяем есть ли и-нет соединение try: requests.get('http://vk.com', proxies=self.proxies, auth=self.auth) except IOError: if self.DEBUG: print('Check internet connection') msgBox = QMessageBox( QMessageBox.Critical, 'Error', 'Check internet connection', QMessageBox.NoButton) msgBox.exec_() else: print('Поехали') self.current_page = 1 self.load_pic_list() self.load_pic_prev() self.draw_pic() self.check_buttons() self.statusbar.showMessage('Page: ' + str(self.current_page)) self.loading_error = False # Загружаем следующую картинку при нажатии кнопки Next def next_pic(self): # Если находимся в режиме preview, то загружаем следующие if self.prev_mode == 0: # Показываем заставку при загрузке self.downloading('Loading next pics...') self.wait() self.current_page += 1 self.load_pic_prev() self.draw_pic() self.check_buttons() self.statusbar.showMessage('Page: ' + str(self.current_page)) self.splash.close() # Если находимся в режима просмотра большой картинки, то показываем следующую else: print('--->') if self.photo_max_id < len(self.photo_max) - 1: self.photo_max_id += 1 self.load_big() self.big_check() self.label.setPixmap(QtGui.QPixmap(self.image).scaled( self.width_my, self.height_my, QtCore.Qt.KeepAspectRatio)) # Если фото последнее и режим просмотра большого фото,то делаем кнопку next в меню и на панели неактивной if self.photo_max_id >= len(self.photo_max) - 1 and self.prev_mode == 1: self.actionNext.setEnabled(False) else: self.actionNext.setEnabled(True) # Если фото первое и режим просмотра большого фото,то делаем кнопку preview неактивной if self.photo_max_id <= 0 and self.prev_mode == 1: self.actionPreview.setEnabled(False) else: self.actionPreview.setEnabled(True) # Загружаем предыдущую картинку при нажатии кнопки Preview def preview_pic(self): if self.prev_mode == 0: # Показываем заставку при загрузке self.downloading('Loading prev pics...') self.wait() self.current_page -= 1 self.load_pic_prev() self.draw_pic() self.check_buttons() self.statusbar.showMessage('Page: ' + str(self.current_page)) self.splash.close() else: print('<---') if self.photo_max_id > 0: self.photo_max_id -= 1 self.load_big() self.big_check() # Сравниваем его размер с размером окна self.label.setPixmap(QtGui.QPixmap(self.image).scaled( self.width_my, self.height_my, QtCore.Qt.KeepAspectRatio)) # Если фото последнее и режим просмотра большого фото,то делаем кнопку next в меню и на панели неактивной if self.photo_max_id >= len(self.photo_max) - 1 and self.prev_mode == 1: self.actionNext.setEnabled(False) else: self.actionNext.setEnabled(True) # Если фото первое и режим просмотра большого фото,то делаем кнопку preview неактивной if self.photo_max_id <= 0 and self.prev_mode == 1: self.actionPreview.setEnabled(False) else: self.actionPreview.setEnabled(True) # Просмотр большого фото def full_pic_view(self, event): # Показываем заставку при загрузке self.downloading('Loading full image...') self.wait() """Загрузка и просмотр большого изображения""" self.prev_mode = 1 # Выставляем флаг, что мы перешли в режим просмотра большого фото self.wat_is_button() # Какая кнопка с preview была нажата, чтобы загрузить большое фото self.clear_screen() # Удаляем все кнопки с изображениями (очищаем окно) self.check_buttons() # Проверяем флаги кнопок в меню и тулбаре # self.win_size() # Определяем текущий размер окна # Ищем большое фото mult_num = self.num_line * self.num_column self.photo_max_id = self.current_page *\ mult_num - mult_num + self.sender1 # Создаем Label в котором будем выводить фото self.label = QtWidgets.QLabel(self.centralwidget) self.label.setAlignment(QtCore.Qt.AlignCenter) self.label.setObjectName("label") self.load_big() # Загружаем большое фото self.big_check() # Сравниваем его размер с размером окна self.label.setPixmap(QtGui.QPixmap(self.image).scaled( self.width_my, self.height_my, QtCore.Qt.KeepAspectRatio)) self.gridLayout_2.addWidget(self.label, 0, 0, 0, 0) self.label.mousePressEvent = self.close_full_pic_view # Если фото последнее, то делаем кнопку next в меню и на панели неактивной if self.photo_max_id >= len(self.photo_max) - 1: self.actionNext.setEnabled(False) # Если фото первое, то делаем кнопку preview неактивной if self.photo_max_id == 0: self.actionPreview.setEnabled(False) # Закрываем заставку self.splash.close() # Загрузка большого фото def load_big(self): """Загружаем большое фото""" # req = Request(self.photo_max[self.photo_max_id]) # response = urlopen(req).read() # # Показываем заставку при загрузке # self.downloading() # self.wait() response = requests.get(self.photo_max[self.photo_max_id], proxies=self.proxies, auth=self.auth) self.image = QImage() self.image.loadFromData(response.content) # self.modalWindowDownloading.close() # Подгоняем размер картинки под размер окна def big_check(self): # Определяем размер окна, чтобы оно не растягивалось, если размер изображения больше, чем размер окна self.win_size() # Сверяем размер большого фото с размером окна if self.image.width() < self.width: self.width_my = self.image.width() self.height_my = self.image.height() else: if self.DEBUG: print('BIG_width') self.width_my = self.width - self.width * 0.1 self.height_my = self.height - self.height * 0.1 if self.height_my < self.height: if self.DEBUG: print('do nothing') else: if self.DEBUG: print('BIG_height') self.width_my = self.width - self.width * 0.1 self.height_my = self.height - self.height * 0.1 if self.DEBUG: print('Ширина:{0}; Высота:{1}'.format(self.width_my, self.height_my)) # ##############Окно настроек ###################################################### def settings_window(self): """Окно настройки""" combo = { 50: 0, 100: 1, 130: 2, 160: 3, 200: 4, 250: 5 } self.modalWindow = QWidget(window, Qt.Window) self.modalWindow.setWindowModality(Qt.WindowModal) # SettingsWindow(modalWindow) Ui_Form.setupUi(self, self.modalWindow) Ui_Form.retranslateUi(self, self.modalWindow) self.pushButtonOK.mousePressEvent = self.button_ok self.pushButtonCancel.mousePressEvent = self.button_cancel self.toolButton.mousePressEvent = self.tool_button self.pushButtonAdd.mousePressEvent = self.button_add self.pushButtonDel.mousePressEvent = self.button_del self.checkBox.stateChanged.connect(self.check_box) self.radioButtonYes.toggled.connect(self.radio_button) self.modalWindow.setAttribute(Qt.WA_DeleteOnClose, True) # modalWindow.move(window.geometry().center() - modalWindow.rect().center() - QtCore.QPoint(4, 30)) try: fp = open("settings.json", "r") try: self.settings = json.load(fp) finally: fp.close() # Размер preview self.photo_size = self.settings['settings']['preview'][0]['prev_size'] self.comboBox.setCurrentIndex(combo[self.photo_size]) # Количество загружаемых страниц self.num_pages = self.settings['settings']['pages_load'][0]['num_pages'] self.spinPages.setProperty("value", self.num_pages) # Количество строк self.num_line = self.settings['settings']['preview'][0]['num_line'] self.spinRow.setProperty("value", self.num_line) # Количество столбцов self.num_column = self.settings['settings']['preview'][0]['num_column'] self.spinColumns.setProperty("value", self.num_column) # Путь (каталог на диске) для сохранения изображений self.pic_save_path = self.settings['settings']['pic_save'][0]['path'] self.lineEdit.setText(self.pic_save_path) # Заполняем listWidget списком групп dict = self.settings['vk_groups'] for i in dict: self.listWidget.addItem(str(i) + ':' + dict[i]) # Заполняем прокси, если есть self.proxy_host = self.settings['settings']['proxies'][0]['host'] self.proxy_port = self.settings['settings']['proxies'][0]['port'] self.proxy_username = self.settings['settings']['proxies'][0]['username'] self.proxy_password = self.settings['settings']['proxies'][0]['password'] if self.proxy_host and self.proxy_port: self.radioButtonYes.setChecked(True) self.lineEditProxy.setText(self.proxy_host) self.spinBoxPort.setProperty("value", self.proxy_port) if self.proxy_username and self.proxy_password: self.checkBox.setChecked(True) self.lineEditLogin.setText(self.proxy_username) self.lineEditPwd.setText(self.proxy_password) else: self.lineEditLogin.setDisabled(True) self.lineEditPwd.setDisabled(True) else: self.radioButtonNo.setChecked(True) self.lineEditProxy.setDisabled(True) self.spinBoxPort.setDisabled(True) self.lineEditLogin.setDisabled(True) self.lineEditPwd.setDisabled(True) self.checkBox.setDisabled(True) except IOError: self.num_pages = 2 self.num_line = 2 self.num_column = 2 self.photo_size = 50 self.modalWindow.show() def radio_button(self): if self.radioButtonYes.isChecked(): self.lineEditProxy.setDisabled(False) self.spinBoxPort.setDisabled(False) self.checkBox.setDisabled(False) else: self.lineEditProxy.setDisabled(True) self.spinBoxPort.setDisabled(True) self.checkBox.setDisabled(True) self.lineEditLogin.setDisabled(True) self.lineEditPwd.setDisabled(True) self.checkBox.setChecked(False) def check_box(self): if self.checkBox.isChecked(): self.lineEditLogin.setDisabled(False) self.lineEditPwd.setDisabled(False) else: self.lineEditLogin.setDisabled(True) self.lineEditPwd.setDisabled(True) # Кнопка добавления группы в список listWidget def button_add(self, e): print('button add') self.modalWindowAdd = QWidget(window, Qt.Window) self.modalWindowAdd.setWindowModality(Qt.WindowModal) Ui_FormUrl.setupUi(self, self.modalWindowAdd) Ui_FormUrl.retranslateUi(self, self.modalWindowAdd) self.pushButtonUrl.mousePressEvent = self.buttonUrl self.modalWindowAdd.show() # Кнопка удаления группы из списка listWidget def button_del(self, e): print(self.settings['vk_groups']) # Берем из listWidget текущее значение (id группы) self.group_id = self.dict_count[self.listWidget.currentRow()] # print(self.group_id) # print(self.dict_count) # self.dict_count.pop(self.dict_count[self.group_id]) # print(self.dict_count) # Удаляем текущее значение из JSON self.settings['vk_groups'].pop(self.group_id) print(self.settings['vk_groups']) # Удаляем текущее значение из списка listWidget for item in self.listWidget.selectedItems(): self.listWidget.takeItem(self.listWidget.row(item)) def buttonUrl(self, e): url = self.lineEditUrl.text() try: response = requests.post(url, proxies=self.proxies, auth=self.auth) except IOError: print('Unable to fetch URL!') QMessageBox.critical(self.modalWindowAdd, 'Error','Unable to fetch URL!\nURL must be like: http://vk.com/sergeqwe') return None if response.status_code == 200: # Ищем ID группы result = response.text start = result.find('[group]') id = result[start:start+20] if id: id = int(sub("\D", "", id)) print(id) # Ищем название группы start = result.find('<title>') end = result.find('</title>') groupe_name = result[start+7:end] print(groupe_name) self.listWidget.addItem(str(id) + ':' + groupe_name) self.settings['vk_groups'][str(id)] = groupe_name print(self.settings['vk_groups']) else: QMessageBox.critical(self.modalWindowAdd, 'Error', 'Not a group!') return None else: print('Unable to fetch URL...') self.modalWindowAdd.close() def button_ok(self, e): # Размер preview self.settings['settings']['preview'][0]['prev_size'] = int(self.comboBox.currentText()) self.photo_size = int(self.comboBox.currentText()) # Количество загружаемых страниц self.settings['settings']['pages_load'][0]['num_pages'] = int(self.spinPages.text()) self.num_pages = int(self.spinPages.text()) # Количество строк self.settings['settings']['preview'][0]['num_line'] = int(self.spinRow.text()) self.num_line = int(self.spinRow.text()) # Количество столбцов self.settings['settings']['preview'][0]['num_column'] = int(self.spinColumns.text()) self.num_column = int(self.spinColumns.text()) # Путь (каталог на диске) для сохранения изображений self.settings['settings']['pic_save'][0]['path'] = self.lineEdit.text() self.pic_save_path = self.lineEdit.text() # Проверяем включен ли в настройках прокси # Если прокси выключен, то обнуляем переменную proxies if self.radioButtonNo.isChecked(): print('proxy_disable') self.proxies = {} self.auth = HTTPProxyAuth('', '') if self.radioButtonYes.isChecked(): if self.checkBox.isChecked(): username = self.lineEditLogin.text() password = self.lineEditPwd.text() self.proxies = { "http": 'http://' + username + ':' + password + '@' + self.lineEditProxy.text() + ':' + self.spinBoxPort.text(), "https": 'http://' + username + ':' + password + '@' + self.lineEditProxy.text() + ':' + self.spinBoxPort.text(), } self.auth = self.auth = HTTPProxyAuth(username, password) self.settings['settings']['proxies'][0]['username'] = self.lineEditLogin.text() self.settings['settings']['proxies'][0]['password'] = self.lineEditPwd.text() else: self.proxies = { "http": 'http://' + self.lineEditProxy.text() + ':' + self.spinBoxPort.text(), "https": 'http://' + self.lineEditProxy.text() + ':' + self.spinBoxPort.text(), } self.settings['settings']['proxies'][0]['username'] = '' self.settings['settings']['proxies'][0]['password'] = '' self.settings['settings']['proxies'][0]['host'] = self.lineEditProxy.text() self.settings['settings']['proxies'][0]['port'] = self.spinBoxPort.text() else: self.settings['settings']['proxies'][0]['host'] = '' self.settings['settings']['proxies'][0]['port'] = '' self.settings['settings']['proxies'][0]['username'] = '' self.settings['settings']['proxies'][0]['password'] = '' try: fp = open("settings.json", "w") try: json.dump(self.settings, fp, indent=4) finally: fp.close() except IOError: print('error') self.group_fill() self.modalWindow.close() self.first_run = 0 def button_cancel(self, e): print('cancel') self.modalWindow.close() ###################################################################################### # Флаги активности кнопок def check_buttons(self): """Флаги для выставления активности(затемненности) пунктов меню и кнопок""" # Если находимся в режиме росмотра большого фото, то делаем кнопку refresh активной # А кнопку Load недоступной if self.prev_mode == 1: self.actionRefresh.setEnabled(True) self.actionLoad.setEnabled(False) else: self.actionRefresh.setEnabled(False) self.actionLoad.setEnabled(True) if self.loading_error == False: # Если в режиме preview и на последней странице, то затемняем кнопку next if self.current_page == (len(self.result["response"]["items"])) / (self.num_line * self.num_column)\ and self.prev_mode == 0: self.actionPreview.setEnabled(True) self.actionNext.setEnabled(False) else: self.actionPreview.setEnabled(True) self.actionNext.setEnabled(True) # Если в режиме preview и на первой странице, то затемняем кнопку preview if self.current_page == 1 and self.prev_mode == 0: self.actionPreview.setEnabled(False) self.actionNext.setEnabled(True) # Загружаем список фото def load_pic_list(self): self.downloading('Loading...') self.wait() if self.first_run == 0: self.group_fill_ava() self.first_run = 1 current_row = self.listWidgetMain.currentRow() # Берем из listWidget текущее значение (id группы) if self.DEBUG: print('Current row (group): ' + str(current_row)) if current_row == -1: current_row = 0 if self.DEBUG: print('Current row (group): ' + str(current_row)) self.group_id = self.dict_count[current_row] if self.DEBUG: print('Groupe ID: ' + self.group_id) """Загружаем и парсим JSON""" # self.label.setPixmap(QtGui.QPixmap("pic/avto.jpg").scaled(200, 200, QtCore.Qt.KeepAspectRatio)) req = 'https://api.vk.com/method/photos.get?v=5.32' \ '&owner_id=-{0}' \ '&album_id=wall&count={1}' \ '&rev=1&photo_sizes=1'.format(self.group_id,(self.num_line * self.num_column) * self.num_pages) if self.DEBUG: print('Loading JSON list of pics: ' + req) try: response = requests.get(req, proxies=self.proxies, auth=self.auth, timeout=3) except requests.exceptions.Timeout: print('Time out') self.loading_error = True except requests.exceptions.ProxyError: print('04 Gateway Time-out') self.loading_error = True except IOError: print('Error loading JSON') self.loading_error = True # if response.status_code != 200: # print('Косяк. Статус код') # self.loading_error = True if self.loading_error == False: self.result = json.loads(response.text) # req = Request(req) # # try: # response = urlopen(req) # # except HTTPError as e: # print('The server couldn\'t fulfill the request.') # print('Error code: ', e.code) # exit(0) # # except URLError as e: # print('We failed to reach a server.') # print('Reason: ', e.reason) # exit(0) # # self.result = json.loads(response.read().decode('utf8')) # print('JSON LOADING OK') # print(self.result) # Ищем приблизительно равные размеры фото заданные в переменной photo_size # Так же помещаем в переменную photo_date дату публикации фото if self.DEBUG: print('Всего фото загружено: ' + str(len(self.result["response"]["items"]))) if len(self.result["response"]["items"]) < (self.num_line * self.num_column) * self.num_pages: print('НЕТ СТОЛЬКО ФОТО!') exit(0) return None self.photo_avg = [] self.photo_date = [] e = 0 while e < len(self.result["response"]["items"]): i = 0 v = [] while i < len(self.result["response"]["items"][e]["sizes"]): v.append(abs(self.photo_size - self.result["response"]["items"][e]["sizes"][i]["height"])) i += 1 out = 0 generator = enumerate(v) out = [i for i,x in generator if x == min(v)] self.photo_avg.append(self.result["response"]["items"][e]["sizes"][out[0]]["src"]) self.photo_date.append(self.result["response"]["items"][e]["date"]) e += 1 # Ищем картинку с самым большим разрешением self.photo_max = [] e = 0 while e < len(self.result["response"]["items"]): i = 0 v = 0 count = 0 while i < len(self.result["response"]["items"][e]["sizes"]): if v < self.result["response"]["items"][e]["sizes"][i]["height"]: v = self.result["response"]["items"][e]["sizes"][i]["height"] count = i i += 1 self.photo_max.append(self.result["response"]["items"][e]["sizes"][count]["src"]) e += 1 if self.DEBUG: print(self.photo_max) # self.modalWindowDownloading.close() self.splash.close() # Загружаем preview def load_pic_prev(self): """Загружаем фото с сайта в зависимости от страницы и момещаем их в список loading_image""" # Показываем заставку при загрузке self.downloading('Img...') self.wait() if self.loading_error == False: if self.result and len(self.result["response"]["items"]) == (self.num_line * self.num_column) * self.num_pages: self.loading_image = [] # Обнуляем список mult_num = self.num_line * self.num_column for i in range(self.current_page * mult_num - mult_num, self.current_page * mult_num): # req = Request(self.photo_avg[i]) # response = urlopen(req).read() try: response = requests.get(self.photo_avg[i], proxies=self.proxies, auth=self.auth) except IOError: print('Не смог загрузить preview на страницу') exit(0) image = QImage() image.loadFromData(response.content) self.loading_image.append(image) if self.DEBUG: print(str(i) + ')' + self.photo_avg[i]) self.splash.showMessage(os.path.basename(self.photo_avg[i]), QtCore.Qt.AlignTop | QtCore.Qt.AlignCenter, QtCore.Qt.black) else: print('NO_RESULT') # self.modalWindowDownloading.close() # print('На странице: ' + str(self.loading_image)) if self.loading_image[0].size().width() <=0: if self.DEBUG: print('Error internet connection') # QMessageBox.critical(window, 'Error','Error internet connection') self.splash.close() msgBox = QMessageBox( QMessageBox.Critical, 'Error', 'Check internet connection', QMessageBox.NoButton) msgBox.exec_() self.first_run = 0 return None self.splash.close() # Выводим preview def draw_pic(self): if self.loading_error == False: """Выводим preview""" self.clear_screen() # Очищаем окно if len(self.result["response"]["items"]) == (self.num_line * self.num_column) * self.num_pages: t = 0 for i in range(self.num_line): for n in range(self.num_column): self.icon[t] = QtGui.QIcon() self.icon[t].addPixmap(QtGui.QPixmap(self.loading_image[t]), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.button[t] = QtWidgets.QPushButton(self.centralwidget) self.button[t].setIcon(self.icon[t]) self.button[t].setIconSize(QtCore.QSize(self.photo_size, self.photo_size)) self.button[t].setFlat(True) # self.button[t].setStyleSheet('background-color:#FFFFFF;color:#000000;') # self.button[t].setStyleSheet("font-size:40px;background-color:#333333;border: 2px solid #222222") # self.button[t].setStyleSheet("border: 1px solid #222222") self.gridLayout_2.addWidget(self.button[t], i, n, 1, 1, QtCore.Qt.AlignTop) self.button[t].setObjectName("Button: " + str(t)) self.pic_date[t] = time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime(self.photo_date[t])) self.button[t].setToolTip(str(self.pic_date[t])) self.button[t].clicked.connect(self.full_pic_view) t += 1 else: print('Не совпало') exit(0) # Выход из просмотра большой картинки при нажатии левой кнопки и сохранение картинки при нажатии правой кнопки def close_full_pic_view(self, e): """Закрываем просмотр большой картинки левым кликом мыши""" if e.buttons() == QtCore.Qt.LeftButton: if self.DEBUG: print('left button pressed') self.prev_mode = 0 # Флаг, что выходим из просмотра в preview self.clear_screen() # Удаляем изображение self.check_buttons() self.draw_pic() self.statusbar.showMessage('Page: ' + str(self.current_page)) # Созраняем изображение при нажатии правой кнопки мыши if e.buttons() == QtCore.Qt.RightButton: path = self.pic_save_path + '/' + os.path.basename(self.photo_max[self.photo_max_id]) print(path) self.image.save(path) if os.path.exists(path): self.statusbar.showMessage('File saved to: ' + path ) else: self.statusbar.showMessage('File is not saved. Сheck the path settings!' ) msgBox = QMessageBox( QMessageBox.Critical, 'Error', 'File is not saved. Сheck the path settings!\n<File-Settings-Path>', QMessageBox.NoButton) msgBox.exec_() # Очищаем окно def clear_screen(self): """Удаляем все кнопки с изображениями (очищаем окно)""" while self.gridLayout_2.count(): item = self.gridLayout_2.takeAt(0) item.widget().deleteLater() # Определяем какая кнопка (превиюшка) была нажата def wat_is_button(self): """Определяем какая кнопка была нажата""" sender1 = self.sender().objectName() self.sender1 = int(sub("\D", "", sender1)) print(self.sender1) # Определяем размер окна def win_size(self): """Определяем размер окна (scrollArea), чтобы оно не растягивалось, если размер изображения больше, чем размер окна""" # self.height = window.size().height() - 70 # self.width = window.size().width() - 10 self.height = self.scrollArea.size().height() self.width = self.scrollArea.size().width() # Окно загрузки def downloading(self, msg): # print('downloading...') # self.modalWindowDownloading = QWidget(window, Qt.Window) # self.modalWindowDownloading.setWindowModality(Qt.WindowModal) # Ui_FormDownload.setupUi(self, self.modalWindowDownloading) # Ui_FormDownload.retranslateUi(self, self.modalWindowDownloading) # self.modalWindowDownloading.show() image = QPixmap('./pic/loading1.jpg') self.splash = QSplashScreen(image) self.splash.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.splash = QSplashScreen(image, Qt.WindowStaysOnTopHint) self.splash.setMask(image.mask()) font = QFont(self.splash.font()) font.setPointSize(font.pointSize() + 3) self.splash.setFont(font) self.splash.showMessage(msg, QtCore.Qt.AlignTop | QtCore.Qt.AlignCenter, QtCore.Qt.black) self.splash.show() def wait(self): start = time.time() while time.time() - start < 1: time.sleep(0.001) app.processEvents()
parser = argparse.ArgumentParser(\ description='Test script for tiled graphicview widget') parser.add_argument('--file', '-f', help='hdf file to load', default=None) args = parser.parse_args() if args.file is not None and not os.path.isfile(args.file): raise SystemExit("File does not exist!") app = QApplication(sys.argv) # windows always sucks!! if sys.platform.startswith("win"): sqldrivers = join(dirname(QtGui.__file__), "plugins") app.addLibraryPath(sqldrivers) splash_pix = QPixmap(':annotationtool_about.png') splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) splash.show() splash.showMessage(version.information, alignment=Qt.AnchorHorizontalCenter| Qt.AnchorVerticalCenter) app.processEvents() mw = AtMainWindow(args.file) mw.show() app.thread().msleep(1000) splash.finish(mw) sys.exit(app.exec_())
self.schlumbergerLayout = False self.wennerLayout = True def schlumberger(self): """Define Schlumberger layout is True""" self.schlumbergerLayout = True self.wennerLayout = False if __name__ == '__main__': app = QApplication(sys.argv) app.setWindowIcon(QIcon('hand_drill.png')) splashPix = QPixmap('splash.png') splashScreen = QSplashScreen(splashPix, Qt.WindowStaysOnTopHint) splashScreen.setMask(splashPix.mask()) splashScreen.show() app.processEvents() time.sleep(3) startup = StartupWindow(tableData, headers, colors, old_coefficients) startup.show() splashScreen.finish(startup) sys.exit(app.exec_())
def start_ide(app, filenames, projects_path, extra_plugins, linenos): """Load all the settings necessary before loading the UI, and start IDE.""" QCoreApplication.setOrganizationName('NINJA-IDE') QCoreApplication.setOrganizationDomain('NINJA-IDE') QCoreApplication.setApplicationName('NINJA-IDE') app.setWindowIcon(QIcon(":img/icon")) # Check if there is another session of ninja-ide opened # and in that case send the filenames and projects to that session # running = ipc.is_running() # start_server = not running[0] # if running[0] and (filenames or projects_path): # sended = ipc.send_data(running[1], filenames, projects_path, linenos) # running[1].close() # if sended: # sys.exit() # else: # running[1].close() # Create and display the splash screen splash_pix = QPixmap(":img/splash") splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint) splash.setMask(splash_pix.mask()) splash.show() app.processEvents() # Set the codec for strings (QString) # QTextCodec.setCodecForCStrings(QTextCodec.codecForName('utf-8')) # FIXME: handle this qsettings = ide.IDE.ninja_settings() data_qsettings = ide.IDE.data_settings() # Translator # language = QLocale.system().name() # lang = qsettings.value('preferences/interface/language', # defaultValue=language, type='QString') + '.qm' # lang_path = file_manager.create_path(resources.LANGS, lang) # if file_manager.file_exists(lang_path): # settings.LANGUAGE = lang_path # translator = QTranslator() # if settings.LANGUAGE: # translator.load(settings.LANGUAGE) # app.installTranslator(translator) # qtTranslator = QTranslator() # qtTranslator.load( # "qt_" + language, # QLibraryInfo.location(QLibraryInfo.TranslationsPath)) # app.installTranslator(qtTranslator) # Loading Syntax splash.showMessage("Loading Syntax", Qt.AlignRight | Qt.AlignTop, Qt.black) json_manager.load_syntax() # Read Settings splash.showMessage("Loading Settings", Qt.AlignRight | Qt.AlignTop, Qt.black) # FIXME: handle this # Set Stylesheet # style_applied = False # if settings.NINJA_SKIN not in ('Default'): # file_name = ("%s.qss" % settings.NINJA_SKIN) # qss_file = file_manager.create_path(resources.NINJA_THEME_DOWNLOAD, # file_name) # if file_manager.file_exists(qss_file): # with open(qss_file) as fileaccess: # qss = fileaccess.read() # app.setStyleSheet(qss) # style_applied = True # if not style_applied: # if settings.NINJA_SKIN == 'Default': # with open(resources.NINJA_THEME) as fileaccess: # qss = fileaccess.read() # app.setStyleSheet(qss) # FIXME: handle this # Loading Schemes splash.showMessage("Loading Schemes...", Qt.AlignRight | Qt.AlignTop, Qt.black) all_schemes = json_manager.load_editor_schemes() scheme = qsettings.value("preferences/editor/scheme", "") resources.COLOR_SCHEME = all_schemes['Ninja Dark'] # if scheme: # color_scheme = all_schemes[scheme] # resources.CUSTOM_SCHEME = color_scheme # print(all_schemes) # scheme = qsettings.value('preferences/editor/scheme', "default", # type='QString') # if scheme != 'default': # scheme = file_manager.create_path(resources.EDITOR_SKINS, # scheme + '.color') # if file_manager.file_exists(scheme): # resources.CUSTOM_SCHEME = json_manager.parse(open(scheme)) # Loading Shortcuts # resources.load_shortcuts() # Loading GUI splash.showMessage("Loading GUI", Qt.AlignRight | Qt.AlignTop, Qt.black) # ninjaide = ide.IDE(start_server) ninjaide = ide.IDE() # Style app.setStyle(ninja_style.NinjaStyle()) # Showing GUI ninjaide.show() # OSX workaround for ninja window not in front try: ninjaide.raise_() except: pass # I really dont mind if this fails in any form # FIXME: handle this # Loading Session Files splash.showMessage("Loading Files and Projects", Qt.AlignRight | Qt.AlignTop, Qt.black) # First check if we need to load last session files files = data_qsettings.value('last_session/opened_files', []) projects = data_qsettings.value('last_session/projects', []) current_file = data_qsettings.value('last_session/current_file', '') if files is None: files = [] if projects is None: projects = [] ninjaide.load_session_files_projects(files, projects, current_file, []) # projects = data_qsettings.value('last_session/projects', []) # files = [] # projects = [] # if projects is None: # projects = [] # if files is None: # files = [] # current_file = '' # recent_files = [] # ninjaide.load_session_files_projects(files, projects, # current_file, recent_files) # if qsettings.value('preferences/general/loadFiles', True, type=bool): # # Files in Main Tab # files = data_qsettings.value('lastSession/openedFiles', []) # tempFiles = [] # if files: # for file_ in files: # fileData = tuple(file_) # if fileData: # tempFiles.append(fileData) # files = tempFiles # # Recent Files # recent_files = data_qsettings.value('lastSession/recentFiles', []) # # Current File # current_file = data_qsettings.value( # 'lastSession/currentFile', '', type='QString') # # Projects # projects = data_qsettings.value('lastSession/projects', []) # else: # files = [] # recent_files = [] # current_file = '' # projects = [] # Include files received from console args # file_with_nro = list([(f[0], (f[1] - 1, 0), 0) # for f in zip(filenames, linenos)]) # file_without_nro = list([(f, (0, 0), 0) for f in filenames[len(linenos):]]) # files += file_with_nro + file_without_nro # Include projects received from console args # if projects_path: # projects += projects_path # FIXME: IMPROVE THIS WITH THE NEW WAY OF DO IT # ninjaide.load_session_files_projects(files, projects, # current_file, recent_files) # Load external plugins # if extra_plugins: # ninjaide.load_external_plugins(extra_plugins) splash.finish(ninjaide)