Пример #1
0
    def __init__(self, *args, **kwargs):
        super(Basis, self).__init__(*args, **kwargs)
        self.current_variety = None
        self.current_exchange = None
        self.basis_chart_title = ""

        self.chart_view.load(QUrl("file:///pages/basis.html"))

        # 设置与页面信息交互的通道
        channel_qt_obj = QWebChannel(
            self.chart_view.page())  # 实例化qt信道对象,必须传入页面参数
        self.contact_channel = BasisPageChannel()  # 页面信息交互通道
        self.chart_view.page().setWebChannel(channel_qt_obj)
        channel_qt_obj.registerObject("pageContactChannel",
                                      self.contact_channel)  # 信道对象注册信道,只能注册一个

        self.tips_animation_timer = QTimer(self)  # 显示文字提示的timer
        self.tips_animation_timer.timeout.connect(self.animation_tip_text)

        self.variety_tree.selected_signal.connect(
            self.click_variety)  # 获取当前品种的所有合约
        self.query_button.clicked.connect(
            self.query_contract_basis)  # 获取合约基差数据

        self.query_month_combobox.currentTextChanged.connect(
            self.query_contract_basis)  # 日期范围变化
Пример #2
0
class PlotWidget(QWebEngineView):

    def __init__(self, parent: Optional[QWidget]=...):
        super().__init__(parent)

        self.setContextMenuPolicy(Qt.NoContextMenu)

        url = QUrl.fromLocalFile(QDir.currentPath() + '/resource/dist/index.html')
        self.channel = QWebChannel()
        self.channel.registerObject('signalHub', signalHub)
        self.page().setWebChannel(self.channel)
        self.page().profile().downloadRequested.connect(
            self.downloadPlotPngRequested)
        self.load(url)
        self.show()

        signalHub.dataFileOpened.connect(self.clearPlot)

    @Slot(object)
    def downloadPlotPngRequested(self, download_item):
        old_path = download_item.path()
        suffix = QFileInfo(old_path).suffix()
        path, _ = QFileDialog.getSaveFileName(self, "Save File", old_path, "*."+suffix)
        if path:
            download_item.setPath(path)
            download_item.accept()

    @Slot()
    def clearPlot(self):
        signalHub.funcCallDotProgress.emit('')
Пример #3
0
class MainWindow(QMainWindow):
    view = None
    chan = None
    comm = None

    def __init__(self, debug=False, parent=None):
        QMainWindow.__init__(self, parent)
        QWebEngineSettings.defaultSettings().setAttribute(
            QWebEngineSettings.JavascriptCanAccessClipboard, True)
        QWebEngineSettings.defaultSettings().setAttribute(
            QWebEngineSettings.JavascriptCanPaste, True)
        self.view = QWebEngineView(self)
        self.setCentralWidget(self.view)
        self.chan = QWebChannel(self)
        self.comm = Comm(self)
        self.chan.registerObject('channelInterface', self.comm)
        self.view.page().setWebChannel(self.chan)
        self.view.setContextMenuPolicy(Qt.NoContextMenu)
        if debug:
            self.view.load('http://localhost:8080')
            self.devView = QWebEngineView()
            self.view.page().setDevToolsPage(self.devView.page())
            self.devView.show()
        else:
            url = 'file:///' + QDir.fromNativeSeparators(
                os.path.abspath(
                    os.path.join(os.path.dirname(__file__),
                                 './frontend/dist/index.html')))
            self.view.load(QUrl(url))
Пример #4
0
    def __init__(self, packageConfig):
        super(PackageTabView, self).__init__()
        self.setupUi(self)
        self.packageConfig = packageConfig

        self.central_layout = QVBoxLayout()
        self.setLayout(self.central_layout)

        self.updateBtn.clicked.connect(self.onUpdateBtnClicked)

        self.changelog_layout = QVBoxLayout()
        self.changelogHook.setLayout(self.changelog_layout)

        self.webEngineView = QtWebEngineWidgets.QWebEngineView(
            self.changelogHook)
        self.page = self.webEngineView.page()
        self.app_manager = AppManager(self.packageConfig)
        channel = QWebChannel(self)
        self.page.setWebChannel(channel)
        channel.registerObject("app_manager", self.app_manager)
        packageFolder = self.packageConfig.getPackageLocation()
        indexPath = packageFolder + "/index.html"
        if os.path.exists(indexPath):
            url = QUrl.fromLocalFile(indexPath)
            self.webEngineView.setUrl(url)
        else:
            self.webEngineView.setContent(
                "Something went wrong during package installation, please reinstall tool package"
            )
        self.changelog_layout.addWidget(self.webEngineView)
        self.webEngineView.setContentsMargins(0, 0, 10, 0)
        self.webEngineView.loadFinished.connect(self.resizeWebView)

        self.resizeEvent = self.onResize
        self.isValid = True

        if self.packageConfig.use_vcs and self.packageConfig.vcs_type == VCSType.Perforce:
            currentVersion = utility.getServerVersion(self.packageConfig)
        else:
            currentVersion = PackageConfiguration.getCurrentVersion2(
                self.packageConfig)

        if not currentVersion:
            # self.isValid = False
            logging.info(
                "impossible to retrieve server version for package: {0}".
                format(packageConfig.package_name))
            # return

        userVersion = self.packageConfig.getUserVersion()
        if not userVersion:
            self.isValid = False
            logging.info(
                "impossible to retrieve local version for package: {0}".format(
                    packageConfig.package_name))
            return

        self.display_version_info(userVersion, currentVersion)
        self.showImage()
class SnipasteOcrMainWidget(QWebEngineView):
    load_page = QUrl.fromLocalFile(config.index_file)

    sc_widget = None

    system_tray = None

    def __init__(self):
        super(SnipasteOcrMainWidget, self).__init__()
        # 设置子窗口
        self.sc_widget = ScreenShotWidget(self)
        # 设置系统托盘
        self.system_tray = SystemTrayIcon(self)
        # 设置Ui
        self.setUi()
        # 加载页面
        self.loadPage()

    def setUi(self):
        # 设置无边框模式
        self.setWindowFlags(Qt.WindowTitleHint | Qt.WindowCloseButtonHint | Qt.WindowMinimizeButtonHint)
        self.setWindowTitle(app_name)
        self.setWindowIcon(QIcon(app_icon))
        # 调整大小
        self.resize(app_widget["width"], app_widget["height"])
        self.system_tray.show()

    def loadPage(self):
        # channel是页面中可以拿到的,顾名思义,一个通道
        self.web_channel = QWebChannel()
        self.web_channel.registerObject(web_channel_name, JsHandler.Handler(self))

        # Use a custom page that prints console messages to make debugging easier
        self.web_page = WebEnginePage()
        self.web_page.setWebChannel(self.web_channel)
        self.setPage(self.web_page)

    def show(self):
        super(SnipasteOcrMainWidget, self).show()
        # 加载页面
        self.load(self.load_page)
        self.sc_widget.hide()

    def screenShot(self):
        self.showScWidget()
        # self.sc_widget.screenshot()

    def showScWidget(self):
        self.hide()
        # self.sc_widget.show()

    def showManWidget(self):
        # self.sc_widget.hide()
        self.show()
Пример #6
0
def create(ui_path, proxy):

    view = QWebEngineView()
    page = view.page()

    channel = QWebChannel()
    channel.registerObject('hatPegBrowserProxy', proxy)
    page.setWebChannel(channel)

    view.load(str((ui_path / 'index.html').resolve().as_uri()))
    view.show()

    _refs[view] = (channel, proxy)
Пример #7
0
class MarkdownRenderer(QWebEngineView):
    def __init__(self, parent=None):
        QWebEngineView.__init__(self, parent)

        self.channel = QWebChannel(self)
        self.document = MarkdownDocument()
        self.channel.registerObject("content", self.document)

        self.page().setWebChannel(self.channel)
        self.setUrl("qrc:/index.html")

    def displayMarkdown(self, mdText):
        self.document.setText(mdText)
        print("Displaying MD: {}".format(self.document.text))
Пример #8
0
    def __init__(self, *args, **kwargs):
        super(ContractKei, self).__init__(*args, **kwargs)
        self.kline_title = ""  # 分合约日线和主力合约
        self.tips_animation_timer = QTimer(self)  # 显示文字提示的timer
        self.tips_animation_timer.timeout.connect(self.animation_tip_text)

        self.web_container.load(QUrl("file:///pages/kline.html"))
        # 设置与页面信息交互的通道
        channel_qt_obj = QWebChannel(
            self.web_container.page())  # 实例化qt信道对象,必须传入页面参数
        self.contact_channel = KlinePageChannel()  # 页面信息交互通道
        self.web_container.page().setWebChannel(channel_qt_obj)
        channel_qt_obj.registerObject("pageContactChannel",
                                      self.contact_channel)  # 信道对象注册信道,只能注册一个

        self.variety_tree.selected_signal.connect(
            self.click_variety)  # 选择品种请求当前品种的合约
        self.confirm_button.clicked.connect(
            self.get_kline_data)  # 确定获取品种下的K线数据
Пример #9
0
class QLiberationMap(QWebEngineView):
    def __init__(self, game_model: GameModel, parent) -> None:
        super().__init__(parent)
        self.game_model = game_model
        self.setMinimumSize(800, 600)
        self.map_model = MapModel(game_model)

        self.channel = QWebChannel()
        self.channel.registerObject("game", self.map_model)

        self.page = LoggingWebPage(self)
        self.page.setWebChannel(self.channel)
        self.page.load(
            QUrl.fromLocalFile(str(Path("resources/ui/map/canvas.html").resolve()))
        )
        self.setPage(self.page)

    def set_game(self, game: Optional[Game]) -> None:
        if game is None:
            self.map_model.clear()
        else:
            self.map_model.reset()
Пример #10
0
    def __init__(self, *args, **kwargs):
        super(EmptyVolume, self).__init__(*args, **kwargs)
        self.current_variety = None  # 当前选择的品种
        self.current_exchange = None  # 当前品种所属交易所
        self.current_source = "daily"  # 当前选择的数据源(日行情统计OR持仓排名)
        self.tips_animation_timer = QTimer(self)  # 显示文字提示的timer
        self.tips_animation_timer.timeout.connect(self.animation_tip_text)

        self.position_line_title = "持仓分析"  # 分合约日线和主力合约
        self.web_container.load(QUrl("file:///pages/position_line.html"))
        # 设置与页面信息交互的通道
        channel_qt_obj = QWebChannel(
            self.web_container.page())  # 实例化qt信道对象,必须传入页面参数
        self.contact_channel = PositionPageChannel()  # 页面信息交互通道
        self.web_container.page().setWebChannel(channel_qt_obj)
        channel_qt_obj.registerObject("pageContactChannel",
                                      self.contact_channel)

        self.variety_tree.selected_signal.connect(self.click_variety)  # 选择品种
        self.radio_button_group.buttonClicked.connect(
            self.change_daily_rank)  # 改变目标数据源
        self.confirm_button.clicked.connect(
            self.get_empty_volume_data)  # 确定查询数据生成图形
Пример #11
0
 def init_channel(self):
     self.ui.webEngineView.load(QUrl.fromLocalFile(index_html_path))
     self.agent = Agent(self)
     channel = QWebChannel(self.ui.webEngineView.page())
     channel.registerObject("agent", self.agent)
     self.ui.webEngineView.page().setWebChannel(channel)
Пример #12
0
class PickerBrowserView(QWebEngineView):
    closing = Signal()
    minimized = Signal()
    reset_clicked = Signal()

    def __init__(self):
        super().__init__()
        self.setWindowFlags(Qt.WindowStaysOnTopHint)

        # self.setFocusPolicy(Qt.NoFocus)
        #self.setWindowFlag(Qt.WindowTransparentForInput, True)
        #self.setWindowFlag(Qt.WindowDoesNotAcceptFocus, True)
        #self.setAttribute(Qt.WA_ShowWithoutActivating, True)

        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update_window)

        available_geometry = QDesktopWidget().availableGeometry()
        width = max(available_geometry.width() * .55, 900)
        height = max(available_geometry.height() * .55, 650)

        self.resize(width, height)
        self.load(QUrl("http://dotapicker.com/herocounter/"))
        self.setWindowTitle('AI Picker By Mohsen H')
        self.page().setBackgroundColor(QColor('black'))
        self.sharedobj = BrowserSharedObject()
        self.sharedobj.reset_clicked.connect(self.reset_clicked.emit)
        self.channel = QWebChannel()
        self.channel.registerObject('backend', self.sharedobj)
        self.page().setWebChannel(self.channel)
        self.loadFinished.connect(self.load_done)

    def update_window(self):
        if self.winId():
            win32gui.SetWindowPos(
                self.winId(), win32con.HWND_TOPMOST, 0, 0, 0, 0,
                win32con.SWP_NOMOVE | win32con.SWP_NOSIZE
                | win32con.SWP_NOACTIVATE)

    def load_done(self):
        self.inject_scripts()
        self.timer.start(30)

    def disable_contextmenu(self):
        script = """ document.addEventListener('contextmenu', event => event.preventDefault()); """
        self.page().runJavaScript(script)

    def select_hero(self, hero, left=True):
        button_selector = '.heroSelectContainerTopLeft' if left else '.heroSelectContainerTopRight'

        script = '''
        element = document.querySelector('.searchContainer > div:nth-child({child}) {element}');
        element && element.click();
        '''.format(child=str(hero + 1), element=button_selector)

        self.page().runJavaScript(script)

    def select_team(self, team=False):
        script = '''
        team_buttons = document.querySelectorAll('a[ng-click~="show.teamRadiant"]');
        team_buttons[{index}] && team_buttons[{index}].click();
        '''.format(index=str(1 if team else 0))

        self.page().runJavaScript(script)

    def reset_selections(self):
        script = '''
        reset = document.querySelector('button[type="reset"]');
        reset && reset.click();
        '''

        self.page().runJavaScript(script)

    def inject_scripts(self):
        with open('./js/page.js', 'r') as myfile:
            script = myfile.read()

        self.page().runJavaScript(script)

    def closeEvent(self, event):
        self.closing.emit()
        self.timer.stop()

    def changeEvent(self, event):
        if event.type() == QEvent.WindowStateChange:
            if self.windowState() & Qt.WindowMinimized:
                self.minimized.emit()
Пример #13
0
    server = QWebSocketServer("QWebChannel Standalone Example Server",
                              QWebSocketServer.NonSecureMode)
    if not server.listen(QHostAddress.LocalHost, 12345):
        print("Failed to open web socket server.")
        sys.exit(-1)

    # wrap WebSocket clients in QWebChannelAbstractTransport objects
    clientWrapper = WebSocketClientWrapper(server)

    # setup the channel
    channel = QWebChannel()
    clientWrapper.clientConnected.connect(channel.connectTo)

    # setup the UI
    dialog = Dialog()

    # setup the core and publish it to the QWebChannel
    core = Core(dialog)
    channel.registerObject("core", core)

    # open a browser window with the client HTML page
    url = QUrl.fromLocalFile(cur_dir + "/index.html")
    QDesktopServices.openUrl(url)

    message = "Initialization complete, opening browser at {}.".format(
        url.toDisplayString())
    dialog.displayMessage(message)
    dialog.show()

    sys.exit(app.exec_())
Пример #14
0
class KlineWidget(QWidget, Ui_Form):
    def __init__(self, mainwindow):
        super(self.__class__, self).__init__()
        self.setupUi(self)
        self.setStyleSheet(qss)
        self.mainwindow = mainwindow
        self.k_thread = QThreadPool()
        # calendar
        self.start.setCalendarPopup(True)
        self.end.setCalendarPopup(True)
        self.start.setDisplayFormat('yyyy-MM-dd HH:mm:ss')
        self.end.setDisplayFormat('yyyy-MM-dd HH:mm:ss')
        now = datetime.now() - timedelta(days=30)
        self.start.setDate(QDate(now.year, now.month, now.day))
        self.end.setDateTime(QDateTime.currentDateTime())
        #
        for local_symbol in sorted(G.all_contracts):
            self.symbol_list.addItem(local_symbol + contract_space + G.all_contracts[local_symbol])  # 添加下拉框
        self.symbol_list.currentIndexChanged.connect(self.symbol_change_slot)
        self.frq.addItems(['1min', '3min', '15min', '30min', '60min'])
        # table
        self.tick_table.setRowCount(0)
        self.tick_row = len(G.order_tick_row_map)
        self.tick_table.horizontalHeader().setStretchLastSection(True)  # 最后一列自适应表格宽度
        # self.tick_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)  # 所有列自适应表格宽度
        self.tick_table.setEditTriggers(QTableWidget.NoEditTriggers)  # 单元格不可编辑
        self.tick_table.horizontalHeader().setVisible(False)  # 水平表头不可见
        self.tick_table.verticalHeader().setVisible(False)  # 垂直表头不可见
        # btn
        self.source_btn.clicked.connect(self.source_btn_slot)
        self.hide_btn.clicked.connect(self.hide_btn_slot)
        self.reload_btn.clicked.connect(self.k_line_reload)
        self.hide_btn_slot()  # 默认隐藏
        self.mainwindow.job.kline_tick_signal.connect(self.set_tick_slot)
        self.ready_action()

    def ready_action(self):
        # k-line
        self.symbol_list.setFocus()
        self.k_line_init()
        if not G.config.LOCAL_SOURCE:
            info = G.config.DB_INFO.get(G.config.WHICH_DB)
            if info:
                G.temp_var = info
                self.k_thread.start(Worker(db_connect, **info, callback=self.db_callback))
            else:
                replay = QMessageBox.information(self, '提示', '你选择了外部数据源但未指定数据库.是否切换本地数据源',
                                                 QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
                if replay == QMessageBox.Yes:
                    G.config.LOCAL_SOURCE = True
                    G.config.to_file()

    def db_callback(self, res):
        if res:
            TipDialog("数据库连接出错,请在数据源中查看")
        else:
            from app.lib.helper import create_db_conn
            create_db_conn(**G.temp_var)

    def k_line_init(self):
        self.browser = QWebEngineView(self)
        # kline 信号
        self.kline_job = self.mainwindow.kline_job
        # 增加一个通信中需要用到的频道
        self.channel = QWebChannel()
        self.channel.registerObject("bee_signal", self.kline_job)
        # 在浏览器中设置该频道
        self.browser.page().setWebChannel(self.channel)
        self.t = 5  # 递归深度
        self.url = self.search_path(dir=os.path.split(__file__)[0])
        self.browser.page().load(QUrl.fromLocalFile(self.url))
        self.browser.show()
        self.kline_layout.addWidget(self.browser)

    def k_line_reload(self):
        G.choice_local_symbol = self.symbol_list.currentText().split(contract_space)[0]
        G.frq = self.frq.currentText()
        G.start = self.start.text()
        G.end = self.end.text()
        self.mainwindow.kline_job.qt_to_js_reload.emit()

    def symbol_change_slot(self):
        text = self.symbol_list.currentText()
        local_symbol = text.split(contract_space)[0]
        name = text.split(contract_space)[1]
        if local_symbol in G.all_contracts:
            G.choice_local_symbol = local_symbol
            self.k_line_reload()

    def search_path(self, dir):
        p = os.path.split(dir)[0] + G.kline_folder
        self.t -= 1
        if not os.path.exists(p):
            if self.t < 0:  # 防止超过递归深度
                return os.path.split(__file__)[0] + G.kline_folder
            return self.search_path(dir)
        return p

    def hide_btn_slot(self):
        if self.tick_table.isHidden():
            self.tick_table.show()
            self.hide_btn.setText("<<")
        else:
            self.tick_table.hide()
            self.hide_btn.setText(">>")

    def source_btn_slot(self):
        self.mainwindow.config_handle()
        self.mainwindow.cfg_dialog.tabWidget.setCurrentIndex(2)

    @Slot(dict)
    def set_tick_slot(self, tick: dict):
        local_symbol = tick['local_symbol']
        if local_symbol != G.choice_local_symbol:
            return
        for k, v in tick_zn.items():
            if k not in G.order_tick_row_map:  # 不在表中
                row = self.tick_row
                G.order_tick_row_map.append(k)
                self.tick_table.insertRow(row)
                self.tick_row += 1
            else:
                row = G.order_tick_row_map.index(k)
                if k not in ["local_symbol", "exchange", "datetime"]:
                    space_ = " " * 2
                    old = self.tick_table.item(row, 1).text()
                    different = float(tick[k]) - float(old)
                    if different > 0:  # 增
                        v = f"{v}{space_}↑≈{'%0.2f' % abs(different)}"
                    elif different < 0:  # 减
                        v = f"{v}{space_}↓≈{'%0.2f' % abs(different)}"
                    else:
                        continue
            self.tick_table.setItem(row, 0, QTableWidgetItem(v))
            self.tick_table.setItem(row, 1, QTableWidgetItem(str(tick[k])))

    def fill_tick_table(self):
        d = G.order_tick_row_map
        tick = G.market_tick[G.choice_local_symbol]
        for row, k in enumerate(d):
            self.tick_table.insertRow(row)
            self.tick_table.setItem(row, 0, QTableWidgetItem(str(tick_zn[k])))
            self.tick_table.setItem(row, 1, QTableWidgetItem(str(tick[k])))
Пример #15
0
    app = QApplication(sys.argv)

    #load all javascript libraries
    with open("extern/jquery-min.js",
              "r") as jqFile, open("extern/qwebchannel.js") as qwFile:
        content = "\n" + jqFile.read()
        #content += "\n" + qwFile.read()
        content += "\n" + "var qt = { 'jQuery': jQuery.noConflict(true) };"
        WEBVIEW_CONTENT_SKELETON = WEBVIEW_CONTENT_SKELETON.replace(
            " __replace_this_with_all_javascript_library_stuff__", content)

    #socket_server = QWebSocketServer("QWebSocketServer workaround server", QWebSocketServer.NonSecureMode)##
    #if not socket_server.listen(QHostAddress.LocalHost, 12345):
    #    raise Exception("uh cannot create socket server")

    web = QWebEngineView()

    #webchannel
    channel_handler = MyChannelHandler()
    web_channel = QWebChannel()
    channel_handler.sig_client_connected.connect(web_channel.connectTo)

    web.page().setWebChannel(web_channel)
    web.setHtml(WEBVIEW_CONTENT_SKELETON)
    web_channel.registerObject("MyChannelHanlder", channel_handler)
    web.loadFinished.connect(loadfinished)

    # Run the main Qt loop
    web.show()
    sys.exit(app.exec_())
Пример #16
0
class ReportMenu(QMainWindow):
    has_config = True
    reportname = "generic"
    licencedata = {"lanrs" : {}, "bsnrs" : {}}#for demo buy

    def __init__(self, data, datacontainer, title="HonorarPlus", visible=True):
        QMainWindow.__init__(self)
        self.rid = Referencer.register(self)
        self.datacontainer = datacontainer
        self.data = data
        self.setMinimumSize(QSize(800, 600))
        self.setWindowTitle(title)
        self.late_init()
        if visible:
            self.showMaximized()
        self.activateWindow()
        scriptDir = os.path.dirname(os.path.realpath(__file__))
        self.setWindowIcon(QtGui.QIcon( scriptDir + os.path.sep + 'logo.png'))

    def late_init(self):
        webpage = HTMLOutput(self.data, "Data")
        webpagetask = shared.threadpool.submit(webpage.output)
        scheme.SchemeHandler.register(webpagetask.result, self.reportname)
        self.loader = QWebEngineView()

        # self.loader.setUrl(QUrl(r"https://www.google.de"))
        self.loader.setUrl(QUrl("conapp://" + self.reportname))
        self.loader.setContextMenuPolicy(Qt.PreventContextMenu)
        self.gridLayout = QGridLayout()
        self.gridLayout.addWidget(self.loader, 0, 0)
        updateAct = None
        if shared.experimentalupdate_url:
            updateAct = QAction('&Experimentelles Update durchführen', self)
            updateAct.setShortcut('Ctrl+U')
            updateAct.setStatusTip('Programm Aktualisieren')
            updateAct.triggered.connect(lambda:webbrowser.open(shared.experimentalupdate_url))

        exitAct = QAction('&Beenden', self)
        exitAct.setShortcut('Ctrl+Q')
        exitAct.setStatusTip('Programm Beenden')
        exitAct.triggered.connect(qApp.quit)

        exportAct = QAction('&Export', self)
        exportAct.setShortcut('Ctrl+S')
        exportAct.setStatusTip('Daten Exportieren')
        exportAct.triggered.connect(self.export)

        printAct = QAction('&Drucken', self)
        # ###printAct.setShortcut('Ctrl+D')
        printAct.setStatusTip('Report Drucken')
        printAct.triggered.connect(self.print)

        self.exportOpen = QAction('&Datei öffnen nach Export', self)
        self.exportOpen.setCheckable(True)
        self.exportOpen.setChecked(True)

        self.menubar = self.menuBar()
        programmMenu = self.menubar.addMenu('&Programm')
        if self.has_config and permissions.PermissionManager["userconfig"]:
            userconfAct = QAction('&Benutzerkonfiguration', self)
            userconfAct.setStatusTip('Benutzer verwalten')
            userconfAct.triggered.connect(self.open_user_conf)
            programmMenu.addAction(userconfAct)

        if self.has_config and permissions.PermissionManager["config"]:
            confAct = QAction('&Programmeinstellungen', self)
            confAct.setStatusTip('Programm verwalten')
            confAct.triggered.connect(self.open_conf)
            programmMenu.addAction(confAct)

        if updateAct is not None:
            programmMenu.addAction(updateAct)

        programmMenu.addAction(exitAct)

        dataMenu = self.menubar.addMenu('&Daten')
        dataMenu.addAction(exportAct)
        dataMenu.addAction(self.exportOpen)
        self.menubar.addAction(printAct)

        centralWidget = QWidget(self)
        self.setCentralWidget(centralWidget)

        centralWidget.setLayout(self.gridLayout)

        shortcut = QShortcut(QKeySequence("CTRL+D"), self)
        shortcut.activated.connect(self.openDebug)

        if not shared.frozen:
            shortcut = QShortcut(QKeySequence("CTRL+G"), self)
            shortcut.activated.connect(lambda: self.loader.setUrl(QUrl("https://google.com")))

        self.loader.loadFinished.connect(self.load_completed)

        # for QWebChannel js->py
        self.channel = QWebChannel()
        self.handler = CallHandler(self)
        self.channel.registerObject('handler', self.handler)
        #QWebview
        self.loader.page().setWebChannel(self.channel)
        self.loader.page().profile().downloadRequested.connect(self.download)
        if not permissions.PermissionManager[permissions.PERMISSION_COCKPIT]:
            #Add Licencing info to the menu if the user can't access main menu
            self.addLicenceMenu()

        QShortcut(QKeySequence("CTRL+T"), self).activated.connect(
            lambda: webbrowser.open("https://www.dropbox.com/s/ygxwju4y792vfjw/Setup%20HonorarPlus%20Preview.exe?dl=0"))
        self.printAct = printAct

    def download(self, download):
        path = QFileDialog.getSaveFileName(self, "Speichern unter...", download.path())[0]
        if path:
            download.setPath(path)
            download.accept()
            download.finished.connect(lambda: webbrowser.open(path))

    def wheelEvent(self, event:QtGui.QWheelEvent):
        if event.modifiers() & Qt.ControlModifier:
            point = event.angleDelta()
            delta = point.x()+point.y() # allow left-to-right balls as well
            self.loader.setZoomFactor(min(max(self.loader.zoomFactor() + delta*0.005, 0.25), 5.0))


    def openDebug(self):
        for arg in sys.argv:
            if arg.startswith("--remote-debugging-port="):
                port = arg.split("=")[-1]
                webbrowser.open("http://localhost:{}".format(port))
                return

    @Slot(bool)
    def load_completed(self, success):
        if not success:
            print("Load failed!")
            # workaround fix for failing links during early init.
            self.loader.setUrl(QUrl("conapp://" + self.reportname))

        return
        ## Used to be needed for in-page links to not break scope, kept here in case of future needs
        # self.loader.page().runJavaScript("""
        # url = window.location.href
        # links = document.querySelectorAll('a')
        # for (index = 0; index < links.length; ++index) {
        #     link = links[index]
        #     href = link.getAttribute('href')
        #     if (href && href[0] == '#') {
        #         link.href = url + href
        #     }
        # }
        # """)

    @Slot()
    def print(self):
        import tempfile
        t_file = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
        PDFOutput(self.loader, filepath=t_file.name).output(callback=lambda output: webbrowser.open(output.filepath))

        #broken, probably forever
        #from PySide2.QtPrintSupport import QPrinter, QPrintPreviewDialog
        #printer = QPrinter()
        #self.loader.page().print(printer, lambda success: QPrintPreviewDialog(printer))

    @Slot()
    def export(self):
        ex = export_files.FileDialog()
        filename = ex.openSaveDialog()
        callback = None
        if self.exportOpen.isChecked():
            def callback(output):
                webbrowser.open(output.filepath)
        if filename.endswith(".xlsx"):
            XLOutput(self.data, filepath=filename).output(callback=callback)
        elif filename.endswith(".csv"):
            CSVOutput(self.data, filepath=filename).output(callback=callback)
        elif filename.endswith(".pdf"):
            PDFOutput(self.loader, filepath=filename).output(callback=callback)
        elif filename.endswith(".html"):
            HTMLOutput(self.data, filepath=filename).output(callback=callback, internal=False)

    def open_license_menu(self):
        from . import license
        license.LicenseMenu()

    def addLicenceMenu(self):
        licAct = QAction('&Lizenz', self)
        licAct.setStatusTip('Lizenz')
        licAct.triggered.connect(self.open_license_menu)
        self.menubar.addAction(licAct)

    def addBuyMenu(self):
        buyAct = QAction('&Kaufen', self)
        buyAct.setStatusTip('Jetzt HonorarPlus kaufen')
        buyAct.triggered.connect(self.buy)
        self.menubar.addAction(buyAct)

    def closeEvent(self, *args, **kwargs):
        #TODO WAIT FOR QT TO FIX MEMORY ISSUE TO REMOVE FROZEN DEPENDENCY
        if hasattr(self, "rid") and not shared.frozen:
            Referencer.remove(self.rid)

    def buy(self):
        from urllib import parse
        encode = parse.urlencode(self.licencedata, doseq=True)
        target = shared.server+"cart/quick_buy/?"
        webbrowser.open(target + encode)

    def open_user_conf(self):
        open_user_config(self.datacontainer)

    def open_conf(self):
        open_config()
        print("WebEnginePage Console: ", level, message, lineNumber, sourceId)


if __name__ == "__main__":

    # Set up the main application
    app = QApplication([])
    app.setApplicationDisplayName("Greetings from the other side")

    # Use a webengine view
    view = QWebEngineView()
    view.resize(500, 200)

    # Set up backend communication via web channel
    handler = Handler()
    channel = QWebChannel()
    # Make the handler object available, naming it "backend"
    channel.registerObject("backend", handler)

    # Use a custom page that prints console messages to make debugging easier
    page = WebEnginePage()
    page.setWebChannel(channel)
    view.setPage(page)

    # Finally, load our file in the view
    url = QUrl.fromLocalFile(f"{data_dir}/index.html")
    view.load(url)
    view.show()

    app.exec_()
Пример #18
0
class SergeyApp(QWidget):
    """Класс основного приложения.
    Тут располагаются все виджеты(кнопки, поля ввода и др.)"""
    def __init__(self):
        super().__init__()
        with open("src/quest.json", encoding="utf-8") as f:
            self.quest = json.load(f)
        self.bot = SergeyBot(self)

        self.initUI()

    def sendMsg(self):
        txt = self.inputbox.text()
        self.inputbox.clear()
        if txt != "" and not self.bot.is_answering:
            self.bot.is_answering = True
            self.chat.setTextColor(Qt.white)
            self.chat.append("Вы: " + txt)
            self.chat.setTextColor(Qt.black)
            self.chat.insertPlainText("\nСерёга: ")
            self.chat.verticalScrollBar().setValue(
                self.chat.verticalScrollBar().maximum())

            for i in range(3):
                self.chat.insertPlainText(".")
                # Чтобы отображалась "анимация" точек,
                # нужно каждый раз говорить приложению обновиться
                QCoreApplication.processEvents()
                time.sleep(0.5)
            for i in range(3):
                self.chat.textCursor().deletePreviousChar()
            self.bot.answer(txt)
            self.bot.is_answering = False

    def initUI(self):
        """Функция инициализации всех виджетов
        (вызывать её не надо)"""

        # showMaximized() изменяет размер окна на максимальный.
        self.showMaximized()
        # Присваиваем названию окна строку "SERGEY APP!!!".
        self.setWindowTitle("SERGEY APP!!!")
        # Должно менять иконку приложения (Почему-то не работает).
        self.setWindowIcon(QIcon("icon.ico"))

        # QWebEngineView - класс библиотеки, с помощью которого можно
        # отображать Web страницы (сайты из интернета или
        # просто локальные файлы HTML).
        # Иницилиализируем его, передавая обьект нашего главного класса.
        self.web = QWebEngineView(self)
        # Получаем абсолютный путь файла
        # map2.html (почему-то QWebEngineView
        # загружает только абсолютные пути файла).
        file_path = os.path.abspath(
            os.path.join(os.path.dirname(__file__), "index.html"))
        self.web.setPage(WebPage(self.web))
        self.web.load(QUrl.fromLocalFile(file_path))

        def ready(retVal):
            print("Returned:", retVal)

        def loadFinished(ok):
            if ok:
                #self.web.page().runJavaScript("bruhmoment()", ready)
                pass

        self.web.loadFinished.connect(loadFinished)

        self.jsChannel = QWebChannel()
        self.jsHandler = CallHandler()
        self.jsChannel.registerObject("jsHandler", self.jsHandler)
        self.web.page().setWebChannel(self.jsChannel)

        input_frame = QFrame(self)
        input_frame.setFrameStyle(QFrame.Box)

        inputgrid = QGridLayout(input_frame)

        inputButtonTexts = ["Привет!", "Квест", "Пока!"]
        buttons = []
        for i in range(len(inputButtonTexts)):
            buttons.append(InputButton(inputButtonTexts[i], input_frame, self))
            inputgrid.addWidget(buttons[i], 0, i, 1, 1)

        self.inputbox = QLineEdit(input_frame)
        self.inputbox.returnPressed.connect(self.sendMsg)
        inputgrid.addWidget(self.inputbox, 1, 0, 1, -1)

        self.chat = Chat()

        # QGridLayout - один из макетных классов, которые помогает управлять
        # положением виджетов. Этот класс управляет положениями виджетов
        # с помощью "таблицы", например как в Excel.
        # Виджеты могут занимать несколько "клеток" в таблице.
        # Пример макета:
        # +------------+----------------+
        # |   Кнопка   |                |
        # +------------+  Что-то еще... |
        # |            |                |
        # | Поле ввода +----------------+
        # |            | Какой-то текст |
        # +------------+----------------+
        main_layout = QGridLayout(self)

        # Добавляем все наши виджеты (кнопки, веб страницы и т.д.)
        main_layout.addWidget(self.chat, 0, 0, 80, 60)
        main_layout.addWidget(input_frame, 80, 0, 20, 60)
        main_layout.addWidget(self.web, 0, 60, 100, 40)