class TestReportWidget(QWidget): def __init__(self): super().__init__() self.setWindowTitle(f'性能評価 詳細 - {Project.project_name()}') self.test_report_model = TestReportModel() self.web_view = QWebEngineView(self) html_size = QSize(890, 390) self.web_view.setFixedSize(html_size) self.setFixedSize(html_size) def reload_html(self): html = self.test_report_model.generate_test_details() self.web_view.setHtml(html)
import sys import os import pyautogui import time from PyQt5.QtCore import QUrl from PyQt5.QtTest import QTest from PyQt5.QtWidgets import QApplication,QDesktopWidget from PyQt5.QtWebEngineWidgets import QWebEnginePage, QWebEngineView app = QApplication(sys.argv) base_url = os.getcwd() base_url = base_url.replace('\\', '/') browser = QWebEngineView() browser.load(QUrl(base_url+"/demo.html")) browser.setWindowTitle("VTuber") browser.setFixedSize(1280,720) screen = QDesktopWidget().screenGeometry() size = browser.geometry() newLeft = (screen.width() - size.width()) / 2 newTop = (screen.height() - size.height()) / 2 browser.setGeometry(newLeft,newTop,1280,720) #窗口的大小和位置设置 browser.show() print(browser.geometry()) app.exec_()
class cStack(QWidget): ## Widget for every contestant def __init__(self, conNum, res, bg): super().__init__() self.conNum = conNum self.scores = None self.imgNum = 0 self.setFixedSize(rPix(1600), rPix(885)) ## Renames passed ResourceManager() object self.res = res ## Loads Pixmaps self.bg = bg self.ui = self.res.ui self.pixmaps = self.res.images self.runOnce = False self.callback_value = None self.initUI() def initUI(self): ## Information Labels: infoLabel1 = QLabel() ## NAME infoLabel1.setText(con[self.conNum - 1][0][0]["name"].upper()) infoLabel1.setFont(QFont(fonts[1], rPix(25), weight=75)) infoLabel2 = QLabel() infoLabel2.setText(con[self.conNum - 1][1][0]["name"].upper()) infoLabel2.setFont(QFont(fonts[1], rPix(25), weight=75)) infoLabel3 = QLabel() ## SECTION if con[self.conNum - 1][0][1]["section"] == con[self.conNum - 1][1][1]["section"]: infoLabel3.setText( str(con[self.conNum - 1][2]["grade"]) + " - " + con[self.conNum - 1][0][1]["section"]) else: infoLabel3.setText( str(con[self.conNum - 1][2]["grade"]) + " - " + con[self.conNum - 1][0][1]["section"] + " & " + con[self.conNum - 1][1][1]["section"]) infoLabel3.setFont(QFont(fonts[0], rPix(15), weight=75)) infoLabelLayout = [QHBoxLayout(), QHBoxLayout(), QHBoxLayout() ] ## Centralize Using Horizontal Box Layout for i in infoLabelLayout: i.setContentsMargins(0, 0, 0, 0) i.setSpacing(0) infoLabelLayout[0].addStretch() infoLabelLayout[0].addWidget(infoLabel1) infoLabelLayout[0].addStretch() infoLabelLayout[1].addStretch() infoLabelLayout[1].addWidget(infoLabel2) infoLabelLayout[1].addStretch() infoLabelLayout[2].addStretch() infoLabelLayout[2].addWidget(infoLabel3) infoLabelLayout[2].addStretch() ## Information Layout: infoLayout = QVBoxLayout() infoLayout.setSpacing(10) for i in infoLabelLayout: infoLayout.addLayout(i) ## Information Frame: infoFrame = QFrame() infoFrame.setFixedSize(rPix(780), rPix(205)) infoFrame.setObjectName("infoFrame") infoFrame.setStyleSheet( ".QFrame#infoFrame{border-bottom:2px #A9A9A9;background:" + self.ui[(self.conNum - 1) % 4] + ";border-radius : 5px}") infoFrame.setLayout(infoLayout) ## Score Sheet Webview: if "-nosheet" in sys.argv: self.sheet = QFrame() self.sheet.setFixedSize(rPix(760), rPix(630)) else: self.sheet = QWebView() self.sheet.loadFinished.connect(self.pageLoaded) _path = QUrl.fromLocalFile(currentDir() + "/resources/sheet.html") self.sheet.load(_path) ## Navigation Buttons resetButton = ImageButton("resources/img/buttons/reset", rPix(30), rPix(30), toggle=False, tooltip="<b>Reset Scores</b>") saveButton = ImageButton("resources/img/buttons/save", rPix(30), rPix(30), toggle=False, tooltip="<b>Save Scores</b>") if "-nosheet" not in sys.argv: resetButton.clicked.connect(self.resetScores) saveButton.clicked.connect(self.saveScores) ## Sheet Navigation Layout: sheetNavigationLayout = QHBoxLayout() sheetNavigationLayout.addStretch() sheetNavigationLayout.addWidget(resetButton) sheetNavigationLayout.addWidget(saveButton) ## Layout of Sheet Frame: sheetLayout = QVBoxLayout() sheetLayout.setContentsMargins(rPix(15), rPix(10), rPix(10), rPix(10)) sheetLayout.setSpacing(rPix(5)) sheetLayout.addWidget(self.sheet) sheetLayout.addLayout(sheetNavigationLayout) ## Sheet Frame: sheetFrame = QFrame() sheetFrame.setFixedSize(rPix(780), rPix(650)) sheetFrame.setObjectName("sheetFrame") sheetFrame.setStyleSheet( ".QFrame#sheetFrame{border-bottom:2px #A9A9A9;background:" + self.ui[(self.conNum - 1) % 4] + ";border-radius : 5px}") sheetFrame.setLayout(sheetLayout) ## Left Placeholder Layout: leftLayout = QVBoxLayout() leftLayout.setContentsMargins(0, 0, 0, 0) leftLayout.setSpacing(10) leftLayout.addWidget(infoFrame) leftLayout.addWidget(sheetFrame) ## Previous Image Button: prevImage = ImageButton("resources/img/buttons/prevImg", rPix(100), rPix(845), toggle=False, tooltip="<b>Previous Image</b>") prevImage.clicked.connect(self.prevImageEvt) ## Next Image Button: nextImage = ImageButton("resources/img/buttons/nextImg", rPix(100), rPix(845), toggle=False, tooltip="<b>Next Image</b>") nextImage.clicked.connect(self.nextImageEvt) ##Con Num Label: conNumLabel = QLabel(str(self.conNum)) conNumLabel.setFont(QFont(fonts[0], rPix(30))) ##Con Num Layout: conNumLabelLayout = QHBoxLayout() conNumLabelLayout.setContentsMargins(0, 0, 0, 0) conNumLabelLayout.setSpacing(0) conNumLabelLayout.addStretch() conNumLabelLayout.addWidget(conNumLabel) conNumLabelLayout.addStretch() ## Label for info self.infoconLabel = QLabel("NO IMAGE LOADED") self.infoconLabel.setFont(QFont(fonts[1], rPix(10))) ##Con Num Layout: infoconLabelLayout = QHBoxLayout() infoconLabelLayout.setContentsMargins(0, 0, 0, 0) infoconLabelLayout.setSpacing(0) infoconLabelLayout.addStretch() infoconLabelLayout.addWidget(self.infoconLabel) infoconLabelLayout.addStretch() ##Vertical Layout for conNum and Info vertConInfoLayout = QVBoxLayout() vertConInfoLayout.setContentsMargins(0, 0, 0, 0) vertConInfoLayout.setSpacing(rPix(20)) vertConInfoLayout.addStretch() vertConInfoLayout.addLayout(conNumLabelLayout) vertConInfoLayout.addLayout(infoconLabelLayout) vertConInfoLayout.addStretch() ## Image Info Frame: infoFrame = ImageFrame() _infoPixmap = QPixmap("resources/img/infoFrame.png") infoFrame.setPixmap( _infoPixmap.scaled(rPix(560), rPix(120), Qt.KeepAspectRatio)) infoFrame.setLayout(vertConInfoLayout) ## Image Info Filler: infoFiller = QLabel() infoFiller.setFixedSize(rPix(560), rPix(727)) ## Image Info Layout: infoLayout = QVBoxLayout() infoLayout.addWidget(infoFiller) infoLayout.addWidget(infoFrame) infoLayout.setContentsMargins(0, 0, 0, 0) infoLayout.setSpacing(0) ## Image Navigation/Info Layout: navigLayout = QHBoxLayout() navigLayout.addWidget(prevImage) navigLayout.addLayout(infoLayout) navigLayout.addWidget(nextImage) navigLayout.setContentsMargins(0, 0, 0, 0) navigLayout.setSpacing(0) ## Image Navigation/Info Frame: navigFrame = QFrame() navigFrame.setObjectName("noframe") navigFrame.setStyleSheet(styles["noframe"]) navigFrame.setLayout(navigLayout) ## Image Frame: self.imageFrame = ImageFrame(fade=True) try: ##Checks if Pixmap is available, then sets it self.imageFrame.setPixmap(self.pixmaps[str( self.conNum)][self.imgNum]) self.infoconLabel.setText(order[self.imgNum]) except: pass self.imageFrame.setFixedSize(rPix(760), rPix(845)) #self.imageFrame.setLayout(navigLayout) ## Image Stacked Layout: imageStacked = QStackedLayout() imageStacked.setStackingMode(QStackedLayout.StackAll) imageStacked.setContentsMargins(0, 0, 0, 0) imageStacked.setSpacing(0) imageStacked.insertWidget(0, self.imageFrame) imageStacked.insertWidget(1, navigFrame) ## Image Placeholder Layout: imagePlaceholderLayout = QHBoxLayout() imagePlaceholderLayout.setContentsMargins(rPix(15), rPix(10), rPix(10), rPix(10)) imagePlaceholderLayout.setSpacing(0) imagePlaceholderLayout.addLayout(imageStacked) ## Image Placeholder Frame imagePlaceholderFrame = QFrame() imagePlaceholderFrame.setObjectName("imageplaceholder") imagePlaceholderFrame.setStyleSheet( ".QFrame#imageplaceholder{border-bottom:2px #A9A9A9;background:" + self.ui[(self.conNum - 1) % 4] + ";border-radius : 5px}") imagePlaceholderFrame.setFixedSize(rPix(780), rPix(865)) imagePlaceholderFrame.setLayout(imagePlaceholderLayout) ## Main Layout: mainLayout = QHBoxLayout() mainLayout.setContentsMargins(rPix(10), rPix(10), rPix(10), rPix(10)) mainLayout.setSpacing(10) ## Dynamic Layouting (based on Contestant Number) if self.conNum <= (tconNum / 2): mainLayout.addLayout(leftLayout) mainLayout.addWidget(imagePlaceholderFrame) else: mainLayout.addWidget(imagePlaceholderFrame) mainLayout.addLayout(leftLayout) ## Background Frame: mainFrame = ImageFrame() mainFrame.setPixmap(self.bg) mainFrame.setLayout(mainLayout) ## Placeholder Layout: placeholderLayout = QHBoxLayout() placeholderLayout.setContentsMargins(0, 0, 0, 0) placeholderLayout.setSpacing(0) placeholderLayout.addWidget(mainFrame) self.setLayout(placeholderLayout) def prevImageEvt(self): self.imgNum = (self.imgNum - 1) % self.res.totalImgNum try: ##Checks if Pixmap is available, then sets it self.imageFrame.setPixmap(self.pixmaps[str( self.conNum)][self.imgNum]) self.infoconLabel.setText(order[self.imgNum]) except: pass def nextImageEvt(self): self.imgNum = (self.imgNum + 1) % self.res.totalImgNum try: ##Checks if Pixmap is available, then sets it self.imageFrame.setPixmap(self.pixmaps[str( self.conNum)][self.imgNum]) self.infoconLabel.setText(order[self.imgNum]) except: pass def callback(self, value): self.callback_value = value def save_callback(self, value): _html = self.sheet.page() if value == "error": print("error") else: try: female = [int(i) for i in value.split('~')[0].split("-")] male = [int(i) for i in value.split('~')[1].split("-")] pair = [int(i) for i in value.split('~')[2].split("-")] scores = {"pair": pair, "female": female, "male": male} ostream = {"scores": scores} with open( os.path.join( currentDir(), "resources\\data\\sheets\\" + str(self.conNum) + ".yml"), "w+") as _f: yaml.dump(ostream, _f, default_flow_style=False) except: pass def pageLoaded(self): ## Runs Functions on Page Load() if not self.runOnce: self.runOnce = True self.setBG() self.runOnce = False else: self.runOnce = False def activate(self): if "-nosheet" not in sys.argv and os.path.isfile( os.path.join( currentDir(), "resources\\data\\sheets\\" + str(self.conNum) + ".yml")): self.loadScores() def setBG(self): ## Sets background of sheet based on UI Color (x007) palette = self.res.ui[(self.conNum - 1) % 4] _html = self.sheet.page() _html.runJavaScript('setBackground("' + palette + '");', self.callback) def resetScores(self): _html = self.sheet.page() if os.path.isfile( os.path.join( currentDir(), "resources\\data\\sheets\\" + str(self.conNum) + ".yml")): alertReply = QMessageBox.warning( self, 'Are you sure?', "Do you want to Reset Fields? Press the Reset option to clear fields only", QMessageBox.Yes | QMessageBox.Reset | QMessageBox.No, QMessageBox.No) if alertReply == QMessageBox.Yes: _html.runJavaScript('clearFields();', self.callback) os.remove( os.path.join( currentDir(), "resources\\data\\sheets\\" + str(self.conNum) + ".yml")) if alertReply == QMessageBox.Reset: _html.runJavaScript('clearFields();', self.callback) if alertReply == QMessageBox.No: return else: _html.runJavaScript( 'alert("Cannot Reset scores! No scoresheet saved.");', self.callback) def loadScores(self): ## Loads Saved Scores with open( os.path.join( currentDir(), "resources\\data\\sheets\\" + str(self.conNum) + ".yml")) as _f: _istream = yaml.load(_f) scores = _istream["scores"] female = [str(i) for i in scores["female"]] male = [str(i) for i in scores["male"]] pair = [str(i) for i in scores["pair"]] scoreList = "-".join(female) + "~" + "-".join(male) + "~" + "-".join( pair) _html = self.sheet.page() _html.runJavaScript('loadScores("' + scoreList + '");', self.callback) print("Scores for Contestant # " + str(self.conNum) + " Loaded.") def saveScores(self): _html = self.sheet.page() self.scores = "" _html.runJavaScript('saveScores();', self.save_callback)
class MainWindow(QWidget): def __init__(self): super(MainWindow, self).__init__() self.resize(1200, 700) self.showMaximized() self.setStyleSheet( "MainWindow {background-color: #F0F8FF ;color: white;padding-left: 4px;border: 1px solid #6c6c6c;" "spacing: 3px; }") self.image_path = 'map.PNG' self.data_dict = {} # self.setFixedSize(1200,700) self.setWindowIcon(QtGui.QIcon('algomo.png')) self.info = QLabel('Info...', self) self.info.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Maximum) self.info.setStyleSheet( "QLabel {background-color: QLinearGradient(x1:0, y1:0, x2:0, y2:1, stop:0 #d7801a, stop:0.5 #b56c17 stop:1 #ffa02f); font-size:25px; font-family: 'Open Sans', sans-serif; text-align:center;}" ) self.layout = QVBoxLayout() self.setWindowTitle('COVID Feed') self.title = QLabel('COVID Updates ', self) self.title.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Maximum) self.title.setAlignment(Qt.AlignHCenter) self.title.setStyleSheet( "QLabel {background-color: #F0F8FF ;color:darkBlue; font-family: Avantgarde; text-align:center;font-size:30px; font-weight:bold;}" ) self.layout.setSpacing(0) self.layout.setContentsMargins(0, 0, 0, 0) self.layout.addWidget(self.title) self.setLayout(self.layout) self.run_backend() def deleteWidget(self, layout, widget): layout.removeWidget(widget) widget.deleteLater() widget = None def update_map(self): self.journey_map = QWebView() self.journey_map.settings().setAttribute( QWebEngineSettings.JavascriptEnabled, True) self.journey_map.load( QUrl.fromLocalFile( QDir.current().absoluteFilePath('legend2.html'))) self.tabs_widget.tab2.layout.addWidget(self.journey_map) def display(self, location, headings_df, num_articles=10): print(headings_df) self.map_image = QLabel() pixmap = QtGui.QPixmap(self.image_path) self.map_image.setPixmap(pixmap) self.location_box = TextBox('Enter your postcode', self) self.location_box.clicked.connect(self.location_box.selectAll) self.location_box.returnPressed.connect(self.set_location) #self.layout.addWidget(self.map_image, 0, Qt.AlignCenter) self.tabs_widget = MyTableWidget(self) self.tabs_widget.setStyleSheet("QWidget {background-color: #e6f0ff}") self.layout.addWidget(self.tabs_widget) self.maps_tabs = MapsWidget(self) #self.maps_tabs.setStyleSheet("QWidget {background-color:#b8dbff}") self.maps_tabs.setStyleSheet("QWidget {background-color:white;} ") self.maps_tabs.setFixedSize(1400, 700) self.map = QWebView() self.map.settings().setAttribute(QWebEngineSettings.JavascriptEnabled, True) self.map.load( QUrl.fromLocalFile(QDir.current().absoluteFilePath('export.html'))) self.maps_tabs.tab1.layout.addWidget(self.map, 0, Qt.AlignHCenter) self.h_layout = QHBoxLayout() self.h_layout.addWidget(self.maps_tabs) #self.h_layout.addWidget(QLabel('test')) self.journey_map = QWebView() self.journey_map.settings().setAttribute( QWebEngineSettings.JavascriptEnabled, True) self.journey_map.load( QUrl.fromLocalFile(QDir.current().absoluteFilePath('legend.html'))) self.location_box = TextBox( 'Enter start and end location, seperated by comma', self) self.location_box.clicked.connect(self.location_box.selectAll) self.location_box.returnPressed.connect(self.update_location) self.articles_table = QTableWidget(num_articles, 2) self.map.setSizePolicy( QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)) self.articles_table.setSizePolicy( QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)) self.map.setFixedSize(1400, 800) header = self.articles_table.horizontalHeader() #header.setStretchLastSection(True) #self.articles_table.verticalHeader().setStretchLastSection(True) self.articles_table.setFixedSize(400, 700) #self.map.resize(700,500) #self.articles_table.resize(400,500) for i, headings_sent in enumerate( zip(headings_df.Heading, headings_df.Sentiment)): heading, sentiment = headings_sent print(heading, sentiment) self.articles_table.setItem(i, 0, QTableWidgetItem(heading)) self.articles_table.setItem(i, 1, QTableWidgetItem(str(sentiment))) header = self.articles_table.horizontalHeader() header.setSectionResizeMode(0, QHeaderView.Stretch) #header.setSectionResizeMode(1, QHeaderView.ResizeToContents) #self.articles_table.resizeColumnsToContents() self.articles_table.resizeRowsToContents() self.articles_table.setColumnWidth(1, 80) self.articles_table.setAutoScroll(False) #self.articles_table.setHorizontalScrollMode(QAbstractItemView.ScrollPerPixel) self.articles_table.setHorizontalHeaderLabels(('Title', 'Sentiment')) self.articles_table.horizontalHeader().setDefaultAlignment( Qt.AlignLeft) articles_layout = QVBoxLayout() table_title = QLabel('Latest Headlines') table_title.setSizePolicy( QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)) table_title.setStyleSheet( "QLabel {background-color:#e6f0ff; font-size:25px;font-weight:bold; font-family: 'Open Sans', sans-serif; text-align:center;}" ) articles_layout.addWidget(table_title) articles_layout.addWidget(self.articles_table) self.articles_table.setFrameStyle(QFrame.NoFrame) self.h_layout.addLayout(articles_layout) self.tabs_widget.tab1.layout.addLayout(self.h_layout) self.tabs_widget.tab2.layout.addWidget(self.journey_map) self.tabs_widget.tab2.layout.addWidget(self.location_box) self.map.setStyleSheet( "QWebEngineView { background-color: #F0F8FF;padding: 1px; border-style: solid; border: 1px solid #1e1e1e;border-radius: 5; }" ) self.articles_table.setStyleSheet( "QTableWidget { background-color: #F0F8FF;padding: 1px; border-style: solid; border: 1px solid #1e1e1e;border-radius: 5; }" ) #self.tabs_widget.tab1.layout.addWidget(self.map) self.layout.addWidget(self.location_box) def update_location(self): self.back_end.data = str(self.location_box.text()) print('3') self.deleteWidget(self.layout, self.journey_map) print('3') self.back_end.returned = True def set_location(self): self.data_dict['location'] = str(self.location_box.text()) print('3') self.deleteWidget(self.layout, self.location_box) self.back_end.data = self.data_dict print('3') self.back_end.returned = True def ask_location(self): self.location_box = TextBox('Enter your postcode', self) self.location_box.clicked.connect(self.location_box.selectAll) self.location_box.returnPressed.connect(self.set_location) self.layout.addWidget(self.location_box, 0, Qt.AlignCenter) def run_backend(self): self.threads = [] self.back_end = BackEnd() self.threads.append(self.back_end) self.back_end.ask_location_trigger.connect(self.ask_location) self.back_end.display_trigger.connect(self.display) self.back_end.update_journey.connect(self.update_map) self.back_end.start()
# set up main window mainWindow = QMainWindow() ui = gui_main.Ui_MainWindow() ui.setupUi(mainWindow) # set up map dialog mappedRoute = QDialog(mainWindow) mappedRoute_ui = mapGUI.Ui_Dialog() mappedRoute_ui.setupUi(mappedRoute) #create new map widget in horizontal box layout of map dialog mapWV = WebMapWidget() mappedRoute_ui.mapHBL.addWidget(mapWV) mapWV.setFixedSize(1200, 800) mapWV.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)) ui.actionExit.setIcon(app.style().standardIcon(QStyle.SP_DialogCancelButton)) ui.hoursLE.setValidator(QIntValidator()) #========================================== # connect signals #========================================== ui.findLocPB.clicked.connect(runQuery) ui.mapPB.clicked.connect(mapMyRoute) mappedRoute_ui.exportPB.clicked.connect(exportRouteShapefile) #=======================================
class scMap(QWidget): # map class used def __init__(self, app, parent=None): super().__init__(parent=parent) self.app = app self.browser = QWebEngineView(self) self.channel = QWebChannel() self.bridge = Bridge() self.channel.registerObject('bridge', self.bridge) self.browser.page().setWebChannel(self.channel) self.initUI() self.bool_zoom_change = True self.bool_reset_map = True self.zoom_got = None self.bounds_got = None self.bool_contains = None self.bool_contains_1 = None self.bool_contains_2 = None def initUI(self): self.browser.load(QUrl("file:///display/map.html")) self.browser.setFixedSize(783, 616) self.show() def runJavaScript(self, js_str): self.browser.page().runJavaScript(js_str) def runJavaScript_with_callback(self, js_str, callback): self.browser.page().runJavaScript(js_str, callback) def createMarker(self, name, lat, lng, icon): js_str = """%s = new google.maps.Marker({ position: {lat: %f, lng: %f}, map: map, icon: "data/%s" });""" % (name, lat, lng, icon) self.runJavaScript(js_str) def moveMarker(self, name, lat, lng, link): # 判断是否越界,越界则重置地图中心与缩放 if self.cross_the_border(lat, lng, link): # print('cross_the_border') self.reset_map(link) js_str = """%s.setPosition({lat: %f, lng: %f})""" % (name, lat, lng) self.runJavaScript(js_str) def deleteMarker(self, name): pass def setCenter(self, lat, lng): js_str = """map.setCenter({lat: %f, lng: %f})""" % (lat, lng) self.runJavaScript(js_str) def panTo(self, lat, lng): js_str = """map.panTo({lat: %f, lng: %f})""" % (lat, lng) self.runJavaScript(js_str) def set_home(self, lat, lng): js_str = """home = new google.maps.Marker({ position: {lat: %f, lng: %f}, map: map, icon: "data/home.png" });""" % (lat, lng) self.runJavaScript(js_str) def cross_the_border(self, lat, lng, link): # None for no result js_str = "map.getBounds().contains({lat: %f, lng: %f})" % (lat, lng) self.runJavaScript_with_callback(js_str, link.js_callback) bool_ctb = link.js_result link.js_result = None if bool_ctb is None: return bool_ctb else: return not bool_ctb def cross_the_border_1(self, lat, lng): # None for no result js_str = "map.getBounds().contains({lat: %f, lng: %f})" % (lat, lng) self.runJavaScript_with_callback(js_str, self.ctb_callback_1) bool_ctb = self.bool_contains_1 self.bool_contains_1 = None if bool_ctb is None: return bool_ctb else: return not bool_ctb def cross_the_border_2(self, lat, lng): # None for no result js_str = "map.getBounds().contains({lat: %f, lng: %f})" % (lat, lng) self.runJavaScript_with_callback(js_str, self.ctb_callback_2) bool_ctb = self.bool_contains_2 self.bool_contains_2 = None if bool_ctb is None: return bool_ctb else: return not bool_ctb def ctb_callback(self, result): self.bool_contains = result def ctb_callback_1(self, result): self.bool_contains_1 = result def ctb_callback_2(self, result): self.bool_contains_2 = result def callback_print(self, v): print(type(v), v) def reset_map(self, link): if self.bool_reset_map: self.bool_reset_map = False lat1 = None lat2 = None lng1 = None lng2 = None for linkInt in self.app.toolbox.getLinkManager().links: if lat1 is None or linkInt.uav_lat < lat1: lat1 = linkInt.uav_lat if lat2 is None or linkInt.uav_lat > lat2: lat2 = linkInt.uav_lat if lng1 is None or linkInt.uav_lng < lng1: lng1 = linkInt.uav_lng if lng2 is None or linkInt.uav_lng > lng2: lng2 = linkInt.uav_lng self.panTo((lat1 + lat2) / 2, (lng1 + lng2) / 2) # 预留范围 p = 1 / 8 lat1_goal = lat1 - (lat2 - lat1) * p lat2_goal = lat2 + (lat2 - lat1) * p lng1_goal = lng1 - (lng2 - lng1) * p lng2_goal = lng2 + (lng2 - lng1) * p # get map bounds (lat1_got, lat2_got, lng1_got, lng2_got) bounds = None while bounds is None: bounds = self.getBounds() lat1_got, lat2_got, lng1_got, lng2_got = bounds # get zoom(n_got) n_got = None while n_got is None: n_got = self.getZoom() # compare (lat1_goal, lat2_goal, lng1_goal, lng2_goal) and (lat1_got, lat2_got, lng1_got, lng2_got) ratio = max(([(lat2_goal - lat1_goal) / (lat2_got - lat1_got), (lng2_goal - lng1_goal) / (lng2_got - lng1_got)])) # confirm delta delta = 0 if ratio > 1: # while ratio > 1: # delta -= 1 # ratio /= 2 delta = -1 elif 1 / 2 >= ratio > 0: # while ratio <= 1 / 2: # delta += 1 # ratio *= 2 delta = 1 elif ratio == 0 or 1 >= ratio > 1 / 2: pass else: input('reset map::ratio error') n_goal = n_got + delta if n_goal > 20: n_goal = 20 elif n_goal < 3: n_goal = 3 #if delta != 0: # print(threading.current_thread().getName(), 'delta:', delta, '|', 'n_goal:', n_goal) # print((lat1_goal, lat2_goal, lng1_goal, lng2_goal), (lat1_got, lat2_got, lng1_got, lng2_got)) # self.zoom_change(zoom=n_goal) self.fitBounds(lat1_goal, lat2_goal, lng1_goal, lng2_goal) self.bool_reset_map = True def fitBounds(self, lat1_goal, lat2_goal, lng1_goal, lng2_goal): js_str = '''fitBounds(%f, %f, %f, %f)''' % (lat1_goal, lat2_goal, lng1_goal, lng2_goal) self.runJavaScript(js_str) def zoom_change(self, delta=-1, zoom=None): if self.bool_zoom_change: self.bool_zoom_change = False if zoom is None: n_got = None while n_got is None: n_got = self.getZoom() n_goal = n_got + delta if n_goal > 20: n_goal = 20 elif n_goal < 3: n_goal = 3 if delta != 0: print('n_goal:', n_goal, threading.current_thread().getName()) while n_got != n_goal: # setZoom js_str = '''map.setZoom(%d)''' % n_goal self.runJavaScript(js_str) # getZoom n_temp = None while n_temp is None: n_temp = self.getZoom() n_got = n_temp else: n_got = None while n_got is None: n_got = self.getZoom() n_goal = zoom while n_got != n_goal: # setZoom js_str = '''map.setZoom(%d)''' % n_goal self.runJavaScript(js_str) # getZoom n_temp = None while n_temp is None: n_temp = self.getZoom() n_got = n_temp self.bool_zoom_change = True def getZoom(self): js_str = '''map.getZoom()''' self.runJavaScript_with_callback(js_str, self.callback_getZoom) zoom = self.zoom_got self.zoom_got = None return zoom def callback_getZoom(self, result): self.zoom_got = result def getBounds(self): js_str = '''map.getBounds()''' self.runJavaScript_with_callback(js_str, self.callback_getBounds) bounds = self.bounds_got self.bounds_got = None if bounds is None: return bounds else: # return (lat1_got, lat2_got, lng1_got, lng2_got) return (bounds['f']['b'], bounds['f']['f'], bounds['b']['b'], bounds['b']['f']) def callback_getBounds(self, result): self.bounds_got = result
class Ui_MainWindow(QtWidgets.QMainWindow): def __init__(self): super(Ui_MainWindow, self).__init__() # Set the size of Main Window self.setFixedSize(1000, 700) # Initialize the layout self.initLayout() self.initLeftWidget() def search(self): source = str(self.sourceInput.text()) dest = str(self.destInput.text()) date = str(self.calendarInput.text()) deptTime = str(self.timeInput.text()) arrTime = str(self.timeInputArr.text()) maxTrans = str(self.exchangeInput.text()) # for path planning and monte carlo sampling max_transfer_stop = int(maxTrans) departure_month = date.split('/')[0] departure_day = int(date.split('/')[1]) departure_hour = int(deptTime.split(':')[0]) departure_minute = int(deptTime.split(':')[1]) arrival_hour = int(arrTime.split(':')[0]) arrival_minute = int(arrTime.split(':')[1]) dep_date = datetime.strptime( departure_month + ' {:02d} {:02d}'.format(departure_day, _DEFAULT_YEAR_), '%b %d %Y') dep_time = '{:02d}:{:02d}'.format(departure_hour, departure_minute) arr_time = '{:02d}:{:02d}'.format(arrival_hour, arrival_minute) plotplan = path_and_probability(source, dest, max_transfer_stop, dep_time, arr_time, dep_date) f = codecs.open("./data/Sample_Application.html", 'r', 'utf-8') html = f.read() self.web = QWebEngineView() self.web.setHtml(html) self.web.setFixedSize(640, 700) self.right_layout.addWidget(self.web, 0, 0, 12, 8) self.right_widget.setStyleSheet(''' QWidget#right_widget{color:#232C51; background:white; border:1px solid darkGray; border-top-right-radius:5px; border-top-left-radius:5px; border-bottom-right-radius:5px; border-bottom-left-radius:5px;}''') # Prepare the data for output numRes = len(plotplan) # Clear the widget for i in reversed(range(self.left_bottom_layout.count())): widgetToRemove = self.left_bottom_layout.itemAt(i).widget() # remove it from the layout list self.left_bottom_layout.removeWidget(widgetToRemove) # remove it from the gui widgetToRemove.setParent(None) # Set Header font font = QtGui.QFont() font.setFamily("Arial Black") font.setPointSize(12) self.routeButton = {} for i in range(numRes): deptTime = plotplan[i][5][0] arrTime = plotplan[i][6][-1] buttonTemp = QtWidgets.QPushButton() buttonTemp.setFixedSize(278, 70) buttonTemp.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) MapLabel = QtWidgets.QLabel() mapIcon = QtGui.QPixmap('./image/Map.svg').scaled( 20, 20, QtCore.Qt.IgnoreAspectRatio) MapLabel.setPixmap(mapIcon) # Route option routeLabel = QtWidgets.QLabel() routeLabel.setFont(font) routeLabel.setFixedSize(45, 20) routeLabel.setText(deptTime) routeLabel1 = QtWidgets.QLabel() routeLabel1.setFont(font) routeLabel1.setFixedSize(5, 20) routeLabel1.setText('--') routeLabel2 = QtWidgets.QLabel() routeLabel2.setFont(font) routeLabel2.setFixedSize(45, 20) routeLabel2.setText(arrTime) deptTime = datetime.strptime('2017/09/13 ' + deptTime, '%Y/%m/%d %H:%M') arrTime = datetime.strptime('2017/09/13 ' + arrTime, '%Y/%m/%d %H:%M') hour = int((arrTime - deptTime).seconds / 3600) minute = int(((arrTime - deptTime).seconds / 3600 - hour) * 60) routeLabel3 = QtWidgets.QLabel() routeLabel3.setFont(font) routeLabel3.setFixedSize(80, 20) routeLabel3.setText('{}h {}min'.format(hour, minute)) lay = QtWidgets.QGridLayout(buttonTemp) lay.addWidget(MapLabel, 0, 0, 1, 1, QtCore.Qt.AlignLeft) lay.addWidget(routeLabel, 0, 1, 1, 1) lay.addWidget(routeLabel1, 0, 2, 1, 1) lay.addWidget(routeLabel2, 0, 3, 1, 1) lay.addWidget(routeLabel3, 0, 6, 1, 4, QtCore.Qt.AlignRight) timeLabel = QtWidgets.QLabel() timeIcon = QtGui.QPixmap('./image/Time.svg').scaled( 20, 20, QtCore.Qt.IgnoreAspectRatio) timeLabel.setPixmap(timeIcon) setVech = [] font1 = QtGui.QFont() font1.setFamily("Arial Black") font1.setPointSize(8) for car in plotplan[i][3]: if car not in setVech: setVech.append(car) for j in range(len(setVech)): if j == 0: routeLabel4 = QtWidgets.QLabel() routeLabel4.setFont(font1) routeLabel4.setFixedSize(60, 20) routeLabel4.setText(setVech[j]) lay.addWidget(routeLabel4, 1, j + 1, 1, 1) else: routeLabel5 = QtWidgets.QLabel() routeLabel5.setFont(font1) routeLabel5.setFixedSize(5, 20) routeLabel5.setText('--') routeLabel6 = QtWidgets.QLabel() routeLabel6.setFont(font1) routeLabel6.setFixedSize(60, 20) routeLabel6.setText(setVech[j]) lay.addWidget(routeLabel5, 1, j * 2, 1, 1) lay.addWidget(routeLabel6, 1, j * 2 + 1, 1, 1) self.routeButton[i] = buttonTemp self.left_bottom_layout.addWidget(self.routeButton[i], i, 0, 1, 4, QtCore.Qt.AlignTop) # Complement blank space if numRes < 4: for i in range(numRes, 4): buttonTemp = QtWidgets.QPushButton() buttonTemp.setFixedHeight(70) sp_retain = buttonTemp.sizePolicy() sp_retain.setRetainSizeWhenHidden(True) buttonTemp.setSizePolicy(sp_retain) buttonTemp.setVisible(False) self.left_bottom_layout.addWidget(buttonTemp, i, 0, 1, 4, QtCore.Qt.AlignTop) self.left_bottom_layout_style += '''QPushButton{border:none; background-color:white; color: red; border-bottom:1px solid darkGray; border-radius:3px;}''' self.left_bottom_widget.setStyleSheet(self.left_bottom_layout_style) def initLayout(self): """ Use grid for layout and initialize it. """ # Create grid Layout for main widget self.main_widget = QtWidgets.QWidget() self.main_widget.setObjectName('main_widget') self.main_layout = QtWidgets.QGridLayout() self.main_widget.setLayout(self.main_layout) # Create left-side-up widget self.left_widget = QtWidgets.QWidget() self.left_widget.setObjectName('left_widget') self.left_layout = QtWidgets.QGridLayout() self.left_widget.setLayout(self.left_layout) # Create left-side-down widget self.left_down_widget = QtWidgets.QWidget() self.left_down_widget.setObjectName('left_down_widget') self.left_down_layout = QtWidgets.QGridLayout() self.left_down_widget.setLayout(self.left_down_layout) # Create left-side-bottom widget self.left_bottom_widget = QtWidgets.QWidget() self.left_bottom_widget.setObjectName('left_bottom_widget') self.left_bottom_layout = QtWidgets.QGridLayout() self.left_bottom_widget.setLayout(self.left_bottom_layout) # Create right-side widget self.right_widget = QtWidgets.QWidget() self.right_widget.setObjectName('right_widget') self.right_layout = QtWidgets.QGridLayout() self.right_widget.setLayout(self.right_layout) # Add left-side and right side widget to main widget self.main_layout.addWidget(self.left_widget, 0, 0, 3, 4) self.main_layout.addWidget(self.left_down_widget, 3, 0, 3, 4) self.main_layout.addWidget(self.left_bottom_widget, 6, 0, 6, 4) self.main_layout.addWidget(self.right_widget, 0, 4, 12, 8) self.setCentralWidget(self.main_widget) def initLeftWidget(self): """ Initialize left-side widget. """ # ---------- Source region ---------- # # Source label self.sourceLabel = QtWidgets.QLabel() sourceIcon = QtGui.QPixmap('./image/SourceIcon.svg').scaled( 20, 20, QtCore.Qt.IgnoreAspectRatio) self.sourceLabel.setPixmap(sourceIcon) # Source Input self.sourceInput = QtWidgets.QLineEdit() self.sourceInput.setPlaceholderText('Starting Point') self.sourceInput.setFixedHeight(30) # To icon self.toLabel = QtWidgets.QLabel() toIcon = QtGui.QPixmap('./image/ToIcon.svg').scaled( 15, 15, QtCore.Qt.IgnoreAspectRatio) self.toLabel.setFixedHeight(15) self.toLabel.setPixmap(toIcon) # Search button self.searchButton = QtWidgets.QPushButton() self.searchButton.setIcon(QtGui.QIcon('./image/SearchIcon.svg')) self.searchButton.setIconSize(QtCore.QSize(20, 20)) self.searchButton.setCursor(QtGui.QCursor( QtCore.Qt.PointingHandCursor)) self.searchButton.clicked.connect(self.search) # Exchange button self.exchangeButton = QtWidgets.QPushButton() self.exchangeButton.setIcon(QtGui.QIcon('./image/ChangeIcon.svg')) self.exchangeButton.setIconSize(QtCore.QSize(22, 22)) self.exchangeButton.setCursor( QtGui.QCursor(QtCore.Qt.PointingHandCursor)) # Destination label self.destLabel = QtWidgets.QLabel() destIcon = QtGui.QPixmap('./image/DestIcon.svg').scaled( 20, 20, QtCore.Qt.IgnoreAspectRatio) self.destLabel.setPixmap(destIcon) # Destination Input self.destInput = QtWidgets.QLineEdit() self.destInput.setPlaceholderText('Ending Point') self.destInput.setFixedHeight(30) # Set the layout self.left_layout.addWidget(self.sourceLabel, 0, 0, 1, 1) self.left_layout.addWidget(self.sourceInput, 0, 1, 1, 7) self.left_layout.addWidget(self.searchButton, 0, 8, 1, 1) self.left_layout.addWidget(self.toLabel, 1, 0, 1, 1) self.left_layout.addWidget(self.exchangeButton, 1, 8, 1, 1) self.left_layout.addWidget(self.destLabel, 2, 0, 1, 1) self.left_layout.addWidget(self.destInput, 2, 1, 1, 7) self.left_widget.setStyleSheet(''' QPushButton{border:none;color:white;} QLineEdit{border-bottom:1px solid darkGray; border-radius:3px; padding:2px 4px;} QWidget#left_widget{color:#232C51; background:white; border-top:1px solid darkGray; border-left:1px solid darkGray; border-right:1px solid darkGray; border-top-left-radius:5px; border-top-right-radius:5px;}''') # ---------- Route option region ---------- # # Calendar label self.calendarLabel = QtWidgets.QLabel() calendarIcon = QtGui.QPixmap('./image/Calendar.svg').scaled( 20, 20, QtCore.Qt.IgnoreAspectRatio) self.calendarLabel.setPixmap(calendarIcon) # Calendar Input self.calendarInput = QtWidgets.QLineEdit() self.calendarInput.setPlaceholderText('Departure Date') self.calendarInput.setFixedSize(120, 30) # Time label self.timeLabel = QtWidgets.QLabel() timeIcon = QtGui.QPixmap('./image/Time.svg').scaled( 20, 20, QtCore.Qt.IgnoreAspectRatio) self.timeLabel.setPixmap(timeIcon) # Time Input self.timeInput = QtWidgets.QLineEdit() self.timeInput.setPlaceholderText('Dept Time') self.timeInput.setFixedHeight(30) # Calendar label self.calendarLabelArr = QtWidgets.QLabel() self.calendarLabelArr.setPixmap(calendarIcon) # Calendar Input self.calendarInputArr = QtWidgets.QLineEdit() self.calendarInputArr.setPlaceholderText('Arrival Date') self.calendarInputArr.setFixedSize(120, 30) # Time label self.timeLabelArr = QtWidgets.QLabel() self.timeLabelArr.setPixmap(timeIcon) # Time Input self.timeInputArr = QtWidgets.QLineEdit() self.timeInputArr.setPlaceholderText('Arrival Time') self.timeInputArr.setFixedHeight(30) # Transfer Stop self.transLabel = QtWidgets.QLabel() exchangeIcon = QtGui.QPixmap('./image/Exchange.svg').scaled( 20, 20, QtCore.Qt.IgnoreAspectRatio) self.transLabel.setPixmap(exchangeIcon) # Exchange Input self.exchangeInput = QtWidgets.QLineEdit() self.exchangeInput.setPlaceholderText('Max Transfer') self.exchangeInput.setFixedHeight(30) # Set the layout self.left_down_layout.addWidget(self.calendarLabel, 0, 0, 1, 1) self.left_down_layout.addWidget(self.calendarInput, 0, 1, 1, 3) self.left_down_layout.addWidget(self.timeLabel, 0, 4, 1, 1) self.left_down_layout.addWidget(self.timeInput, 0, 5, 1, 3) self.left_down_layout.addWidget(self.timeLabelArr, 1, 4, 1, 1) self.left_down_layout.addWidget(self.timeInputArr, 1, 5, 1, 3) self.left_down_layout.addWidget(self.transLabel, 2, 0, 1, 1) self.left_down_layout.addWidget(self.exchangeInput, 2, 1, 1, 3) self.left_down_widget.setStyleSheet(''' QLineEdit{border-bottom:1px solid darkGray; border-radius:3px; padding:2px 4px;} QWidget#left_down_widget{color:#232C51; background:white; border-left:1px solid darkGray; border-right:1px solid darkGray;}''') # # ---------- Result region ---------- # # scroll = QtGui.QScrollArea() # scroll.setWidget(console) # scroll.setAutoFillBackground(True) # scroll.setWidgetResizable(True) # vbox = QtGui.QVBoxLayout() # vbox.addWidget(scroll) # tab1.setLayout(vbox) self.left_bottom_layout_style = ''' QLineEdit{border-bottom:1px solid darkGray; border-radius:3px; padding:2px 4px;} QWidget#left_bottom_widget{color:#232C51; background:white; border-bottom:1px solid darkGray; border-left:1px solid darkGray; border-right:1px solid darkGray; border-bottom-right-radius:5px; border-bottom-left-radius:5px;}''' self.left_bottom_widget.setStyleSheet(self.left_bottom_layout_style) # ---------- Web region ---------- # # f = codecs.open("./image/Sample_Application.html", 'r', 'utf-8') # html = f.read() html = '' self.web = QWebEngineView() self.web.setHtml(html) self.web.setFixedSize(640, 700) self.right_layout.addWidget(self.web, 0, 0, 12, 8) self.right_widget.setStyleSheet(''' QWidget#right_widget{color:#232C51; background:white; border:1px solid darkGray; border-top-right-radius:5px; border-top-left-radius:5px; border-bottom-right-radius:5px; border-bottom-left-radius:5px;}''') def js_callback(self, result): return ("js_callback: " + str(result))