Example #1
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.qwebengine = QWebEngineView(self.centralwidget)
        self.qwebengine.setGeometry(QtCore.QRect(10, 30, 451, 321))
        self.qwebengine.setAutoFillBackground(False)
        self.qwebengine.setStyleSheet("background-color: rgb(170, 170, 127);")
        self.qwebengine.setObjectName("qwebengine")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 23))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
Example #2
0
 def initUI(self):
     # self.resize(1000, 1000)
     QToolTip.setFont(QFont('SansSerif', 10))
     self.setWindowTitle('直播压力测试')
     self.setWindowIcon(QIcon('favicon.ico'))
     # self.getText()
     self.url_edit = QLineEdit(self)
     self.url_edit.setPlaceholderText('请输入url')
     self.url_edit.setGeometry(5, 5, 800, 20)
     self.nums_edit = QLineEdit(self)
     self.nums_edit.setPlaceholderText('nums')
     self.nums_edit.setGeometry(820, 5, 40, 20)
     # self.label = QLabel(self)
     # self.label.setGeometry(20, 20, 200, 20)
     # print(self.url_edit)
     btn = QPushButton('新建窗口', self)
     btn.setToolTip('新建直播窗口')
     btn.move(900, 5)
     # btn.resize(btn.sizeHint())
     view = QWebEngineView(self)
     view.load(QUrl("https://httpswww.msyk.cn/"))
     view.setGeometry(30, 30, 800, 800)
     # _player = QMediaPlayer(self)
     # _videoSurface =
     self.resize(1000, 1000)
     self.show()
     # 居中屏幕方法,计算屏幕和窗口的坐标差,除以2即是需要移动的坐标值
     screen = QDesktopWidget().screenGeometry()
     size = self.geometry()
     newLeft = (screen.width() - size.width()) / 2
     newTop = (screen.height() - size.height()) / 2
     self.move(newLeft, newTop)
Example #3
0
class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(1009, 685)
        self.pushButtonGo = QtWidgets.QPushButton(Dialog)
        self.pushButtonGo.setGeometry(QtCore.QRect(560, 580, 75, 23))
        self.pushButtonGo.setObjectName("pushButtonGo")
        self.lineEditURL = QtWidgets.QLineEdit(Dialog)
        self.lineEditURL.setGeometry(QtCore.QRect(210, 580, 291, 20))
        self.lineEditURL.setObjectName("lineEditURL")
        self.widget = QWebEngineView(Dialog)
        self.widget.setGeometry(QtCore.QRect(90, 50, 851, 491))
        self.widget.setObjectName("widget")
        self.label = QtWidgets.QLabel(Dialog)
        self.label.setGeometry(QtCore.QRect(100, 580, 91, 21))
        self.label.setObjectName("label")

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.pushButtonGo.setText(_translate("Dialog", "Go"))
        self.label.setText(_translate("Dialog", "Enter URL"))
Example #4
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.qwebengine = QWebEngineView(self.centralwidget)
        self.qwebengine.setGeometry(QtCore.QRect(10, 30, 451, 321))
        self.qwebengine.setAutoFillBackground(False)
        self.qwebengine.setStyleSheet("background-color: rgb(170, 170, 127);")
        self.qwebengine.setObjectName("qwebengine")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 23))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
Example #5
0
class ViewsHelp(QMdiSubWindow):
    def __init__(self, main, url, title):
        """
        Show html view help by given view url.

        :param main: Reference for main windows.
        :param url: The view url.
        :param title: The windows title.
        """
        super(ViewsHelp, self).__init__()

        geo = main.frameGeometry()
        width = int(0.6 * geo.width())
        height = int(0.8 * geo.height())
        self.setWindowTitle(title)
        self.setGeometry(QRect(0, 0, width, height))

        self.subwindow = QWidget()
        p = self.palette()
        p.setColor(self.backgroundRole(), QColor(255, 255, 255))
        self.setPalette(p)
        self.setWidget(self.subwindow)

        self.web_view = QWebEngineView(self.subwindow)
        self.web_view.setGeometry(QRect(0, 0, width, height))
        self.web_view.load(QUrl(url))
        self.web_view.show()
class Window(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.qwebengine = QWebEngineView(self)
        self.qwebengine.setGeometry(QRect(50, 20, 1200, 600))
        self.qwebengine.load(
            QUrl.fromLocalFile('\plotly_html\if_hs300_bais.html'))
Example #7
0
class Ui_Form(object):
    def __init__(self, k):
        config = configparser.ConfigParser()
        config.read('gameSetting.ini')
        self.URL = config['BROWSER']['URL' + str(k)]
        self.gain = config.getfloat('BROWSER', 'gain' + str(k))

        self.Dialog = QtWidgets.QDialog()
        self.setupUi(self.Dialog)

    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(1300, 800)
        Form.setMinimumSize(QtCore.QSize(1300, 800))
        Form.setMaximumSize(QtCore.QSize(1300, 800))
        Form.setMouseTracking(True)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("media/cat.ico"), QtGui.QIcon.Normal,
                       QtGui.QIcon.Off)
        Form.setWindowIcon(icon)
        self.webEngineView = QWebEngineView(Form)
        self.webEngineView.setGeometry(QtCore.QRect(0, 0, 1300, 800))
        self.webEngineView.setMinimumSize(QtCore.QSize(1300, 800))
        self.webEngineView.setMaximumSize(QtCore.QSize(1300, 800))
        self.webEngineView.setMouseTracking(False)
        self.webEngineView.setUrl(QtCore.QUrl(self.URL))
        self.webEngineView.setZoomFactor(self.gain)
        self.webEngineView.setObjectName("webEngineView")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "黑猫浏览器"))
class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(563, 339)
        self.widget = QWebEngineView(Dialog)
        self.widget.setGeometry(QtCore.QRect(10, 60, 531, 251))
        self.widget.setObjectName("widget")
        self.pushButtonGo = QtWidgets.QPushButton(Dialog)
        self.pushButtonGo.setGeometry(QtCore.QRect(450, 20, 91, 23))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.pushButtonGo.setFont(font)
        self.pushButtonGo.setObjectName("pushButtonGo")
        self.lineEditURL = QtWidgets.QLineEdit(Dialog)
        self.lineEditURL.setGeometry(QtCore.QRect(100, 20, 331, 21))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.lineEditURL.setFont(font)
        self.lineEditURL.setObjectName("lineEditURL")
        self.label = QtWidgets.QLabel(Dialog)
        self.label.setGeometry(QtCore.QRect(10, 20, 71, 16))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label.setFont(font)
        self.label.setObjectName("label")

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.pushButtonGo.setText(_translate("Dialog", "Go"))
        self.label.setText(_translate("Dialog", "Enter URL"))
Example #9
0
class Window(BaseWindow):
    def __init__(self):
        self.debug=1
        self.app = QApplication(sys.argv)
        self.desktop= QApplication.desktop()
        self.web = QWebEngineView()
        self.icon = QIcon(ICON)
        #self.web.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks)
      
        self.web.titleChanged.connect(self.title_changed)
        self.web.iconUrlChanged.connect(self.icon_changed)
        self.web.page().windowCloseRequested.connect(self.close_window)
        self.web.page().geometryChangeRequested.connect(self.set_geometry)
    
    def show(self,window_state):
        if window_state == "maximized" and not self.web.isMaximized():
            self.web.showNormal()
            self.web.showMaximized()
        elif window_state == "fullscreen" and not self.web.isFullScreen():
            self.web.showNormal()
            self.web.showFullScreen()
        elif window_state == "normal":
            self.web.showNormal()
        else:
            self.web.show()

    def run(self):
        return self.app.exec_()
                
    def set_debug(self, debuglevel):
        self.debug=debuglevel
    
    def set_geometry(self,geom ):
        self.web.setGeometry(geom)
        
    def close_window(self):
        sys.exit()
    
    def icon_changed(self):
        if not self.icon.isNull():
            self.web.setWindowIcon(self.icon)
            
    def title_changed(self, title):
        self.web.setWindowTitle(title)

    def load_url(self,url):
        self.url=QUrl.fromEncoded(url)
        self.web.setUrl(self.url)
    
    def set_size(self,width, height):
        if width<=0:
            width=640
        if height<=0:
            height=480
        
        left=(self.desktop.width()-width)/2
        top=(self.desktop.height()-height)/2
        
        self.web.setGeometry(left,top,width,height)
Example #10
0
class Window(BaseWindow):
    def __init__(self):
        self.debug = 1
        self.app = QApplication(sys.argv)
        self.desktop = QApplication.desktop()
        self.web = QWebEngineView()
        self.icon = QIcon(ICON)
        #self.web.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks)

        self.web.titleChanged.connect(self.title_changed)
        self.web.iconUrlChanged.connect(self.icon_changed)
        self.web.page().windowCloseRequested.connect(self.close_window)
        self.web.page().geometryChangeRequested.connect(self.set_geometry)

    def show(self, window_state):
        if window_state == "maximized" and not self.web.isMaximized():
            self.web.showNormal()
            self.web.showMaximized()
        elif window_state == "fullscreen" and not self.web.isFullScreen():
            self.web.showNormal()
            self.web.showFullScreen()
        elif window_state == "normal":
            self.web.showNormal()
        else:
            self.web.show()

    def run(self):
        return self.app.exec_()

    def set_debug(self, debuglevel):
        self.debug = debuglevel

    def set_geometry(self, geom):
        self.web.setGeometry(geom)

    def close_window(self):
        sys.exit()

    def icon_changed(self):
        if not self.icon.isNull():
            self.web.setWindowIcon(self.icon)

    def title_changed(self, title):
        self.web.setWindowTitle(title)

    def load_url(self, url):
        self.url = QUrl.fromEncoded(url)
        self.web.setUrl(self.url)

    def set_size(self, width, height):
        if width <= 0:
            width = 640
        if height <= 0:
            height = 480

        left = (self.desktop.width() - width) / 2
        top = (self.desktop.height() - height) / 2

        self.web.setGeometry(left, top, width, height)
Example #11
0
class Window(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.qWebEngine = QWebEngineView(self)
        self.qWebEngine.setGeometry(QRect(50, 20, 1200, 600))
        self.qWebEngine.load(
            QUrl.fromLocalFile('\plotly_html\if_hs300_bais.html'))
        self.setWindowTitle("Plotly Demo")
        self.setWindowIcon(QIcon("./images/Python2.ico"))
Example #12
0
 def display_ah_stat_line(self, int):
     """
     显示程序当前目录下分析生成的html文件
     :return:
     """
     ah_stat_html = QWebEngineView(self.ui.tab_2)
     ah_stat_html.load(QtCore.QUrl("file:///ah_compare_line.html"))
     ah_stat_html.setGeometry(QtCore.QRect(50, 310, 1491, 421))
     ah_stat_html.show()
Example #13
0
class event_key(QWidget):
    def __init__(self):

        super().__init__()
        self.setWindowTitle("Browser by Gabriel F")
        self.setWindowIcon(QIcon("logo.png"))
        self.showMaximized()
        self.setWindowFlags(Qt.WindowCloseButtonHint
                            | Qt.MSWindowsFixedSizeDialogHint)

        #Focus a la ventana
        self.setFocus()

        self.initUI()

    def initUI(self):
        #-------------------------------Widgets------------------------------

        layout = QGridLayout(self)

        #Variable por defecto
        default_url = "https://webfomatica.com/"

        self.browser = QWebEngineView(self)
        self.browser.setGeometry(5, 30, 700, 700)
        self.browser.load(QUrl(default_url))
        self.browser.show()

        #Agregar al layout
        layout.addWidget(self.browser, 0, 0, 1, 1)  #widget

        #Agregar al layout de la clase
        self.setLayout(layout)

    def closeEvent(self, event):
        #Evento cerrar ventana

        close = QMessageBox(self)
        close.setWindowTitle("¡Cerrar ventana!")
        close.setIcon(QMessageBox.Question)
        close.setText("¿Estás seguro que desea salir de la ventana?   ")
        #Opciones
        botonSalir = close.addButton("Salir", QMessageBox.YesRole)
        botonCancelar = close.addButton("Cancelar", QMessageBox.NoRole)

        close.exec_()

        if close.clickedButton() == botonSalir:

            event.accept()

        else:

            event.ignore()
Example #14
0
class AboutDialog(QtWidgets.QDialog, Ui_Dialog):
    def __init__(self):
        super(AboutDialog, self).__init__()
        self.setupUi(self)
        self.setFixedSize(501, 371)

        self.webView = QWebEngineView(self)
        self.webView.setGeometry(QtCore.QRect(0, 20, 481, 281))
        self.webView.setObjectName("webView")

        filenames = 'README'
        md.convert(filenames)
        path = hp.load_file(filenames + '.html')
        self.webView.load(QUrl.fromLocalFile(path))
        self.webView.show()
        self.setWindowTitle(filenames)
Example #15
0
class BrowserDialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName(_fromUtf8("Dialog"))
        Dialog.resize(1024, 768)
        self.qwebview = QWebEngineView(Dialog)
        self.qwebview.setGeometry(QtCore.QRect(0, 50, 1020, 711))
        self.qwebview.setObjectName(_fromUtf8("kwebview"))
        self.lineEdit = QtWidgets.QLineEdit(Dialog)
        self.lineEdit.setGeometry(QtCore.QRect(10, 20, 1000, 25))
        self.lineEdit.setObjectName(_fromUtf8("lineEdit"))

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        Dialog.setWindowTitle(_translate("Browser", "Browser", None))
Example #16
0
class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(562, 488)
        self.widget = QWebEngineView(Dialog)
        self.widget.setGeometry(QtCore.QRect(10, 160, 531, 301))
        self.widget.setObjectName("widget")
        self.pushButtonShowMap = QtWidgets.QPushButton(Dialog)
        self.pushButtonShowMap.setGeometry(QtCore.QRect(210, 110, 101, 31))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.pushButtonShowMap.setFont(font)
        self.pushButtonShowMap.setObjectName("pushButtonShowMap")
        self.lineEditLongitude = QtWidgets.QLineEdit(Dialog)
        self.lineEditLongitude.setGeometry(QtCore.QRect(100, 20, 331, 21))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.lineEditLongitude.setFont(font)
        self.lineEditLongitude.setObjectName("lineEditLongitude")
        self.label = QtWidgets.QLabel(Dialog)
        self.label.setGeometry(QtCore.QRect(10, 20, 71, 21))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label.setFont(font)
        self.label.setObjectName("label")
        self.lineEditLatitude = QtWidgets.QLineEdit(Dialog)
        self.lineEditLatitude.setGeometry(QtCore.QRect(100, 60, 331, 21))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.lineEditLatitude.setFont(font)
        self.lineEditLatitude.setObjectName("lineEditLatitude")
        self.label_2 = QtWidgets.QLabel(Dialog)
        self.label_2.setGeometry(QtCore.QRect(20, 60, 71, 21))
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_2.setFont(font)
        self.label_2.setObjectName("label_2")

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.pushButtonShowMap.setText(_translate("Dialog", "Show Map"))
        self.label.setText(_translate("Dialog", "Longitude"))
        self.label_2.setText(_translate("Dialog", "Latitude"))
class Ui_BTC_LiveGraph(object):
    def setupUi(self, widget):
        self.mypath = os.path.dirname(__file__)
        widget.setObjectName("BTC_LiveGraph")
        widget.resize(1600, 900)
        widget.setAccessibleDescription("")
        self.htmlreader_BTCLiveGraph = QWebEngineView(widget)
        self.htmlreader_BTCLiveGraph.setGeometry(QRect(10, 10, 1500, 800))
        self.htmlreader_BTCLiveGraph.setAccessibleDescription("")
        self.htmlreader_BTCLiveGraph.setObjectName("htmlreader_BTCLiveGraph")

        self.retranslateUi(widget)
        QMetaObject.connectSlotsByName(widget)

    def retranslateUi(self, widget):
        _translate = QCoreApplication.translate
        widget.setWindowTitle(_translate("BTC_LiveGraph", "BTC Live Graph"))
Example #18
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton_2.setGeometry(QtCore.QRect(44, 130, 141, 101))
        self.pushButton_2.setObjectName("pushButton_2")
        self.toolBox = QtWidgets.QToolBox(self.centralwidget)
        self.toolBox.setGeometry(QtCore.QRect(70, 300, 68, 130))
        self.toolBox.setObjectName("toolBox")
        self.page = QtWidgets.QWidget()
        self.page.setGeometry(QtCore.QRect(0, 0, 68, 68))
        self.page.setObjectName("page")
        self.toolBox.addItem(self.page, "")
        self.page_2 = QtWidgets.QWidget()
        self.page_2.setGeometry(QtCore.QRect(0, 0, 68, 68))
        self.page_2.setObjectName("page_2")
        self.toolBox.addItem(self.page_2, "")
        self.webView = QWebEngineView(self.centralwidget)
        self.webView.setGeometry(QtCore.QRect(239, 40, 481, 381))
        self.webView.setUrl(QtCore.QUrl("https://www.baidu.com/"))
        self.webView.setObjectName("webView")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 22))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        self.toolBox.setCurrentIndex(0)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton_2.setText(_translate("MainWindow", "PushButton"))
        self.toolBox.setItemText(self.toolBox.indexOf(self.page),
                                 _translate("MainWindow", "Page 1"))
        self.toolBox.setItemText(self.toolBox.indexOf(self.page_2),
                                 _translate("MainWindow", "Page 2"))
Example #19
0
class UI(QApplication):

    def installKeyFilter(self):
        self._handler = EventHandler(self)
        UI.instance().installEventFilter(self._handler)
        #self.browser.focusProxy().installEventFilter(_handler)

    def __init__(self, argv):
        super(UI, self).__init__(argv)
        margin = 22

        self.browser = QWebEngineView()
        url = 'http://*****:*****@QtCore.pyqtSlot(str, name='takeScreenShot')
    def captureWindowImage(self,filePath):
        if(self.captureFrames):
            #print("Got signal")
            windowSize = self.browser.size()
            #print(windowSize)
            pixmap = QPixmap(windowSize)
            self.browser.render(pixmap)
            #print("Rendered Browser Window")
            pixmap.save(filePath)
            jsonPath=filePath+".json"
            jsonStr= json.dumps(self._handler.keyStatus)
            #print(jsonStr)
            localtime = time.asctime(time.localtime(time.time()))
            print("Screenshot at ", localtime)

            with open(jsonPath, "w") as jsonFile:
                jsonFile.write(jsonStr)
Example #20
0
class Previewer(QWidget):
    instance = 0
    def __init__(self, parent=None, index = -1):
        super(Previewer, self).__init__(parent)
        self.parent = parent
        self.index = index
        self.handle = QWebEngineView()
        self.handle.setGeometry(100, 100, 350, 400)
        self.handle.setWindowTitle("Helper")
        self.handle.setWindowIcon(QIcon('icon.png'))
        if self.index == 0:
            link = "help\\read_time.html"
        elif self.index == 1:
            link = "help\\set_time.html"
        elif self.index == 2:
            link = "help\\read_date.html"
        elif self.index == 3:
            link = "help\\set_date.html"
        elif self.index == 4:
            link = "help\\set_cursor.html"
        elif self.index == 5:
            link = "help\\char_input.html"
        elif self.index == 6:
            link = "help\\char_output.html"
        elif self.index == 7:
            link = "help\\disc_space.html"
        else:
            link = "help\\index.html"
        page = open(link, 'r').read()
        self.page = QWebEnginePage()
        self.page.setHtml(page)
        self.handle.setPage(self.page)
        self.handle.show()


    def zamknij(self):
        Previewer.instance -= 1
        self.handle.destroy()
Example #21
0
class QAboutWidget(QWidget):
    def __init__(self, parent = None):
        super().__init__()
        self.setParent(parent)
        self.initUI()

    def initUI(self):
        self.Athena_About_Browser = QWebEngineView(self)
        url = 'https://overclockedthompson.wixsite.com/athena'
        self.Athena_About_Browser.load(QUrl(url))
        self.Athena_About_Browser.show()

    def resizeEvent(self, QResizeEvent):
        self.Athena_About_Browser.setGeometry(0,0,self.width(),self.height())
    def setGeometry(self, *__args):
        super().setGeometry(*__args)

    def paintEvent(self, event):
        super(type(self), self).paintEvent(event)
        styleSheet = QStyleOption()
        styleSheet.initFrom(self)
        paint = QPainter(self)
        styling = self.style()
        styling.drawPrimitive(QStyle.PE_CustomBase, styleSheet, paint, self)
Example #22
0
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_()

Example #23
0
altura = 1050
root.setGeometry(0, 0, largura, altura)
root.setWindowTitle('Navegador Python')
root.setMinimumHeight(altura)
root.setMaximumHeight(altura)
root.setMinimumWidth(largura)
root.setMaximumWidth(largura)
root.setStyleSheet('background-color: rgb(0,0,0);')

# WEB
home_url = 'https://www.google.com'
facebook_url = 'https://www.facebook.com'
ytb = 'https://www.youtube.com'

web = QWebEngineView(root)
web.setGeometry(0, 30, largura, altura)
web.setStyleSheet('background-color: rgb(255,255,255);')
web.load(QUrl(home_url))


# SEARCH LINE EDIT

go_line = QLineEdit(root)
go_line.setGeometry(200, 3, 255, 24)
go_line.setStyleSheet('background-color: rgb(255,255,255);')

#	BOTOES


class BT():
    def __init__(self, pos_x, png):
class MainWindow(QMainWindow, ui):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        # Additional Initialization
        Initial_path = QDir.currentPath()
        self.setWindowIcon(QIcon(":/IAID.ico"))
        self.PNloc.setText(os.path.join(Initial_path, 'PN_sample.CSV'))
        self.Querybox.setVisible(False)
        self.DB.setVisible(False)
        self.PDFloc.setText(os.path.join(Initial_path, 'PDF_Download'))
        self.APT.setDate(
            QtCore.QDate(int(time.strftime("%Y")), int(time.strftime("%m")),
                         int(time.strftime("%d"))))
        self.IDT.setDate(
            QtCore.QDate(int(time.strftime("%Y")), int(time.strftime("%m")),
                         int(time.strftime("%d"))))
        self.TTL.setChecked(True)
        self.ISD.setChecked(True)
        self.CPC.setChecked(True)
        self.ABST.setChecked(True)
        self.AN.setChecked(True)
        self.PDF.setChecked(True)
        self.PNbt.setChecked(True)
        self.ut.setChecked(True)
        self.MODEL = QtGui.QStandardItemModel()
        self.MODEL.setColumnCount(17)
        self.MODEL.setHorizontalHeaderLabels([''] * 17)
        self.TABLE.setModel(self.MODEL)
        self.TABLE.setShowGrid(True)
        self.TABLE.setAlternatingRowColors(True)
        #setColumnWidth(0, 85)
        #self.TABLE.resizeColumnsToContents()
        #.setRowHeight(row, 18)
        self.webView = QWebEngineView(self.GL)
        self.webView.setGeometry(QtCore.QRect(0, 0, 1011, 491))
        self.webView.settings().setAttribute(QWebEngineSettings.PluginsEnabled,
                                             True)
        self.webView.load(
            QUrl(
                "http://patft.uspto.gov/netacgi/nph-Parser?Sect1=PTO2&Sect2=HITOFF&u=%2Fnetahtml%2FPTO%2Fsearch-adv.htm&r=1&p=1&f=G&l=50&d=PTXT&S1=9532164.PN.&OS=pn/9532164&RS=PN/9532164"
            ))
        self.webView.show()

        # Events
        self.statusBar.showMessage('Welcome!')
        self.PNbws.clicked.connect(self.FileDialog2Line_PNCSV)
        self.PDFbws.clicked.connect(self.FileDialog2Line_PDF)
        self.DB.currentIndexChanged.connect(self.DB2filter)

        # Execution
        self.IMPORT.clicked.connect(self.importPN)
        self.EXPORT.clicked.connect(self.handleSave)
        self.FILTER.clicked.connect(self.TABLE_FILTER)
        self.PDFD.clicked.connect(self.PDFDOWNLOAD)
        self.INFO.clicked.connect(self.Crawler)
        self.STOPLOOP.clicked.connect(self.stopbool)
        self.web_PDF.clicked.connect(self.showPDF)
        self.web_PAT.clicked.connect(self.showPAT)
        self.stop = False

    def showPAT(self):
        PN = self.PNweb.text()
        _, PatFT_link, _, _, _ = ptc.PN_str_and_url(PN)
        self.webView.load(QUrl(PatFT_link))
        self.webView.show()

    def showPDF(self):
        PN = self.PNweb.text()
        _, _, _, PDF_link_full, _ = ptc.PN_str_and_url(PN)
        #self.webView.load(QUrl(PDF_link_full))
        #self.webView.show()
        QDesktopServices.openUrl(QUrl(PDF_link_full))

    def stopbool(self):
        self.stop = True

    def PDFDOWNLOAD(self):
        self.stop = False
        self.PDFD.setEnabled(False)
        # demand: 0=do not download, 1=download full text, 2=download drawing section, 3=download both
        if self.cs2b(self.PDFfull) == 0 and self.cs2b(self.PDFdraw) == 0:
            self.statusBar.showMessage('Please select something to download!')
            self.PDFD.setEnabled(True)
            return
        elif self.cs2b(self.PDFfull) == 1 and self.cs2b(self.PDFdraw) == 0:
            pdf_demand = 1
        elif self.cs2b(self.PDFfull) == 0 and self.cs2b(self.PDFdraw) == 1:
            pdf_demand = 2
        elif self.cs2b(self.PDFfull) == 1 and self.cs2b(self.PDFdraw) == 1:
            pdf_demand = 3

        # return if PN hasn't been imported
        if self.MODEL.headerData(0, Qt.Horizontal) != 'Patent No.':
            self.statusBar.showMessage('Please import Patent Numers first!')
            self.PDFD.setEnabled(True)
            return

        error_download = 0
        cwd = os.getcwd()
        PDF_loc = self.PDFloc.text()
        if not os.path.exists(PDF_loc):
            os.makedirs(PDF_loc)
        os.chdir(PDF_loc)

        totalrow = self.MODEL.rowCount()
        for i in range(totalrow):
            if self.stop:
                break
            QApplication.processEvents()
            PN = str(self.MODEL.data(self.MODEL.index(i, 0)))
            PN, PatFT_link, PN_PDF, PDF_link_full, PDF_link_page = ptc.PN_str_and_url(
                PN)
            status, mes = ptc.PDF_download(PN, PatFT_link, PN_PDF,
                                           PDF_link_full, PDF_link_page,
                                           pdf_demand)
            self.statusBar.showMessage('US' + PN + ' ( ' + str(i + 1) + ' / ' +
                                       str(totalrow) + ' ): ' + mes)
            if not status:
                error_download += 1
        if self.stop:
            self.stop = False
            self.statusBar.showMessage('The program is stop on your demand.')
        elif error_download == 0:
            self.statusBar.showMessage('PDF downloaded sucessfully!')
        else:
            self.statusBar.showMessage('PDF downloaded, but ' +
                                       str(error_download) + 'errors exist')
        os.chdir(cwd)
        self.PDFD.setEnabled(True)

    def Crawler(self):
        self.INFO.setEnabled(False)
        self.stop = False
        # return if PN hasn't been imported
        if self.MODEL.headerData(0, Qt.Horizontal) != 'Patent No.':
            self.statusBar.showMessage('Please import Patent Numers first!')
            self.INFO.setEnabled(True)
            return

        self.statusBar.showMessage('Fetching info for you...')
        row = self.MODEL.rowCount()
        Item_b = [self.cs2b(self.TTL),   self.cs2b(self.ISD),  self.cs2b(self.APD),  self.cs2b(self.IN),   self.cs2b(self.AANM),\
                  self.cs2b(self.AN),    self.cs2b(self.CPC),  self.cs2b(self.CPCs), self.cs2b(self.IPC),  self.cs2b(self.IPCs),\
                  self.cs2b(self.REFby), self.cs2b(self.ABST), self.cs2b(self.FMID), self.cs2b(self.ApNo), self.cs2b(self.PAT), self.cs2b(self.PDF)]
        Item = []
        for i in range(16):
            if Item_b[i] == 1:
                Item.append(i)
        del Item_b
        Head = ["Title","Issue Date", "Application Date", "Inventors", "Applicant", "Assignee", "CPC", "CPC-subclass",\
            "IPC", "IPC-subclass","Referenced by","Abstract", "Family ID",  "Appl. No.", "PatFT Link", "PDF Link"]
        Head = ["Patent No."] + [Head[i] for i in Item]
        Head = Head + (17 - len(Head)) * [' ']
        self.MODEL.setHorizontalHeaderLabels(Head)

        for i in range(row):
            if self.stop:
                break
            QApplication.processEvents()
            PN = str(self.MODEL.data(self.MODEL.index(i, 0)))
            if PN == 'Filtered':
                continue
            PN, PatFT_link, PN_PDF, PDF_link_full, PDF_link_page = ptc.PN_str_and_url(
                PN)
            soup = URL2Soup(PatFT_link)
            ttl = ptc.TTL(soup)
            if len(ttl) < 2:
                time.sleep(1)
                QApplication.processEvents()
                soup = URL2Soup1(PatFT_link)
                ttl = ptc.TTL(soup)
                if len(ttl) < 2:
                    time.sleep(1)
                    QApplication.processEvents()
                    soup = URL2Soup1(PatFT_link)
                    ttl = ptc.TTL(soup)
                    if len(ttl) < 2:
                        time.sleep(1)
                        QApplication.processEvents()
                        soup = URL2Soup1(PatFT_link)
                        ttl = ptc.TTL(soup)
                        if len(ttl) < 2:
                            time.sleep(1)
                            QApplication.processEvents()
                            soup = URL2Soup2(PatFT_link)
                            ttl = ptc.TTL(soup)
                            if len(ttl) < 2:
                                time.sleep(1)
                                QApplication.processEvents()
                                soup = URL2Soup2(PatFT_link)
                                ttl = ptc.TTL(soup)
                                if len(ttl) < 2:
                                    time.sleep(1)
                                    QApplication.processEvents()
                                    soup = URL2Soup2(PatFT_link)
                                    ttl = ptc.TTL(soup)
            j = 1
            #Title
            if 0 in Item:
                try:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem(ttl))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()
            # Issue Date
            if 1 in Item:
                try:
                    self.MODEL.setItem(i, j,
                                       QtGui.QStandardItem(ptc.ISD(soup)))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()
            # Application Date
            if 2 in Item:
                try:
                    self.MODEL.setItem(i, j,
                                       QtGui.QStandardItem(ptc.APD(soup)))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()
            # Inventor
            if 3 in Item:
                try:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem(ptc.IN(soup)))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()
            #Applicant
            if 4 in Item:
                try:
                    self.MODEL.setItem(i, j,
                                       QtGui.QStandardItem(ptc.AANM(soup)))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()
            # Assignee
            if 5 in Item:
                try:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem(ptc.AN(soup)))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()
            # CPC
            if 6 in Item:
                try:
                    self.MODEL.setItem(i, j,
                                       QtGui.QStandardItem(ptc.CPC(soup)))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()
            # CPC subclass
            if 7 in Item:
                try:
                    self.MODEL.setItem(i, j,
                                       QtGui.QStandardItem(ptc.CPCs(soup)))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()
            # IPC
            if 8 in Item:
                try:
                    self.MODEL.setItem(i, j,
                                       QtGui.QStandardItem(ptc.IPC(soup)))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()
            # IPC subclass
            if 9 in Item:
                try:
                    self.MODEL.setItem(i, j,
                                       QtGui.QStandardItem(ptc.IPCs(soup)))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()
            # Number of referenced by
            if 10 in Item:
                try:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem(ptc.REF(PN)))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()
            # Abstract
            if 11 in Item:
                try:
                    self.MODEL.setItem(i, j,
                                       QtGui.QStandardItem(ptc.ABST(soup)))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()
            # Family ID
            if 12 in Item:
                try:
                    self.MODEL.setItem(i, j,
                                       QtGui.QStandardItem(ptc.FMID(soup)))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()
            # Application Number
            if 13 in Item:
                try:
                    self.MODEL.setItem(i, j,
                                       QtGui.QStandardItem(ptc.ApNo(soup)))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()
            # PatFT link
            if 14 in Item:
                try:
                    self.MODEL.setItem(
                        i, j,
                        QtGui.QStandardItem('=HYPERLINK("' + PatFT_link +
                                            '")'))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()
            # PDF link
            if 15 in Item:
                try:
                    self.MODEL.setItem(
                        i, j,
                        QtGui.QStandardItem('=HYPERLINK("' + PDF_link_full +
                                            '")'))
                except:
                    self.MODEL.setItem(i, j, QtGui.QStandardItem('error'))
                j += 1
                QApplication.processEvents()

        if self.stop:
            self.stop = False
            self.statusBar.showMessage(
                'The program is stopped on your demand.')
        else:
            self.statusBar.showMessage('Done.')
        self.INFO.setEnabled(True)

    # Filter PNs and delete them
    def TABLE_FILTER(self):
        self.FILTER.setEnabled(False)
        self.stop = False
        PNtype_limit = np.array([
            self.cs2b(self.ut),
            self.cs2b(self.ds),
            self.cs2b(self.pp),
            self.cs2b(self.ot)
        ])
        if self.MODEL.headerData(0, Qt.Horizontal) != 'Patent No.':
            self.statusBar.showMessage('Please import Patent Numers first!')
            self.FILTER.setEnabled(True)
            return
        if self.cs2b(self.APDdis) == 0 and self.cs2b(
                self.ISDdis) == 0 and (self.cs2b(self.all) == 1
                                       or sum(PNtype_limit) == 4):
            self.statusBar.showMessage('Nothing will be filtered.')
            self.FILTER.setEnabled(True)
            return
        row = self.MODEL.rowCount()

        #Time range
        Afy, Afm, Afd = self.APF.date().year(), self.APF.date().month(
        ), self.APF.date().day()
        Aty, Atm, Atd = self.APT.date().year(), self.APT.date().month(
        ), self.APT.date().day()
        Ify, Ifm, Ifd = self.IDF.date().year(), self.IDF.date().month(
        ), self.IDF.date().day()
        Ity, Itm, Itd = self.IDT.date().year(), self.IDT.date().month(
        ), self.IDT.date().day()
        APD_limit = np.array([Afy, Afm, Afd, Aty, Atm, Atd])
        ISD_limit = np.array([Ify, Ifm, Ifd, Ity, Itm, Itd])

        delete_list = []
        for i in range(row):
            if self.stop:
                break
            self.statusBar.showMessage('Filtering: ' + str(len(delete_list)) +
                                       ' patents are filtered. ( ' +
                                       str(i + 1) + ' / ' + str(row) + ' )')
            PN = str(self.MODEL.data(self.MODEL.index(i, 0)))
            PN, PatFT_link, _, _, _ = ptc.PN_str_and_url(PN)
            APD_str, ISD_str = '', ''
            # derive soup only if necessary (since it's time consuming)
            if self.cs2b(self.APDdis) != 0 or self.cs2b(self.ISDdis) != 0:
                soup = URL2Soup(PatFT_link)
                QApplication.processEvents()
                APD_str = ptc.APD(soup)
                ISD_str = ptc.ISD(soup)
            now = datetime.datetime.now()
            # Do not filter patent type if 'all' is checked
            if self.cs2b(self.all) != 1:
                if not ptc.PNtype_filter(PN, PNtype_limit):
                    delete_list += [i]
                    self.MODEL.setItem(i, 0, QtGui.QStandardItem('Filtered'))
                    continue
            # Do not filter appl. date if (1) user do not want to, (2) appl. date isn't listed, (3) (start time <1790/1/1) AND (end time> now)
            if self.cs2b(self.APDdis) == 1 and len(APD_str) > 1 and not (
                    datetime.datetime(Afy, Afm, Afd) <= datetime.datetime(
                        1790, 1, 1)
                    and datetime.datetime(Aty, Atm, Atd) >= now):
                if not ptc.Date_filter(APD_str, APD_limit):
                    delete_list += [i]
                    self.MODEL.setItem(i, 0, QtGui.QStandardItem('Filtered'))
                    continue
            # Do not filter issue date if (1) user do not want to, (2) issue date isn't listed, (3) (start time <1790/1/1) AND (end time> now)
            if len(ISD_str) > 1 and self.cs2b(self.ISDdis) == 1 and not (
                    datetime.datetime(Ify, Ifm, Ifd) <= datetime.datetime(
                        1790, 1, 1)
                    and datetime.datetime(Ity, Itm, Itd) >= now):
                if not ptc.Date_filter(ISD_str, ISD_limit):
                    delete_list += [i]
                    self.MODEL.setItem(i, 0, QtGui.QStandardItem('Filtered'))
                    continue
            QApplication.processEvents()
        if self.stop:
            self.stop = False
            self.statusBar.showMessage(
                'The program is stopped on your demand.')
        # delete unwanted PN
        elif len(delete_list) > 0:
            delete_list_arr = np.array(delete_list)
            for row_index in delete_list:
                self.MODEL.removeRow(
                    row_index -
                    len(delete_list_arr[delete_list_arr < row_index]))
                self.statusBar.showMessage('Deleting the filtered data.....')
        self.statusBar.showMessage('Done Filtering: ' + str(len(delete_list)) +
                                   ' out of ' + str(row) +
                                   ' patents are filtered.')
        self.FILTER.setEnabled(True)

    # import PN with a existing CSV file
    def import_PNlist_CSV(self, list_loc):
        with open(list_loc) as csvr:
            reader = csv.reader(csvr)
            count = 0
            for row in reader:
                count += 1
                self.statusBar.showMessage(
                    'There are %d patent numbers in the list. Preparing the list...'
                    % count)
                QApplication.processEvents()
            csvr.seek(0)
            self.MODEL.clear()
            self.MODEL.setHorizontalHeaderLabels(['Patent No.'] + [''] * 16)
            i = 0
            error_count = 0
            for row in reader:
                if self.stop:
                    break
                PN = str(row[0]).replace(' ', '').replace(',', '')
                self.MODEL.setItem(i, 0, QtGui.QStandardItem(PN))
                """
                if requests.get("http://patft.uspto.gov/netacgi/nph-Parser?Sect2=PTO1&Sect2=HITOFF&p=1&u=/netahtml/PTO/search-bool.html&r=1&f=G&l=50&d=PALL&RefSrch=yes&Query=PN/"+row[0]).status_code!=200:
                    self.MODEL.setItem(i,1, QtGui.QStandardItem('NO') )
                else:
                    self.MODEL.setItem(i,1, QtGui.QStandardItem('YES') )
                """
                try:
                    int(PN)
                except:
                    try:
                        int(PN[1:])
                        if (PN[0].lower not in [
                                'h', 't', 'd', 'x'
                        ]) and (requests.get(
                                "http://patft.uspto.gov/netacgi/nph-Parser?Sect2=PTO1&Sect2=HITOFF&p=1&u=/netahtml/PTO/search-bool.html&r=1&f=G&l=50&d=PALL&RefSrch=yes&Query=PN/1"
                                + PN).status_code != 200):
                            self.MODEL.setItem(
                                i, 1,
                                QtGui.QStandardItem(
                                    'Not a proper patent number! Please check again.'
                                ))
                            error_count += 1
                    except:
                        try:
                            int(PN[2:])
                            if (PN[0:2].lower not in [
                                    're', 'rx', 'pp', 'ai'
                            ]) and (requests.get(
                                    "http://patft.uspto.gov/netacgi/nph-Parser?Sect2=PTO1&Sect2=HITOFF&p=1&u=/netahtml/PTO/search-bool.html&r=1&f=G&l=50&d=PALL&RefSrch=yes&Query=PN/1"
                                    + PN).status_code != 200):
                                self.MODEL.setItem(
                                    i, 1,
                                    QtGui.QStandardItem(
                                        'Not a proper patent number! Please check again.'
                                    ))
                                error_count += 1
                        except:
                            self.MODEL.setItem(
                                i, 1,
                                QtGui.QStandardItem(
                                    'Not a proper patent number! Please check again.'
                                ))
                            error_count += 1
                QApplication.processEvents()
                i += 1
            if self.stop:
                self.stop = False
                self.statusBar.showMessage(
                    'The program is stopped on your demand.')
            elif error_count == 0:
                self.statusBar.showMessage(
                    'Patent list is ready! There are %d patents.' % count)
            else:
                self.statusBar.showMessage(
                    'Patent list is ready but ' + str(error_count) +
                    'out of %d patent numbers are not in proper formats.' %
                    count)
                self.MODEL.setHorizontalHeaderLabels(['Patent No.', 'Errors'])

    def importPN(self):
        self.IMPORT.setEnabled(False)
        self.FILTER.setEnabled(False)
        self.INFO.setEnabled(False)
        self.PDFD.setEnabled(False)
        self.stop = False
        if self.PNbt.isChecked():
            self.MODEL.clear()
            list_loc = self.PNloc.text()
            if not os.path.exists(list_loc):
                self.statusBar.showMessage(
                    "The path of input PN list doesn't exist. Please check again."
                )
            elif list_loc[-3:].lower() != 'csv':
                self.statusBar.showMessage(
                    'This not a CSV file! Please check again.')
            else:
                self.import_PNlist_CSV(list_loc)
        elif self.Querybt.isChecked():
            self.MODEL.clear()
            self.statusBar.showMessage('Preparing patent list...')
            if self.DB.currentIndex() == 0:
                db = 'PTXT'
            else:
                db = 'PALL'
            query = self.Querybox.toPlainText()
            total_PTnumber, PN_1st_page, message = getInfofromQuery_1st_page(
                query, db)
            self.statusBar.showMessage(
                'There are %d patents can be searched with this query.' %
                total_PTnumber)
            if total_PTnumber == 0:
                self.statusBar.showMessage(message)
            elif total_PTnumber <= 50:
                self.MODEL.setHorizontalHeaderLabels(['Patent No.'])
                for i in range(total_PTnumber):
                    self.MODEL.setItem(i, 0,
                                       QtGui.QStandardItem(PN_1st_page[i]))
                    QApplication.processEvents()
                self.statusBar.showMessage(
                    'Patent list is ready! There are %d patents.' %
                    total_PTnumber)
            else:
                pages = int(total_PTnumber /
                            50) + 1 if total_PTnumber % 50 != 0 else int(
                                total_PTnumber / 50)
                search_pages = [(
                    'http://patft.uspto.gov/netacgi/nph-Parser?Sect1=PTO2&Sect2=HITOFF&u=%2Fnetahtml%2FPTO%2Fsearch-adv.htm&r=0&p='
                    + str(i + 1) + '&f=S&l=50&Query=' + query + '&d=' + db)
                                for i in range(pages)]
                self.MODEL.setHorizontalHeaderLabels(['Patent No.'])
                i = 0
                for link in search_pages:
                    if self.stop:
                        break
                    soup = URL2Soup(link)
                    PN_list = getPNfromSoup_one_page(soup)
                    j = 1
                    for PN in PN_list:
                        index = i * 50 + j
                        self.MODEL.setItem(index - 1, 0,
                                           QtGui.QStandardItem(PN))
                        self.statusBar.showMessage((
                            'There are ' + str(total_PTnumber) +
                            ' patents can be searched with this query. Acquiring patent numbers: '
                            + str(index) + ' / ' + str(total_PTnumber)))
                        QApplication.processEvents()
                        j += 1
                    i += 1
                if self.stop:
                    self.stop = False
                    self.statusBar.showMessage(
                        'The program is stopped on your demand.')
                else:
                    self.statusBar.showMessage(
                        'Patent list is ready! There are %d patents.' %
                        total_PTnumber)
        self.IMPORT.setEnabled(True)
        self.FILTER.setEnabled(True)
        self.INFO.setEnabled(True)
        self.PDFD.setEnabled(True)

    def handleSave(self):
        path = self.FileDialog2Line_OutCSV()
        try:
            os.path.exists(path)
        except:
            return
        if os.path.exists(path):
            with open(os.path.join(path, 'Result.CSV'), 'w',
                      newline='') as stream:
                writer = csv.writer(stream)
                header = []
                for i in range(17):
                    header.append(self.MODEL.headerData(i, Qt.Horizontal))
                writer.writerow(header)
                for row in range(self.MODEL.rowCount()):
                    if self.stop:
                        break
                    rowdata = []
                    for column in range(self.MODEL.columnCount()):
                        item = self.MODEL.item(row, column)
                        if item is not None:
                            rowdata.append(item.text())
                        else:
                            rowdata.append('')
                    writer.writerow(rowdata)
                if self.stop:
                    self.stop = False
                    self.statusBar.showMessage(
                        'The program is stopped by demand.')
                else:
                    self.statusBar.showMessage('Result.CSV is saved.')

    def FileDialog2Line_PNCSV(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getOpenFileName(
            self,
            "Select a CSV file containing Patent Numbers",
            "",
            "CSV Files (*.csv);;All Files (*)",
            options=options)
        del options
        if fileName:
            self.PNloc.setText(fileName)
        del fileName

    def FileDialog2Line_OutCSV(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileName = QFileDialog.getExistingDirectory(self,
                                                    "Saving Result.CSV at:",
                                                    options=options)
        del options
        if fileName:
            return fileName

    def FileDialog2Line_PDF(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileName = QFileDialog.getExistingDirectory(self,
                                                    "Saving PDF files at:",
                                                    "",
                                                    options=options)
        del options
        if fileName:
            self.PDFloc.setText(fileName)
        del fileName

    def DB2filter(self):
        if self.DB.currentIndex() == 0:
            self.APF.setDate(QtCore.QDate(1976, 1, 1))
            self.IDF.setDate(QtCore.QDate(1976, 1, 1))
        else:
            self.APF.setDate(QtCore.QDate(1790, 1, 1))
            self.IDF.setDate(QtCore.QDate(1790, 1, 1))

    def cs2b(self, box):
        if box.checkState() == 2:
            return 1
        else:
            return 0
Example #25
0
class UI(QApplication):

    def installKeyFilter(self):
        UI.instance().installEventFilter(self._handler)
        #self.browser.focusProxy().installEventFilter(_handler)

    def getBrowserScreenshot(self):
        #print('Taking screenshot')
        windowSize = self.browser.size()
        pixmap = QPixmap(windowSize)
        self.browser.render(pixmap)
        buffer = QBuffer()
        buffer.open(QBuffer.ReadWrite)
        pixmap.save(buffer, "PNG")
        pil_im = Image.open(io.BytesIO(buffer.data()))
        return pil_im


    def getFrameAndDrive_bkp(self):
        image = self.getBrowserScreenshot()
        action=get_action_for_image(image, self.model)
        key=get_key_for_action(action)
        print(action+" --> "+str(key))
        event_key_press = QKeyEvent(QEvent.KeyPress, key, Qt.NoModifier)
        event_key_up = QKeyEvent(QEvent.KeyRelease, key, Qt.NoModifier)
        recipient = self.browser.focusProxy()
        QApplication.postEvent(recipient, event_key_press)
        #time.sleep(0.0025)
        QApplication.postEvent(recipient, event_key_up)
        return

    curKey=None

    def sendKey(self,key):
        recipient = self.browser.focusProxy()
        if( self.curKey is not None and key!=self.curKey):
            event_key_up = QKeyEvent(QEvent.KeyRelease, self.curKey, Qt.NoModifier)
            QApplication.postEvent(recipient, event_key_up)

        event_key_press = QKeyEvent(QEvent.KeyPress, key, Qt.NoModifier)
        QApplication.postEvent(recipient, event_key_press)
        if(key != Qt.Key_Up):
            self.curKey = key

    def getFrameAndDrive(self):
        image = self.getBrowserScreenshot()
        action=get_action_for_image(image, self.model)
        key = get_key_for_action(action)
        print(action + " --> " + str(key))
        self.sendKey(Qt.Key_Up);
        self.sendKey(key);
        return



    def __init__(self, argv):
        super(UI, self).__init__(argv)
        margin = 22

        self.model = get_model()
        self.browser = QWebEngineView()
        url = 'http://localhost:'+str(http_port)+'/driving_sim/racer1/javascript-racer/v2.curves.html'
        print("Loading URL : "+url)
        self.browser.setGeometry(200, 200, 640 + margin, 480 + margin)
        self.browser.load(QUrl(url))
        self.browser.show()
        self.thread = background_threds.DriverThread.GameDriverThread(ui=self,interval=.2)
        self.thread.driveSignal.connect(self.getFrameAndDrive)
Example #26
0
class Ui_Form(object):
    def setupUi(self, Form):
        self.path = './graph/monthtype.html'
        Form.setObjectName("Form")
        self.setWindowIcon(QIcon('douyin.png'))
        Form.resize(905, 700)
        self.widget = QWebEngineView(self)
        # 原来的self.widget.setGeometry(QtCore.QRect(0, 88, 910, 650))
        self.widget.setGeometry(QtCore.QRect(-9, 90, 927, 635))  #h=644 y=90
        self.widget.setObjectName("widget")
        font = QtGui.QFont()
        font.setFamily("幼圆")
        font.setPointSize(10)
        self.comboBox_2 = QtWidgets.QComboBox(Form)
        self.comboBox_2.setGeometry(QtCore.QRect(130, 20, 111, 49))
        self.comboBox_2.setObjectName("comboBox_2")
        self.comboBox_2.setFont(font)
        self.comboBox_2.addItem("")
        self.comboBox_2.addItem("")
        self.comboBox_2.addItem("")
        self.comboBox_2.addItem("")
        self.comboBox_2.addItem("")
        self.label_2 = QtWidgets.QLabel(Form)
        self.label_2.setGeometry(QtCore.QRect(49, 20, 69, 41))
        font = QtGui.QFont()
        font.setFamily("幼圆")
        font.setPointSize(18)
        self.label_2.setFont(font)
        self.label_2.setObjectName("label_2")
        self.comboBox_4 = QtWidgets.QComboBox(Form)
        self.comboBox_4.setGeometry(QtCore.QRect(338, 20, 92, 49))
        self.comboBox_4.setObjectName("comboBox_4")
        font.setFamily("幼圆")
        font.setPointSize(11)
        self.comboBox_4.setFont(font)
        self.comboBox_4.addItem("")
        self.comboBox_4.addItem("")
        self.comboBox_4.addItem("")
        self.comboBox_4.addItem("")
        self.comboBox_4.addItem("")
        self.comboBox_4.addItem("")
        self.comboBox_4.addItem("")
        self.comboBox_4.addItem("")
        self.comboBox_4.addItem("")
        self.comboBox_4.addItem("")
        self.comboBox_4.addItem("")
        self.comboBox_4.addItem("")
        self.label_4 = QtWidgets.QLabel(Form)
        self.label_4.setGeometry(QtCore.QRect(262, 20, 69, 41))
        font = QtGui.QFont()
        font.setFamily("幼圆")
        font.setPointSize(18)
        self.label_4.setFont(font)
        self.label_4.setObjectName("label_4")
        self.radioButton = QtWidgets.QRadioButton(Form)
        self.radioButton.setGeometry(QtCore.QRect(462, 21, 125, 41))
        font = QtGui.QFont()
        font.setFamily("Yu Gothic UI Semilight")
        font.setPointSize(10)
        self.radioButton.setFont(font)
        self.radioButton.setObjectName("radioButton")
        self.checkBox = QtWidgets.QCheckBox(Form)
        self.checkBox.setGeometry(QtCore.QRect(692, 21, 133, 41))
        font = QtGui.QFont()
        font.setFamily("Yu Gothic UI Semilight")
        font.setPointSize(10)
        self.checkBox.setFont(font)
        self.checkBox.setObjectName("checkBox")
        #美化
        self.meihuabt1 = QtWidgets.QPushButton(Form)
        self.meihuabt1.setGeometry(QtCore.QRect(4, 2, 14, 14))
        self.meihuabt1.setText("")
        self.meihuabt1.setObjectName("meihuabt1")
        self.meihuabt2 = QtWidgets.QPushButton(Form)
        self.meihuabt2.setGeometry(QtCore.QRect(32, 2, 14, 14))
        self.meihuabt2.setText("")
        self.meihuabt2.setObjectName("meihuabt2")
        self.meihuabt3 = QtWidgets.QPushButton(Form)
        self.meihuabt3.setGeometry(QtCore.QRect(60, 2, 14, 14))
        self.meihuabt3.setText("")
        self.meihuabt3.setObjectName("meihuabt3")
        self.meihuabt1.setStyleSheet(
            '''QPushButton{background:#F76677;border-radius:5px;}QPushButton:hover{background:red;}'''
        )
        self.meihuabt2.setStyleSheet(
            '''QPushButton{background:#F7D674;border-radius:5px;}QPushButton:hover{background:yellow;}'''
        )
        self.meihuabt3.setStyleSheet(
            '''QPushButton{background:#6DDF6D;border-radius:5px;}QPushButton:hover{background:green;}'''
        )
        Form.setWindowOpacity(0.96)
        Form.setWindowFlag(QtCore.Qt.FramelessWindowHint)
        Form.setStyleSheet('''background-color:#FFF0F50 ;''')
        self.meihuabt3.clicked.connect(self.close)
        self.meihuabt1.clicked.connect(self.showMinimized)
        self.radioButton.toggled.connect(self.display)
        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "电影词云"))
        self.comboBox_2.setItemText(0, _translate("Form", "所有年份"))
        self.comboBox_2.setItemText(1, _translate("Form", "  2018"))
        self.comboBox_2.setItemText(2, _translate("Form", "  2017"))
        self.comboBox_2.setItemText(3, _translate("Form", "  2016"))
        self.comboBox_2.setItemText(4, _translate("Form", "  2015"))
        self.label_2.setText(_translate("Form", "年份"))
        self.comboBox_4.setItemText(0, _translate("Form", "  1"))
        self.comboBox_4.setItemText(1, _translate("Form", "  2"))
        self.comboBox_4.setItemText(2, _translate("Form", "  3"))
        self.comboBox_4.setItemText(3, _translate("Form", "  4"))
        self.comboBox_4.setItemText(4, _translate("Form", "  5"))
        self.comboBox_4.setItemText(5, _translate("Form", "  6"))
        self.comboBox_4.setItemText(6, _translate("Form", "  7"))
        self.comboBox_4.setItemText(7, _translate("Form", "  8"))
        self.comboBox_4.setItemText(8, _translate("Form", "  9"))
        self.comboBox_4.setItemText(9, _translate("Form", " 10"))
        self.comboBox_4.setItemText(10, _translate("Form", " 11"))
        self.comboBox_4.setItemText(11, _translate("Form", " 12"))
        self.label_4.setText(_translate("Form", "月份"))
        self.radioButton.setText(_translate("Form", "WATCH ME"))
        self.checkBox.setText(_translate("Form", "KEEP IT?"))

    def display(self):
        self.radioButton.setChecked(True)
        conn = pymysql.connect(host='127.0.0.1',
                               user='******',
                               passwd='714511',
                               db='qinwenrui',
                               port=3306,
                               charset='utf8mb4')

        year = self.comboBox_2.currentText().replace(' ', '')
        month = self.comboBox_4.currentText().replace(' ', '')  #输入

        sql = 'SELECT * FROM `dianying`;'
        df = pd.read_sql(sql, conn)
        if year != '所有年份':
            a = df[(df.年份 == year) & (df.月份 == int(month))]
        else:
            a = df[(df.月份 == int(month))]

        M = []
        TYPE = a[['题材', '票房']]
        c = TYPE[(TYPE.题材 == '犯罪')]
        money = 0
        for k in c.index.tolist():
            money = money + c.loc[k].values[1]
        M.append(money)

        c = TYPE[(TYPE.题材 == '喜剧')]
        money = 0
        for k in c.index.tolist():
            money = money + c.loc[k].values[1]
        M.append(money)

        c = TYPE[(TYPE.题材 == '剧情')]
        money = 0
        for k in c.index.tolist():
            money = money + c.loc[k].values[1]
        M.append(money)

        c = TYPE[(TYPE.题材 == '纪录片')]
        money = 0
        for k in c.index.tolist():
            money = money + c.loc[k].values[1]
        M.append(money)

        c = TYPE[(TYPE.题材 == '奇幻')]
        money = 0
        for k in c.index.tolist():
            money = money + c.loc[k].values[1]
        M.append(money)

        c = TYPE[(TYPE.题材 == '动作')]
        money = 0
        for k in c.index.tolist():
            money = money + c.loc[k].values[1]
        M.append(money)

        c = TYPE[(TYPE.题材 == '冒险')]
        money = 0
        for k in c.index.tolist():
            money = money + c.loc[k].values[1]
        M.append(money)

        c = TYPE[(TYPE.题材 == '悬疑')]
        money = 0
        for k in c.index.tolist():
            money = money + c.loc[k].values[1]
        M.append(money)

        c = TYPE[(TYPE.题材 == '动画')]
        money = 0
        for k in c.index.tolist():
            money = money + c.loc[k].values[1]
        M.append(money)

        c = TYPE[(TYPE.题材 == '战争')]
        money = 0
        for k in c.index.tolist():
            money = money + c.loc[k].values[1]
        M.append(money)

        c = TYPE[(TYPE.题材 == '家庭')]
        money = 0
        for k in c.index.tolist():
            money = money + c.loc[k].values[1]
        M.append(money)

        c = TYPE[(TYPE.题材 == '科幻')]
        money = 0
        for k in c.index.tolist():
            money = money + c.loc[k].values[1]
        M.append(money)

        c = TYPE[(TYPE.题材 == '历史')]
        money = 0
        for k in c.index.tolist():
            money = money + c.loc[k].values[1]
        M.append(money)

        #TYPE.loc[rows]获取信息
        tp = [
            '犯罪', '喜剧', '剧情', '纪录片', '奇幻', '动作', '冒险', '悬疑', '动画', '战争', '家庭',
            '科幻', '历史'
        ]

        pie = Pie('{}年{}月题材票房占比'.format(year, month),
                  title_pos='center',
                  width=907,
                  height=619)  #h=625
        pie._option['animation'] = False
        pie.use_theme('dark')
        pie.add('',
                tp,
                M,
                center=[50, 50],
                radius=[0, 60],
                is_label_show=True,
                legend_orient='vertical',
                legend_pos='left')
        pie.render('./graph/monthtype.html')
        self.widget.load(QUrl.fromLocalFile('/graph/monthtype.html'))
Example #27
0
class BigReport(QMdiSubWindow, form_BigReport.Ui_frmBigReport):

    # create "resized" as a signal that the window can emit
    # we respond to this signal with the form's resizeMe method below
    resized = pyqtSignal()

    def __init__(self):
        super(self.__class__, self).__init__()
        self.setupUi(self)
        self.mdiParent = ""
        self.myHtml = ""
        self.resized.connect(self.resizeMe)
        self.lstDates.currentRowChanged.connect(self.FillSpeciesForDate)
        self.lstLocations.currentRowChanged.connect(
            self.FillSpeciesForLocation)
        self.lstLocations.doubleClicked.connect(
            lambda: self.CreateLocation(self.lstLocations))
        self.tblNewLocationSpecies.itemDoubleClicked.connect(
            lambda: self.CreateLocation(self.tblNewLocationSpecies))
        self.lstDates.doubleClicked.connect(
            lambda: self.CreateSpeciesList(self.lstDates))
        self.lstSpecies.doubleClicked.connect(
            lambda: self.CreateIndividual(self.lstSpecies))
        self.lstLocationSpecies.doubleClicked.connect(
            lambda: self.CreateIndividual(self.lstLocationSpecies))
        self.lstLocationUniqueSpecies.doubleClicked.connect(
            lambda: self.CreateIndividual(self.lstLocationUniqueSpecies))
        self.lstNewLifeSpecies.doubleClicked.connect(
            lambda: self.CreateIndividual(self.lstNewLifeSpecies))
        self.tblNewYearSpecies.doubleClicked.connect(
            lambda: self.CreateIndividual(self.tblNewYearSpecies))
        self.tblNewMonthSpecies.doubleClicked.connect(
            lambda: self.CreateIndividual(self.tblNewMonthSpecies))
        self.tblNewCountrySpecies.doubleClicked.connect(
            lambda: self.CreateIndividual(self.tblNewCountrySpecies))
        self.tblNewStateSpecies.doubleClicked.connect(
            lambda: self.CreateIndividual(self.tblNewStateSpecies))
        self.tblNewCountySpecies.doubleClicked.connect(
            lambda: self.CreateIndividual(self.tblNewCountySpecies))
        self.tblNewLocationSpecies.doubleClicked.connect(
            lambda: self.CreateIndividual(self.tblNewLocationSpecies))
        self.tblSpecies.doubleClicked.connect(self.TblSpeciesClicked)

        # right-click menu actions to widgets as appropriate
        self.tblSpecies.addAction(self.actionSetSpeciesFilter)
        self.tblSpecies.addAction(self.actionSetFirstDateFilter)
        self.tblSpecies.addAction(self.actionSetLastDateFilter)
        self.lstLocations.addAction(self.actionSetLocationFilter)
        self.lstDates.addAction(self.actionSetDateFilter)
        self.lstSpecies.addAction(self.actionSetSpeciesFilter)
        self.lstLocationSpecies.addAction(self.actionSetSpeciesFilter)
        self.lstLocationUniqueSpecies.addAction(self.actionSetSpeciesFilter)
        self.lstNewLifeSpecies.addAction(self.actionSetSpeciesFilter)
        self.tblNewYearSpecies.addAction(self.actionSetSpeciesFilter)
        self.tblNewYearSpecies.addAction(self.actionSetDateFilterToYear)
        self.tblNewMonthSpecies.addAction(self.actionSetSpeciesFilter)
        self.tblNewMonthSpecies.addAction(self.actionSetDateFilterToMonth)
        self.tblNewCountrySpecies.addAction(self.actionSetSpeciesFilter)
        self.tblNewCountrySpecies.addAction(self.actionSetLocationFilter)
        self.tblNewStateSpecies.addAction(self.actionSetSpeciesFilter)
        self.tblNewStateSpecies.addAction(self.actionSetLocationFilter)
        self.tblNewCountySpecies.addAction(self.actionSetSpeciesFilter)
        self.tblNewCountySpecies.addAction(self.actionSetLocationFilter)
        self.tblNewLocationSpecies.addAction(self.actionSetSpeciesFilter)
        self.tblNewLocationSpecies.addAction(self.actionSetLocationFilter)

        # connect right-click actions to methods
        self.actionSetDateFilter.triggered.connect(self.setDateFilter)
        self.actionSetFirstDateFilter.triggered.connect(
            self.setFirstDateFilter)
        self.actionSetLastDateFilter.triggered.connect(self.setLastDateFilter)
        self.actionSetSpeciesFilter.triggered.connect(self.setSpeciesFilter)
        self.actionSetCountryFilter.triggered.connect(self.setLocationFilter)
        self.actionSetStateFilter.triggered.connect(self.setLocationFilter)
        self.actionSetCountyFilter.triggered.connect(self.setLocationFilter)
        self.actionSetLocationFilter.triggered.connect(self.setLocationFilter)
        self.actionSetDateFilterToYear.triggered.connect(self.setDateFilter)
        self.actionSetDateFilterToMonth.triggered.connect(self.setDateFilter)

        self.webMap = QWebEngineView(self.tabMap)
        self.webMap.setUrl(QUrl("about:blank"))
        self.webMap.setObjectName("webMap")

        self.tabAnalysis.setCurrentIndex(0)
        self.speciesList = []
        self.filter = code_Filter.Filter()
        self.filteredSightingList = []

    def CreateLocation(self, callingWidget):
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        if callingWidget.objectName() == "lstLocations":
            locationName = callingWidget.currentItem().text()
        if callingWidget.objectName() == "tblNewLocationSpecies":
            locationName = callingWidget.item(callingWidget.currentRow(),
                                              0).text()
            if callingWidget.currentColumn() != 0:
                QApplication.restoreOverrideCursor()
                return
        sub = code_Location.Location()
        sub.mdiParent = self.mdiParent
        sub.FillLocation(locationName)
        self.parent().parent().addSubWindow(sub)
        self.mdiParent.PositionChildWindow(sub, self)
        sub.show()
        QApplication.restoreOverrideCursor()

    def CreateIndividual(self, callingWidget):
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        if callingWidget.objectName() in ([
                "lstSpecies", "lstLocationSpecies", "lstLocationUniqueSpecies",
                "lstNewLifeSpecies"
        ]):
            species = callingWidget.currentItem().text()
        if callingWidget.objectName() in ([
                "tblNewYearSpecies", "tblNewMonthSpecies",
                "tblNewCountrySpecies", "tblNewStateSpecies",
                "tblNewCountySpecies", "tblNewLocationSpecies"
        ]):
            species = callingWidget.item(callingWidget.currentRow(), 1).text()
            if callingWidget.currentColumn() != 1:
                QApplication.restoreOverrideCursor()
                return
        sub = code_Individual.Individual()
        sub.mdiParent = self.mdiParent
        sub.FillIndividual(species)
        self.parent().parent().addSubWindow(sub)
        self.mdiParent.PositionChildWindow(sub, self)
        sub.show()
        sub.resizeMe()
        QApplication.restoreOverrideCursor()

    def CreateSpeciesList(self, callingWidget):
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        if callingWidget.objectName() == "lstDates":
            date = callingWidget.currentItem().text()

        filter = code_Filter.Filter()
        filter.setStartDate(date)
        filter.setEndDate(date)

        sub = code_Lists.Lists()
        sub.mdiParent = self.mdiParent
        sub.FillSpecies(filter)
        self.parent().parent().addSubWindow(sub)
        self.mdiParent.PositionChildWindow(sub, self)
        sub.show()
        QApplication.restoreOverrideCursor()

    def FillAnalysisReport(self, filter):
        # save filter for later use
        self.filter = filter

        # create subset of master sightings list for this filter
        self.filteredSightingList = deepcopy(
            self.mdiParent.db.GetSightings(filter))
        filteredSightingList = self.filteredSightingList

        # ****Setup Species page****
        # get species and first/last date data from db
        speciesListWithDates = self.mdiParent.db.GetSpeciesWithData(
            filter, self.filteredSightingList, "Subspecies")

        # abort if filter produced no sightings
        if len(speciesListWithDates) == 0:
            return (False)

    # set up tblSpecies column headers and widths
        self.tblSpecies.setColumnCount(4)
        self.tblSpecies.setRowCount(len(speciesListWithDates))
        self.tblSpecies.horizontalHeader().setVisible(True)
        self.tblSpecies.setHorizontalHeaderLabels(
            ['Tax', 'Species', 'First', 'Last'])
        header = self.tblSpecies.horizontalHeader()
        header.setSectionResizeMode(1, QHeaderView.Stretch)
        self.tblSpecies.setShowGrid(False)

        # add species and dates to table row by row
        R = 0
        for species in speciesListWithDates:
            taxItem = QTableWidgetItem()
            taxItem.setData(Qt.DisplayRole, R + 1)
            speciesItem = QTableWidgetItem()
            speciesItem.setText(species[0])
            speciesItem.setData(Qt.UserRole, QVariant(species[4]))
            firstDateItem = QTableWidgetItem()
            firstDateItem.setData(Qt.DisplayRole, species[1])
            lastDateItem = QTableWidgetItem()
            lastDateItem.setData(Qt.DisplayRole, species[2])
            self.tblSpecies.setItem(R, 0, taxItem)
            self.tblSpecies.setItem(R, 1, speciesItem)
            self.tblSpecies.setItem(R, 2, firstDateItem)
            self.tblSpecies.setItem(R, 3, lastDateItem)

            self.speciesList.append(species[4])

            R = R + 1

        # ****Setup Dates page****
        listDates = self.mdiParent.db.GetDates(filter, filteredSightingList)
        self.lstDates.addItems(listDates)
        self.lstDates.setSpacing(2)
        if len(listDates) > 0:
            self.lstDates.setCurrentRow(0)
            self.FillSpeciesForDate()

        # ****Setup Locations page****
        listLocations = self.mdiParent.db.GetLocations(filter, "OnlyLocations",
                                                       filteredSightingList)
        for l in listLocations:
            self.lstLocations.addItem(l)
        self.lstLocations.setSpacing(2)
        if len(listLocations) > 0:
            self.lstLocations.setCurrentRow(0)
            self.FillSpeciesForLocation()
            self.lblLocations.setText("Locations (" + str(len(listLocations)) +
                                      ")")

        # ****Setup New Species for Dates page****
        speciesListFilter = code_Filter.Filter()
        speciesListFilter.setSpeciesList(self.speciesList)
        sightingListForSpeciesSubset = self.mdiParent.db.GetSightings(
            speciesListFilter)

        yearSpecies = self.mdiParent.db.GetNewYearSpecies(
            filter, filteredSightingList, sightingListForSpeciesSubset)
        lifeSpecies = self.mdiParent.db.GetNewLifeSpecies(
            filter, filteredSightingList, sightingListForSpeciesSubset)
        monthSpecies = self.mdiParent.db.GetNewMonthSpecies(
            filter, filteredSightingList, sightingListForSpeciesSubset)

        # set up tblNewYearSpecies column headers and widths
        self.tblNewYearSpecies.setColumnCount(2)
        self.tblNewYearSpecies.setRowCount(len(yearSpecies) + 1)
        self.tblNewYearSpecies.horizontalHeader().setVisible(False)
        header = self.tblNewYearSpecies.horizontalHeader()
        header.setSectionResizeMode(1, QHeaderView.Stretch)
        self.tblNewYearSpecies.setShowGrid(False)

        if len(yearSpecies) > 0:
            R = 1
            for ys in yearSpecies:
                yearItem = QTableWidgetItem()
                yearItem.setText(ys[0])
                newYearSpeciesItem = QTableWidgetItem()
                newYearSpeciesItem.setText(ys[1])
                self.tblNewYearSpecies.setItem(R, 0, yearItem)
                self.tblNewYearSpecies.setItem(R, 1, newYearSpeciesItem)
                R = R + 1
            self.tblNewYearSpecies.removeRow(0)

        self.lblNewYearSpecies.setText("New year species (" +
                                       str(len(yearSpecies)) + ")")

        # set up tblNewMonthSpecies column headers and widths
        self.tblNewMonthSpecies.setColumnCount(2)
        self.tblNewMonthSpecies.setRowCount(len(monthSpecies) + 1)
        self.tblNewMonthSpecies.horizontalHeader().setVisible(False)
        header = self.tblNewMonthSpecies.horizontalHeader()
        header.setSectionResizeMode(1, QHeaderView.Stretch)
        self.tblNewMonthSpecies.setShowGrid(False)

        if len(monthSpecies) > 0:
            R = 1
            for ms in monthSpecies:
                monthItem = QTableWidgetItem()
                monthItem.setText(ms[0])
                newMonthSpeciesItem = QTableWidgetItem()
                newMonthSpeciesItem.setText(ms[1])
                self.tblNewMonthSpecies.setItem(R, 0, monthItem)
                self.tblNewMonthSpecies.setItem(R, 1, newMonthSpeciesItem)
                R = R + 1
            self.tblNewMonthSpecies.removeRow(0)

        self.lblNewMonthSpecies.setText("New month species (" +
                                        str(len(monthSpecies)) + ")")

        # set up lstNewLifeSpecies
        if len(lifeSpecies) > 0:
            self.lstNewLifeSpecies.addItems(lifeSpecies)
            self.lstNewLifeSpecies.setSpacing(2)

        self.lblNewLifeSpecies.setText("New life species (" +
                                       str(len(lifeSpecies)) + ")")

        # ****Setup new Location Species page****
        countrySpecies = self.mdiParent.db.GetNewCountrySpecies(
            filter, filteredSightingList, sightingListForSpeciesSubset,
            self.speciesList)
        stateSpecies = self.mdiParent.db.GetNewStateSpecies(
            filter, filteredSightingList, sightingListForSpeciesSubset,
            self.speciesList)
        countySpecies = self.mdiParent.db.GetNewCountySpecies(
            filter, filteredSightingList, sightingListForSpeciesSubset,
            self.speciesList)
        locationSpecies = self.mdiParent.db.GetNewLocationSpecies(
            filter, filteredSightingList, sightingListForSpeciesSubset,
            self.speciesList)

        # set up tblNewCountrySpecies column headers and widths
        self.tblNewCountrySpecies.setColumnCount(2)
        self.tblNewCountrySpecies.setRowCount(len(countrySpecies))
        self.tblNewCountrySpecies.horizontalHeader().setVisible(False)
        header = self.tblNewCountrySpecies.horizontalHeader()
        header.setSectionResizeMode(1, QHeaderView.Stretch)
        self.tblNewCountrySpecies.setShowGrid(False)

        if len(countrySpecies) > 0:
            R = 0
            for ms in countrySpecies:
                countryItem = QTableWidgetItem()
                countryItem.setText(self.mdiParent.db.GetCountryName(ms[0]))
                newCountrySpeciesItem = QTableWidgetItem()
                newCountrySpeciesItem.setText(ms[1])
                self.tblNewCountrySpecies.setItem(R, 0, countryItem)
                self.tblNewCountrySpecies.setItem(R, 1, newCountrySpeciesItem)
                R = R + 1

        self.lblNewCountrySpecies.setText("New country species (" +
                                          str(len(countrySpecies)) + ")")

        # set up tblNewStateSpecies column headers and widths
        self.tblNewStateSpecies.setColumnCount(2)
        self.tblNewStateSpecies.setRowCount(len(stateSpecies))
        self.tblNewStateSpecies.horizontalHeader().setVisible(False)
        header = self.tblNewStateSpecies.horizontalHeader()
        header.setSectionResizeMode(1, QHeaderView.Stretch)
        self.tblNewStateSpecies.setShowGrid(False)

        if len(stateSpecies) > 0:
            R = 0
            for ms in stateSpecies:
                stateItem = QTableWidgetItem()
                stateItem.setText(self.mdiParent.db.GetStateName(ms[0]))
                newStateSpeciesItem = QTableWidgetItem()
                newStateSpeciesItem.setText(ms[1])
                self.tblNewStateSpecies.setItem(R, 0, stateItem)
                self.tblNewStateSpecies.setItem(R, 1, newStateSpeciesItem)
                R = R + 1
            self.tblNewStateSpecies.sortByColumn(0, Qt.AscendingOrder)

        self.lblNewStateSpecies.setText("New state species (" +
                                        str(len(stateSpecies)) + ")")

        # set up tblNewCountySpecies column headers and widths
        self.tblNewCountySpecies.setColumnCount(2)
        self.tblNewCountySpecies.setRowCount(len(countySpecies))
        self.tblNewCountySpecies.horizontalHeader().setVisible(False)
        header = self.tblNewCountySpecies.horizontalHeader()
        header.setSectionResizeMode(1, QHeaderView.Stretch)
        self.tblNewCountySpecies.setShowGrid(False)

        if len(countySpecies) > 0:
            R = 0
            for ms in countySpecies:
                countyItem = QTableWidgetItem()
                countyItem.setText(ms[0])
                newCountySpeciesItem = QTableWidgetItem()
                newCountySpeciesItem.setText(ms[1])
                self.tblNewCountySpecies.setItem(R, 0, countyItem)
                self.tblNewCountySpecies.setItem(R, 1, newCountySpeciesItem)
                R = R + 1

        self.lblNewCountySpecies.setText("New county species (" +
                                         str(len(countySpecies)) + ")")

        # set up tblNewLocationSpecies column headers and widths
        self.tblNewLocationSpecies.setColumnCount(2)
        self.tblNewLocationSpecies.setRowCount(len(locationSpecies))
        self.tblNewLocationSpecies.horizontalHeader().setVisible(False)
        header = self.tblNewLocationSpecies.horizontalHeader()
        header.setSectionResizeMode(1, QHeaderView.Stretch)
        self.tblNewLocationSpecies.setShowGrid(False)

        if len(locationSpecies) > 0:
            R = 0
            for ms in locationSpecies:
                locationItem = QTableWidgetItem()
                locationItem.setText(ms[0])
                newLocationSpeciesItem = QTableWidgetItem()
                newLocationSpeciesItem.setText(ms[1])
                self.tblNewLocationSpecies.setItem(R, 0, locationItem)
                self.tblNewLocationSpecies.setItem(R, 1,
                                                   newLocationSpeciesItem)
                R = R + 1

        self.lblNewLocationSpecies.setText("New location species (" +
                                           str(len(locationSpecies)) + ")")

        # ****Setup window's main labels****
        # set main species seen lable text
        count = self.mdiParent.db.CountSpecies(self.speciesList)

        self.lblTopSpeciesSeen.setText("Species seen: " + str(count))

        # set main location label, using "All Locations" if none others are selected
        self.mdiParent.SetChildDetailsLabels(self, filter)

        self.setWindowTitle(self.lblLocation.text() + ": " +
                            self.lblDateRange.text())

        if self.lblDetails.text() != "":
            self.lblDetails.setVisible(True)
        else:
            self.lblDetails.setVisible(False)

        self.resizeMe()
        self.scaleMe()

        return (True)

    def FillSpeciesForDate(self):
        # create temporary filter for query with nothing but needed date
        self.lstSpecies.clear()
        date = self.lstDates.currentItem().text()

        tempFilter = code_Filter.Filter()

        tempFilter.setStartDate(date)
        tempFilter.setEndDate(date)

        speciesList = self.mdiParent.db.GetSpecies(tempFilter,
                                                   self.filteredSightingList)

        self.lstSpecies.addItems(speciesList)
        self.lstSpecies.setSpacing(2)

        self.lblSpeciesSeen.setText("Species seen on selected date (" +
                                    str(len(speciesList)) + "):")

    def FillMap(self):

        coordinatesDict = defaultdict()
        mapWidth = self.width() - 20
        mapHeight = self.height() - self.lblLocation.height() - (
            self.lblDateRange.height() * 7.5)
        self.webMap.setGeometry(5, 5, mapWidth, mapHeight)

        for l in range(self.lstLocations.count()):
            locationName = self.lstLocations.item(l).text()
            coordinates = self.mdiParent.db.GetLocationCoordinates(
                locationName)
            coordinatesDict[locationName] = coordinates

        thisMap = code_MapHtml.MapHtml()
        thisMap.mapHeight = mapHeight - 20
        thisMap.mapWidth = mapWidth - 20
        thisMap.coordinatesDict = coordinatesDict

        # save mapHtml in object's variable so we can reload it later
        self.mapHtml = thisMap.html()

        # pass the mapHtml we created to the QWebView widget for display
        self.webMap.setHtml(self.mapHtml)

    def FillSpeciesForLocation(self):
        # create temporary filter for query with nothing but needed location
        location = self.lstLocations.currentItem().text()

        tempFilter = code_Filter.Filter()
        tempFilter.setLocationType("Location")
        tempFilter.setLocationName(location)

        speciesList = self.mdiParent.db.GetSpecies(tempFilter,
                                                   self.filteredSightingList)

        self.lstLocationSpecies.clear()
        self.lstLocationSpecies.addItems(speciesList)
        self.lstLocationSpecies.setSpacing(2)

        uniqueSpecies = self.mdiParent.db.GetUniqueSpeciesForLocation(
            self.filter, location, speciesList, self.filteredSightingList)

        self.lstLocationUniqueSpecies.clear()
        self.lstLocationUniqueSpecies.addItems(uniqueSpecies)
        self.lstLocationUniqueSpecies.setSpacing(2)

        self.lblLocationSpecies.setText("Species at selected location (" +
                                        str(len(speciesList)) + ")")
        self.lblLocationUniqueSpecies.setText(
            "Species seen ONLY at selected location (" +
            str(len(uniqueSpecies)) + ")")

    def TblSpeciesClicked(self):
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        currentColumn = self.tblSpecies.currentColumn()
        currentRow = self.tblSpecies.currentRow()

        tempFilter = deepcopy(self.filter)

        if currentColumn == 0:
            # the taxonomy order column was clicked, so abort. We won't create a report.
            # turn off the hourglass cursor before exiting
            QApplication.restoreOverrideCursor()
            return

        if currentColumn == 1:
            # species column has been clicked so create individual window for that species
            species = self.tblSpecies.item(currentRow, 1).data(Qt.UserRole)
            sub = code_Individual.Individual()
            sub.mdiParent = self.mdiParent
            sub.FillIndividual(species)
            self.parent().parent().addSubWindow(sub)
            self.mdiParent.PositionChildWindow(sub, self)
            sub.show()
            sub.resizeMe()

        if currentColumn > 1:
            # date column has been clicked so create species list frame for that dateArray
            # use same start and end date for new filter to show just the single day
            date = self.tblSpecies.item(currentRow, currentColumn).text()
            tempFilter.setStartDate(date)
            tempFilter.setEndDate(date)

            sub = code_Lists.Lists()
            sub.mdiParent = self.mdiParent
            sub.FillSpecies(tempFilter)
            self.parent().parent().addSubWindow(sub)
            self.mdiParent.PositionChildWindow(sub, self)
            sub.show()
            sub.resizeMe()

        QApplication.restoreOverrideCursor()

    def html(self):

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        # create start to basic html format
        html = """
            <!DOCTYPE html>
            <html>
            <head>
            </head>
            <style>
            * {
                font-size: 75%;
                font-family: "Times New Roman", Times, serif;
                }
            th {
                text-align: left;
            }
            </style>
            <body>
            """

        # add title information
        html = html + ("<H1>" + self.lblLocation.text() + "</H1>")

        html = html + ("<H3>" + self.lblDateRange.text() + "</H3>")

        html = html + ("<H3>" + self.lblDetails.text() + "</H3>")

        html = html + ("<H3>" + self.lblLocationsVisited.text() + "</H3>")

        html = html + ("<H3>" + self.lblTopSpeciesSeen.text() + "</H3>")

        # grab the map image from the map tap
        # process it into a byte array and encode it
        # so we can insert it inline into the html
        myPixmap = self.webMap.grab()
        myPixmap = myPixmap.scaledToWidth(600, Qt.SmoothTransformation)

        myByteArray = QByteArray()
        myBuffer = QBuffer(myByteArray)
        myBuffer.open(QIODevice.WriteOnly)
        myPixmap.save(myBuffer, "PNG")

        encodedImage = base64.b64encode(myByteArray)

        html = html + ("""
        <img src="data:image/png;base64, 
        """)

        html = html + str(encodedImage)[1:]

        html = html + ("""        
        "  />
        """)

        html = html + ("<H4>" + "Species" + "</H4>")

        html = html + ("<font size='2'>" + "<table width='100%'>" + " <tr>")

        html = html + ("<th>" + "Species" + "</th>" + "<th>" + "First" +
                       "</th> " + "<th></th> " + "<th>" + "Latest" + "</th>" +
                       "</tr>")

        for r in range(self.tblSpecies.rowCount()):
            html = html + (
                "<tr>" + "<td>" + self.tblSpecies.item(r, 1).text() + "</td>" +
                "<td>" + self.tblSpecies.item(r, 2).text() + "</td>" + "<td>" +
                "  " + "</td>" + "<td>" + self.tblSpecies.item(r, 3).text() +
                "</td>" + "</tr>")
        html = html + "</table>"

        html = html + ("<H4>" + "Dates" + "</H4>")

        html = html + ("<font size='2'>" + "<p>")

        # loopthrough the dates listed in lstDates
        # create a filter unique to each date
        # and get species for that date
        for r in range(self.lstDates.count()):
            html = html + ("<b>" + self.lstDates.item(r).text() + "</b>")

            # create filter set to our current location
            filter = deepcopy(self.filter)
            filter.setStartDate(self.lstDates.item(r).text())
            filter.setEndDate(self.lstDates.item(r).text())

            species = self.mdiParent.db.GetSpecies(filter)

            html = html + ("<br>" + "<table width='100%'>" + "<tr>")

            # set up counter R to start a new row after listing each 3 species
            R = 1
            for s in species:
                html = html + ("<td>" + s + "</td>")
                if R == 3:
                    html = html + ("</tr>" + "<tr>")
                    R = 0
                R = R + 1

            html = html + ("<br>" + "<br>" + "</table>")

        html = html + (
            "<H4>" + "Locations" + "</H4>" + "<p>" +
            "Asterisks indicate species seen only at listed location.")

        # loopthrough the locations listed in lstLocations
        # create a filter unique to each location
        # and get species for that date
        for r in range(self.lstLocations.count()):
            html = html + ("<b>" + self.lstLocations.item(r).text() + "</b>")

            # create filter set to our current location
            filter = deepcopy(self.filter)
            filter.setLocationType("Location")
            filter.setLocationName(self.lstLocations.item(r).text())

            species = self.mdiParent.db.GetSpecies(filter)

            uniqueSpecies = self.mdiParent.db.GetUniqueSpeciesForLocation(
                self.filter,
                self.lstLocations.item(r).text(), species,
                self.filteredSightingList)

            html = html + ("<br>" + "<table width='100%'>" + "<tr>")

            # set up counter R to start a new row after listing each 3 species
            R = 1
            for s in species:

                if s in uniqueSpecies:
                    s = s + "*"

                html = html + ("<td>" + s + "</td>")
                if R == 3:
                    html = html + ("</tr>" + "<tr>")
                    R = 0
                R = R + 1

            html = html + ("<br>" + "<br>" + "</table>")

        html = html + ("<p>" + "<H4>" + "New Life Species" + "</H4>" + "<p>" +
                       "<table width='100%'>"
                       "<tr>")

        # set up counter R to start a new row after listing each 3 species
        R = 1

        if self.lstNewLifeSpecies.count() == 0:
            html = html + ("<td>" + "None" + "</td>")

        else:

            # loopthrough the species listed in lstNewLifeSpecies
            for r in range(self.lstNewLifeSpecies.count()):

                html = html + ("<td>" + self.lstNewLifeSpecies.item(r).text() +
                               "</td>")

                if R == 3:
                    html = html + ("</tr>" + "<tr>")
                    R = 0

                R = R + 1

            html = html + ("<br>" + "<br>" + "</table>")

        # set up New Year Species
        html = html + ("<p>" + "<H4>" + "New Year Species" + "</H4>" + "<p>" +
                       "<table width='100%'>" + "<tr>")

        # set up counter R to start a new row after listing each 3 species
        R = 1

        if self.tblNewYearSpecies.rowCount() == 0:
            html = html + ("<td>" + "None" + "</td>")

        else:
            # loopthrough the species listed in lstNewLifeSpecies
            for r in range(self.tblNewYearSpecies.rowCount()):

                html = html + (
                    "<td>" + self.tblNewYearSpecies.item(r, 1).text() + " (" +
                    self.tblNewYearSpecies.item(r, 0).text() + ")" + "</td>")

                if R == 3:
                    html = html + ("</tr>" "<tr>")
                    R = 0

                R = R + 1

            html = html + ("</tr>" + "</table>")

        # set up New Month Species
        html = html + ("<p>" + "<H4>" + "New Month Species" + "</H4>" + "<p>" +
                       "<table width='100%'>" + "<tr>")

        # set up counter R to start a new row after listing each 3 species
        R = 1

        if self.tblNewMonthSpecies.rowCount() == 0:
            html = html + ("<td>" + "None" + "</td>")

        else:

            # loopthrough the species listed in lstNewLifeSpecies
            for r in range(self.tblNewMonthSpecies.rowCount()):

                html = html + (
                    "<td>" + self.tblNewMonthSpecies.item(r, 1).text() + " (" +
                    self.tblNewMonthSpecies.item(r, 0).text() + ")" + "</td>")

                if R == 3:
                    html = html + ("</tr>" "<tr>")
                    R = 0

                R = R + 1

            html = html + ("</tr>" + "</table>")

        # set up New Country Species
        html = html + ("<p>" + "<H4>" + "New Country Species" + "</H4>" +
                       "<p>" + "<table width='100%'>" + "<tr>")

        # set up counter R to start a new row after listing each 3 species
        R = 1

        if self.tblNewCountrySpecies.rowCount() == 0:
            html = html + ("<td>" + "None" + "</td>")

        else:

            # loopthrough the species listed in lstNewLifeSpecies
            for r in range(self.tblNewCountrySpecies.rowCount()):

                html = html + ("<td>" + self.tblNewCountrySpecies.item(
                    r, 1).text() + " (" + self.tblNewCountrySpecies.item(
                        r, 0).text() + ")" + "</td>")

                if R == 2:
                    html = html + ("</tr>" "<tr>")
                    R = 0

                R = R + 1

            html = html + ("</tr>" + "</table>")

        html = html + ("<font size>" + "</body>" + "</html>")

        # set up New State Species
        html = html + ("<p>" + "<H4>" + "New State Species" + "</H4>" + "<p>" +
                       "<table width='100%'>" + "<tr>")

        # set up counter R to start a new row after listing each 3 species
        R = 1

        if self.tblNewStateSpecies.rowCount() == 0:
            html = html + ("<td>" + "None" + "</td>")

        else:

            # loopthrough the species listed in lstNewLifeSpecies
            for r in range(self.tblNewStateSpecies.rowCount()):

                html = html + (
                    "<td>" + self.tblNewStateSpecies.item(r, 1).text() + " (" +
                    self.tblNewStateSpecies.item(r, 0).text() + ")" + "</td>")

                if R == 2:
                    html = html + ("</tr>" "<tr>")
                    R = 0

                R = R + 1

            html = html + ("</tr>" + "</table>")

        # set up New County Species
        html = html + ("<p>" + "<H4>" + "New County Species" + "</H4>" +
                       "<p>" + "<table width='100%'>" + "<tr>")

        # set up counter R to start a new row after listing each 3 species
        R = 1

        if self.tblNewCountySpecies.rowCount() == 0:
            html = html + ("<td>" + "None" + "</td>")

        else:

            # loopthrough the species listed in lstNewLifeSpecies
            for r in range(self.tblNewCountySpecies.rowCount()):

                html = html + ("<td>" + self.tblNewCountySpecies.item(
                    r, 1).text() + " (" + self.tblNewCountySpecies.item(
                        r, 0).text() + ")" + "</td>")

                if R == 2:
                    html = html + ("</tr>" "<tr>")
                    R = 0

                R = R + 1

            html = html + ("</tr>" + "</table>")

        # set up New Location Species
        html = html + ("<p>" + "<H4>" + "New Location Species" + "</H4>" +
                       "<p>" + "<table width='100%'>" + "<tr>")

        # set up counter R to start a new row after listing each 3 species
        R = 1

        if self.tblNewLocationSpecies.rowCount() == 0:
            html = html + ("<td>" + "None" + "</td>")

        else:

            # loopthrough the species listed in lstNewLifeSpecies
            for r in range(self.tblNewLocationSpecies.rowCount()):

                html = html + ("<td>" + self.tblNewLocationSpecies.item(
                    r, 1).text() + " (" + self.tblNewLocationSpecies.item(
                        r, 0).text() + ")" + "</td>")

                if R == 2:
                    html = html + ("</tr>" "<tr>")
                    R = 0

                R = R + 1

            html = html + ("</tr>" + "</table>")

        html = html + ("<font size>" + "</body>" + "</html>")

        QApplication.restoreOverrideCursor()

        return (html)

    def setDateFilter(self):
        # get location name and type from focus widget. Varies for widgets.
        if self.focusWidget().objectName() == "lstDates":
            date = self.focusWidget().currentItem().text()
            self.mdiParent.setDateFilter(date)

        if self.focusWidget().objectName() == "tblNewYearSpecies":
            date = self.focusWidget().item(self.focusWidget().currentRow(),
                                           0).text()
            startDate = date + "-01-01"
            endDate = date + "-12-31"
            self.mdiParent.setDateFilter(startDate, endDate)

        if self.focusWidget().objectName() == "tblNewMonthSpecies":
            month = self.focusWidget().item(self.focusWidget().currentRow(),
                                            0).text()
            self.mdiParent.setSeasonalRangeFilter(month)

    def setFirstDateFilter(self):
        # get location name and type from focus widget. Varies for tables.
        if self.focusWidget().objectName() == "tblSpecies":
            date = self.focusWidget().item(self.focusWidget().currentRow(),
                                           2).text()
            self.mdiParent.setDateFilter(date)

    def setLastDateFilter(self):
        # get location name and type from focus widget. Varies for tables.
        if self.focusWidget().objectName() == "tblSpecies":
            date = self.focusWidget().item(self.focusWidget().currentRow(),
                                           3).text()
            self.mdiParent.setDateFilter(date)

    def setLocationFilter(self):

        # get location name and type from focus widget. Varies for tables.
        if self.focusWidget().objectName() == "tblNewCountrySpecies":
            country = self.focusWidget().item(self.focusWidget().currentRow(),
                                              0).text()
            self.mdiParent.setCountryFilter(country)

        if self.focusWidget().objectName() == "tblNewStateSpecies":
            state = self.focusWidget().item(self.focusWidget().currentRow(),
                                            0).text()
            self.mdiParent.setStateFilter(state)

        if self.focusWidget().objectName() == "tblNewCountySpecies":
            county = self.focusWidget().item(self.focusWidget().currentRow(),
                                             0).text()
            self.mdiParent.setCountyFilter(county)

        if self.focusWidget().objectName() == "tblNewLocationSpecies":
            location = self.focusWidget().item(self.focusWidget().currentRow(),
                                               0).text()
            self.mdiParent.setLocationFilter(location)

        if self.focusWidget().objectName() == "lstLocations":
            location = self.focusWidget().currentItem().text()
            self.mdiParent.setLocationFilter(location)

    def setSpeciesFilter(self):

        # get species name from focus widget. Getting the species name is different for tables than for lists.
        if self.focusWidget().objectName() in ([
                "tblSpecies", "tblNewYearSpecies", "tblNewMonthSpecies",
                "tblNewCountrySpecies", "tblNewStateSpecies",
                "tblNewCountySpecies", "tblNewLocationSpecies"
        ]):
            species = self.focusWidget().item(self.focusWidget().currentRow(),
                                              1).text()

        if self.focusWidget().objectName() in ([
                "lstSpecies", "lstLocationSpecies", "lstLocationUniqueSpecies",
                "lstNewLifeSpecies"
        ]):
            species = self.focusWidget().currentItem().text()

        self.mdiParent.setSpeciesFilter(species)

    def resizeEvent(self, event):
        #routine to handle events on objects, like clicks, lost focus, gained forcus, etc.
        self.resized.emit()
        return super(self.__class__, self).resizeEvent(event)

    def resizeMe(self):

        windowWidth = self.frameGeometry().width()
        windowHeight = self.frameGeometry().height()
        self.scrollArea.setGeometry(5, 27, windowWidth - 10, windowHeight - 35)
        self.FillMap()

    def scaleMe(self):

        scaleFactor = self.mdiParent.scaleFactor
        windowWidth = 1100 * scaleFactor
        windowHeight = 625 * scaleFactor
        self.resize(windowWidth, windowHeight)

        fontSize = self.mdiParent.fontSize
        scaleFactor = self.mdiParent.scaleFactor
        #scale the font for all widgets in window
        for w in self.scrollArea.children():
            try:
                w.setFont(QFont("Helvetica", fontSize))
            except:
                pass

        self.lblLocation.setFont(QFont("Helvetica", floor(fontSize * 1.4)))
        self.lblLocation.setStyleSheet("QLabel { font: bold }")
        self.lblDateRange.setFont(QFont("Helvetica", floor(fontSize * 1.2)))
        self.lblDateRange.setStyleSheet("QLabel { font: bold }")
        self.lblDetails.setFont(QFont("Helvetica", floor(fontSize * 1.2)))
        self.lblDetails.setStyleSheet("QLabel { font: bold }")

        metrics = self.tblSpecies.fontMetrics()
        textHeight = metrics.boundingRect("A").height()
        textWidth = metrics.boundingRect("Dummy Country").width()

        for t in ([
                self.tblNewYearSpecies, self.tblNewMonthSpecies,
                self.tblNewCountrySpecies, self.tblNewStateSpecies,
                self.tblNewCountySpecies
        ]):
            header = t.horizontalHeader()
            header.resizeSection(0, floor(1.2 * textWidth))
            for r in range(t.rowCount()):
                t.setRowHeight(r, textHeight * 1.1)

        # format tblSpecies, which is laid out differently from the other tables
        dateWidth = metrics.boundingRect("2222-22-22").width()
        header = self.tblSpecies.horizontalHeader()
        header.resizeSection(2, floor(1.5 * dateWidth))
        header.resizeSection(3, floor(1.5 * dateWidth))
        for r in range(self.tblSpecies.rowCount()):
            self.tblSpecies.setRowHeight(r, textHeight * 1.1)

        # format tblNewLocationSpecies, which needs wider location column
        header = self.tblNewLocationSpecies.horizontalHeader()
        header.resizeSection(0, floor(4 * textWidth))
        for r in range(self.tblNewLocationSpecies.rowCount()):
            t.setRowHeight(r, textHeight * 1.1)
Example #28
0
class Web(QMdiSubWindow, form_Web.Ui_frmWeb):

    resized = pyqtSignal()

    def __init__(self):
        super(self.__class__, self).__init__()
        self.setupUi(self)
        self.setAttribute(Qt.WA_DeleteOnClose, True)
        self.mdiParent = ""
        self.setWindowIcon(QIcon(QPixmap(1, 1)))
        self.contentType = "Web Page"
        self.resized.connect(self.resizeMe)
        self.webView = QWebEngineView(self)
        self.webView.setObjectName("webView")
        self.webView.loadFinished.connect(self.LoadFinished)
        self.webView.loadProgress.connect(self.showLoadProgress)
        self.title = ""

    def resizeEvent(self, event):
        #routine to handle events on objects, like clicks, lost focus, gained forcus, etc.
        self.resized.emit()
        return super(self.__class__, self).resizeEvent(event)

    def resizeMe(self):

        windowWidth = self.frameGeometry().width()
        windowHeight = self.frameGeometry().height()
        self.scrollArea.setGeometry(5, 27, windowWidth - 10, windowHeight - 35)
        self.webView.setGeometry(5, 27, windowWidth - 10, windowHeight - 35)
        if self.contentType == "Map":
            self.webView.adjustSize()
            self.LoadLocationsMap(self.filter)

    def html(self):

        #         QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        html = """
            <!DOCTYPE html>
            <html>
            <head>
            </head>
            <body>
            """

        myPixmap = self.webView.grab()
        myPixmap = myPixmap.scaledToWidth(600, Qt.SmoothTransformation)

        myByteArray = QByteArray()
        myBuffer = QBuffer(myByteArray)
        myBuffer.open(QIODevice.WriteOnly)
        myPixmap.save(myBuffer, "PNG")

        encodedImage = base64.b64encode(myByteArray)

        html = html + ("""
        <img src="data:image/png;base64, 
        """)

        html = html + str(encodedImage)[1:]

        html = html + ("""
            <font size>
            </body>
            </html>
            """)

        #         QApplication.restoreOverrideCursor()

        return (html)

    def scaleMe(self):

        fontSize = self.mdiParent.fontSize
        settings = QWebEngineSettings.globalSettings()
        settings.setFontSize(QWebEngineSettings.DefaultFontSize,
                             floor(fontSize * 1.6))

        scaleFactor = self.mdiParent.scaleFactor
        windowWidth = 800 * scaleFactor
        windowHeight = 580 * scaleFactor
        self.resize(windowWidth, windowHeight)

    def loadAboutYearbird(self):

        self.title = "About Yearbird"

        self.contentType = "About"

        html = """

            <!DOCTYPE html>
            <html>
            <head>
            <title>About Yearbird</title>
            <meta charset="utf-8">
            <style>
            * {
                font-family: "Times New Roman", Times, serif;
                }
            </style>
            </head>
            <body>
            <h1>
            Yearbird
            </h1>
            """

        html = html + "<h3>Version: " + self.mdiParent.versionNumber + "</h3>"
        html = html + "<h3>Date: " + self.mdiParent.versionDate + "</h3>"

        html = html + """
            <font size='4'>            
            <b>
            Yearbird is a free, open-source application to analyze personal eBird sightings. 
            <br><br>
            Created by Richard Trinkner.             
            </b>
            <h3>
            Licenses
            </h3>
            <p>
            <ul>
            <li>
            Yearbird is licensed under the GNU General Public License, version 3.
            </li>
            <li>
            PyQt, by Riverbank Computing, is licensed under the GNU General Public License.
            </li>
            <li>
            Map base layers are retrieved from Google.
            </li>            
            <li>
            Map layers that include points and location labels are generated using OpenLayers. OpenLayers is free, Open Source JavaScript, released under the 2-clause BSD License (also known as the FreeBSD).
            </li>
            <li>
            PyInstaller, by the PyInstaller Development Team, Giovanni Bajo and McMillan Enterprise, is licensed under the GPL General Public License.
            </li>
            </ul>
            </font size>
            </body>
            </html>        
            """

        self.webView.setHtml(html)

        self.setWindowTitle("About Yearbird")

        return (True)

    def LoadWebPage(self, url):
        #         QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        self.webView.load(QUrl(url))
        self.resizeMe()
        self.scaleMe()

    def LoadFinished(self):
        #         QApplication.restoreOverrideCursor()
        return ()

    def LoadLocationsMap(self, filter):

        self.title = "Location Map"

        coordinatesDict = defaultdict()
        mapWidth = self.frameGeometry().width() - 10
        mapHeight = self.frameGeometry().height() - 35
        self.scrollArea.setGeometry(5, 27, mapWidth + 2, mapHeight + 2)
        self.webView.setGeometry(5, 27, mapWidth + 2, mapHeight + 2)
        self.contentType = "Map"
        self.filter = filter

        locations = self.mdiParent.db.GetLocations(filter)

        if len(locations) == 0:
            return (False)

        for l in locations:
            coordinates = self.mdiParent.db.GetLocationCoordinates(l)
            coordinatesDict[l] = coordinates

        thisMap = code_MapHtml.MapHtml()
        thisMap.mapHeight = mapHeight
        thisMap.mapWidth = mapWidth
        thisMap.coordinatesDict = coordinatesDict

        html = thisMap.html()

        self.webView.setHtml(html)

        # set window title to descriptive map name

        locationName = filter.getLocationName(
        )  # str   name of region or location  or ""
        locationType = filter.getLocationType()
        startDate = filter.getStartDate()  # str   format yyyy-mm-dd  or ""
        endDate = filter.getEndDate()  # str   format yyyy-mm-dd  or ""
        startSeasonalMonth = filter.getStartSeasonalMonth()  # str   format mm
        startSeasonalDay = filter.getStartSeasonalDay()  # str   format dd
        endSeasonalMonth = filter.getEndSeasonalMonth()  # str   format  dd
        endSeasonalDay = filter.getEndSeasonalDay()  # str   format dd
        speciesName = filter.getSpeciesName()  # str   speciesName
        family = filter.getFamily()  # str family name

        # set main location label, using "All Locations" if none others are selected

        windowTitle = speciesName

        if locationName != "":
            if locationType == "Country":
                locationName = self.mdiParent.db.GetCountryName(locationName)
            if locationType == "State":
                locationName = self.mdiParent.db.GetStateName(locationName)
            windowTitle = windowTitle + "; " + locationName

        if startDate != "":
            dateTitle = startDate + " to " + endDate
            if startDate == endDate:
                dateTitle = startDate
            windowTitle = windowTitle + "; " + dateTitle

        # set main seasonal range label, if specified
        if not ((startSeasonalMonth == "") or (endSeasonalMonth == "")):
            monthRange = [
                "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
                "Oct", "Nov", "Dec"
            ]
            rangeTitle = monthRange[
                int(startSeasonalMonth) -
                1] + "-" + startSeasonalDay + " to " + monthRange[
                    int(endSeasonalMonth) - 1] + "-" + endSeasonalDay
            windowTitle = windowTitle + "; " + rangeTitle

        if family != "":
            family = family[0:family.index("(") - 1]
            windowTitle = windowTitle + "; " + family

        if windowTitle == "":
            windowTitle = "All species, locations, dates and families"

        #remove leading "; " if needed
        if windowTitle[0:2] == "; ":
            windowTitle = windowTitle[2:]

        # add location count to window title
        windowTitle = "Map: " + windowTitle + " (" + str(
            len(coordinatesDict.keys())) + ")"

        self.setWindowTitle(windowTitle)
        self.title = windowTitle

        icon = QIcon()
        icon.addPixmap(QPixmap(":/icon_map.png"), QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)

        return (True)

    def loadChoroplethUSStates(self, filter):

        from copy import deepcopy
        import folium
        from branca.colormap import LinearColormap

        self.title = "US States Choropleth"

        self.filter = deepcopy(filter)

        # find states in filtered sightings
        stateDict = defaultdict()

        minimalSightingList = self.mdiParent.db.GetMinimalFilteredSightingsList(
            filter)

        for s in minimalSightingList:

            # Consider only full species, not slash or spuh or hybrid entries
            commonName = s["commonName"]
            if "/" not in commonName and "sp." not in commonName and " x " not in commonName:

                if self.mdiParent.db.TestSighting(s, filter):

                    if s["state"][3:5] not in stateDict.keys():
                        stateDict[s["state"][3:5]] = [s]
                    else:
                        stateDict[s["state"][3:5]].append(s)

        # check if no sightings were found. Return false if none found. Abort and display message.
        if len(stateDict) == 0:
            return (False)

        stateTotals = defaultdict()
        largestTotal = 0
        for state in stateDict.keys():
            stateSpecies = set()
            for s in stateDict[state]:
                stateSpecies.add(s["commonName"])
            stateTotals[state] = len(stateSpecies)
            if len(stateSpecies) > largestTotal:
                largestTotal = len(stateSpecies)

        # Load the shape of the zone (US counties)
        geo_file = self.mdiParent.db.state_geo

        #add the state values to the geojson so we can access them for tooltips
        for f in geo_file["features"]:
            if f["id"] in stateTotals.keys():
                f["properties"]["speciesTotal"] = stateTotals[f["id"]]
            else:
                f["properties"]["speciesTotal"] = 0
                stateTotals[f["id"]] = 0

        #create color range for map, using the maximum state value found above
        colormap = LinearColormap(
            colors=[(255, 240, 227), (255, 119, 0)],
            index=[0, round(largestTotal * .75)],
            vmin=0,
            vmax=largestTotal,
        )

        # Initialize the folium map
        state_map = folium.Map(location=[39.5, -98.3], zoom_start=4)

        # Configure the chloropleth layer and add to map
        folium.GeoJson(geo_file,
                       style_function=lambda feature: {
                           'fillColor':
                           'rgb(240, 240, 240)' if stateTotals[feature['id']]
                           == 0 else colormap(stateTotals[feature['id']]),
                           'color':
                           'black',
                           'weight':
                           .2,
                           'fillOpacity':
                           .8,
                       },
                       tooltip=folium.features.GeoJsonTooltip(
                           fields=['name', 'speciesTotal'],
                           aliases=["State", "Species"])).add_to(state_map)

        # make the layer control box visible
        folium.LayerControl().add_to(state_map)

        # get the html string from the map
        html = state_map.get_root().render()

        self.webView.setHtml(html)

        return (True)

    def loadChoroplethUSCounties(self, filter):

        from copy import deepcopy
        import folium
        from branca.colormap import LinearColormap

        self.title = "US Counties Choropleth"

        self.filter = deepcopy(filter)

        # find states in filtered sightings
        countyDict = defaultdict()

        minimalSightingList = self.mdiParent.db.GetMinimalFilteredSightingsList(
            filter)

        for s in minimalSightingList:

            # only count US sightings since we're only showing the US choropleth
            if s["country"] == "US" and s["state"] not in ["US-HI", "US-AK"]:

                #only use sightings that have a county code assigned to them
                # some US sightings won't have them, such as if a checklist is for
                # an entire state, not localized down to a location or county
                if "countyCode" in s.keys():

                    # Consider only full species, not slash or spuh or hybrid entries
                    commonName = s["commonName"]
                    if "/" not in commonName and "sp." not in commonName and " x " not in commonName:

                        if self.mdiParent.db.TestSighting(s, filter):

                            if s["countyCode"] not in countyDict.keys():
                                countyDict[s["countyCode"]] = [s]
                            else:
                                countyDict[s["countyCode"]].append(s)

        # check if no sightings were found. Return false if none found. Abort and display message.
        if len(countyDict) == 0:
            return (False)

        countyTotals = defaultdict()
        largestTotal = 0
        for county in countyDict.keys():
            countySpecies = set()
            for s in countyDict[county]:
                countySpecies.add(s["commonName"])
            countyTotals[county] = len(countySpecies)
            if len(countySpecies) > largestTotal:
                largestTotal = len(countySpecies)

        # Load the shape of the zone (US counties)
        geo_file = self.mdiParent.db.county_geo

        #add the county values to the geojson so we can access them for tooltips
        for f in geo_file["features"]:
            if f["id"] in countyTotals.keys():
                f["properties"]["speciesTotal"] = countyTotals[f["id"]]
            else:
                f["properties"]["speciesTotal"] = 0
                countyTotals[f["id"]] = 0

        #create color range for map, using the maximum state value found above
        colormap = LinearColormap(
            colors=[(255, 240, 227), (255, 119, 0)],
            index=[0, round(largestTotal * .75)],
            vmin=0,
            vmax=largestTotal,
        )

        # Initialize the folium map
        county_map = folium.Map(location=[39.5, -98.3], zoom_start=4)

        # Configure the chloropleth layer and add to map
        folium.GeoJson(geo_file,
                       style_function=lambda feature: {
                           'fillColor':
                           'rgb(240, 240, 240)' if countyTotals[feature['id']]
                           == 0 else colormap(countyTotals[feature['id']]),
                           'color':
                           'black',
                           'weight':
                           1,
                           'fillOpacity':
                           .8,
                           'nan_fill_color':
                           'white'
                       },
                       tooltip=folium.features.GeoJsonTooltip(
                           fields=['name', 'state', 'speciesTotal'],
                           aliases=["County", "State",
                                    "Species"])).add_to(county_map)

        # make the layer control box visible
        folium.LayerControl().add_to(county_map)

        # get the html string from the map
        html = county_map.get_root().render()

        self.webView.setHtml(html)

        return (True)

    def loadChoroplethWorldCountries(self, filter):

        from copy import deepcopy
        import folium
        from branca.colormap import LinearColormap

        self.title = "World Choropleth"

        self.filter = deepcopy(filter)

        # find states in filtered sightings
        countryDict = defaultdict()

        minimalSightingList = self.mdiParent.db.GetMinimalFilteredSightingsList(
            filter)

        for s in minimalSightingList:

            # Consider only full species, not slash or spuh or hybrid entries
            commonName = s["commonName"]
            if "/" not in commonName and "sp." not in commonName and " x " not in commonName:

                if self.mdiParent.db.TestSighting(s, filter):

                    if s["country"] not in countryDict.keys():
                        countryDict[s["country"]] = [s]
                    else:
                        countryDict[s["country"]].append(s)

        # check if no sightings were found. Return false if none found. Abort and display message.
        if len(countryDict) == 0:
            return (False)

        countryTotals = defaultdict()
        largestTotal = 0
        for country in countryDict.keys():
            countrySpecies = set()
            for s in countryDict[country]:
                countrySpecies.add(s["commonName"])
            countryTotals[country] = len(countrySpecies)
            if len(countrySpecies) > largestTotal:
                largestTotal = len(countrySpecies)

        # Load the shape of the zone (US counties)
        geo_file = self.mdiParent.db.country_geo

        #add the country values to the geojson so we can access them for tooltips
        for f in geo_file["features"]:
            if f["id"] in countryTotals.keys():
                f["properties"]["speciesTotal"] = countryTotals[f["id"]]
            else:
                f["properties"]["speciesTotal"] = 0
                countryTotals[f["id"]] = 0

        #create color range for map, using the maximum country value found above
        colormap = LinearColormap(
            colors=[(255, 240, 227), (255, 119, 0)],
            index=[0, round(largestTotal * .75)],
            vmin=0,
            vmax=largestTotal,
        )

        # Initialize the folium map
        choro_map = folium.Map(location=[1, 1], zoom_start=1)

        # Configure the chloropleth layer and add to map
        folium.GeoJson(geo_file,
                       style_function=lambda feature: {
                           'fillColor':
                           'rgb(240, 240, 240)' if countryTotals[feature['id']]
                           == 0 else colormap(countryTotals[feature['id']]),
                           'color':
                           'black',
                           'weight':
                           1,
                           'fillOpacity':
                           .8,
                           'nan_fill_color':
                           'white'
                       },
                       tooltip=folium.features.GeoJsonTooltip(
                           fields=['name', 'speciesTotal'],
                           aliases=["Country", "Species"])).add_to(choro_map)

        # make the layer control box visible
        folium.LayerControl().add_to(choro_map)

        # get the html string from the map
        html = choro_map.get_root().render()

        self.webView.setHtml(html)

        return (True)

    def loadChoroplethWorldSubregion1(self, filter):

        return ()

    def showLoadProgress(self, percent):

        if percent < 100:
            self.setWindowTitle(self.title + ": " + str(percent) + "%")
        else:
            self.setWindowTitle(self.title)
Example #29
0
class MyPyQT_Form(QtWidgets.QWidget, Ui_Form):
    def __init__(self):
        super(MyPyQT_Form, self).__init__()

        self.setupUi(self)
        self.view = QWebEngineView(self)
        self.view.setGeometry(QtCore.QRect(10, 60, 561, 611))

        self.pushButton_start.clicked.connect(self.start)
        self.pushButton_end.clicked.connect(self.end)
        self.pushButton_ok.clicked.connect(self.get_answer)
        self.pushButton_choosefile.clicked.connect(self.open_file)

        self.fileName = "article.txt"

        self.show_article()

        self.pushButton_ok.setEnabled(False)

    def start(self):
        #self.start_time = time.time()
        self.timer_id = self.startTimer(1000,
                                        timerType=QtCore.Qt.VeryCoarseTimer)
        self.pushButton_start.setEnabled(False)
        self.pushButton_end.setEnabled(True)
        threading.Thread(target=self.record, ).start()

    def end(self):
        self.signal = False
        if self.timer_id:
            self.killTimer(self.timer_id)
            self.timer_id = 0
        self.pushButton_start.setEnabled(True)
        self.pushButton_end.setEnabled(False)

        # 显示询问
        self.question = XF_text("output.wav", 16000)
        self.textEdit_question.setText(self.question)
        self.pushButton_ok.setEnabled(True)

    def get_answer(self):
        """
        输入文本,调用模型预测
        """
        self.movie = QtGui.QMovie("icon/loading.gif")
        self.movie.setCacheMode(QtGui.QMovie.CacheAll)
        self.movie.setSpeed(100)

        self.label_mrc.setMovie(self.movie)
        self.movie.start()

        self.question = self.textEdit_question.toPlainText()
        # t = threading.Thread(target=self.run_predict, )
        # t.start()
        # t.join()
        self.run_predict()

    def run_predict(self):
        with open(self.fileName, "r", encoding="utf-8") as f:
            content = f.read()

        data = {
            "version":
            "v1.0",
            "data": [{
                "paragraphs": [{
                    "id":
                    "MRC",
                    "context":
                    content,
                    "qas": [{
                        "question": self.question,
                        "id": "QUERY",
                        "answers": [{
                            "text": "",
                            "answer_start": 0
                        }]
                    }]
                }],
                "id":
                "DEV_0",
                "title":
                "title"
            }]
        }
        with open("eval.json", "w", encoding="utf-8") as f:
            json.dump(data, f, indent=2, ensure_ascii=False)

        # t = threading.Thread(target=self.run_cmd,)
        # t.start()
        # t.join()
        self.thread = Thread()
        self.thread.start()
        self.thread.trigger.connect(self.output)

    def output(self):
        # os.system("python D:\\ML_DL\\nlp\\mrc_bert\\run_mrc.py \
        #   --vocab_file=D:\\ML_DL\\nlp\\mrc_bert\\chinese_L-12_H-768_A-12/vocab.txt \
        #   --bert_config_file=D:\\ML_DL\\nlp\\mrc_bert\\chinese_L-12_H-768_A-12/bert_config.json \
        #   --init_checkpoint=D:\\ML_DL\\nlp\\mrc_bert\\chinese_L-12_H-768_A-12/bert_model.ckpt \
        #   --do_train=False \
        #   --do_predict=True \
        #   --predict_file=D:\\ML_DL\\nlp\\mrc_gui\\eval.json \
        #   --train_batch_size=6 \
        #   --predict_batch_size=4 \
        #   --learning_rate=3e-5 \
        #   --num_train_epochs=2.0 \
        #   --max_seq_length=384 \
        #   --doc_stride=128 \
        #   --output_dir=D:\\ML_DL\\nlp\\mrc_gui")

        with open("predictions.json", "r", encoding="utf-8") as f:
            self.answer = json.load(f)["QUERY"]

        # GUI相关对象不能再非GUI的线程中创建和使用
        self.label_mrc.setPixmap(QtGui.QPixmap("icon/结束.png"))
        self.label_mrc.setScaledContents(True)

        self.textBrowser_question.setText(self.answer)

        #读取答案
        #XF_Speak(answer)
        threading.Thread(target=self.speak, ).start()
        # with open("nbest_predictions.json", "r", encoding="utf-8") as f:
        #     nbest = json.load(f)

    def speak(self):
        XF_Speak(self.answer)

    def timerEvent(self, event):
        end_time = time.strftime("%H:%M:%S")
        self.label_question.setText(end_time)

    def record(self):
        self.signal = True
        CHUNK = 256
        FORMAT = pyaudio.paInt16
        CHANNELS = 1
        RATE = 11025

        p = pyaudio.PyAudio()

        stream = p.open(format=FORMAT,
                        channels=CHANNELS,
                        rate=RATE,
                        input=True,
                        frames_per_buffer=CHUNK)

        frames = []
        while self.signal:
            data = stream.read(CHUNK)
            frames.append(data)

        stream.stop_stream()
        stream.close()
        p.terminate()

        wf = wave.open("output.wav", 'wb')
        wf.setnchannels(CHANNELS)
        wf.setsampwidth(p.get_sample_size(FORMAT))
        wf.setframerate(RATE)
        wf.writeframes(b''.join(frames))

    def show_article(self, start=None, end=None):
        # 绝对地址,否则无法正常显示
        self.view.setHtml(self.get_article(start, end),
                          baseUrl=QtCore.QUrl.fromLocalFile(
                              os.path.abspath('article.html')))

    def get_article(self, start=None, end=None):
        """获取好友动态
        渲染生成HTML代码
        """
        # 读取用户好友动态
        env = Environment(loader=FileSystemLoader("./"))
        template = env.get_template("article.html")

        article = "Article"
        with open(self.fileName, "r", encoding="utf-8") as f:
            content = f.read()

        # 渲染结果
        if start:
            pre = "<span style=\"background:red\">"
            post = "</span>"
            content = content[:start] + pre + content[
                start:end] + post + content[end:]

        content = template.render(article=article, content=content)
        return content

    def open_file(self):
        """点击按钮、读取文件、并渲染到文本框中"""
        self.fileName, self.filetype = QFileDialog.getOpenFileName(
            self, "选取文件", "./",
            "Text Files (*.txt);;All Files (*)")  # 设置文件扩展名过滤,注意用双分号间隔

        if self.fileName != "":
            self.show_article()
        else:
            self.fileName = "article.txt"
Example #30
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow, init_kr):
        self.bian=[]
        self.ans_path=[]
        self.ans_path2=[]
        self.i1=0
        self.i2=0
        self.flag1=1
        self.flag2=1
        MainWindow.setObjectName("MainWindow")
        MainWindow.setEnabled(True)
        MainWindow.resize(1920, 1000)
        self.new_kr = init_kr
        self.new_kr.init_graph()
        with open("Qobject.qss", "r") as f:
            qApp.setStyleSheet(f.read())
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        #  左边的点和边 listQwidget
        self.widget = QtWidgets.QWidget(self.centralwidget)
        self.widget.setGeometry(QtCore.QRect(30, 190, 291, 651))
        self.widget.setObjectName("widget")
        self.gridLayout = QtWidgets.QGridLayout(self.widget)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setObjectName("gridLayout")
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.label3 = QtWidgets.QLabel(self.widget)
        self.label3.setObjectName("label")
        self.verticalLayout.addWidget(self.label3)
        self.listWidget = QtWidgets.QListWidget(self.widget)
        self.listWidget.setObjectName("listWidget")
        self.verticalLayout.addWidget(self.listWidget)
        self.gridLayout.addLayout(self.verticalLayout, 0, 0, 1, 1)
        self.verticalLayout_2 = QtWidgets.QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.label_4 = QtWidgets.QLabel(self.widget)
        self.label_4.setObjectName("label_2")
        self.verticalLayout_2.addWidget(self.label_4)
        self.listWidget_2 = QtWidgets.QListWidget(self.widget)
        self.listWidget_2.setObjectName("listWidget_2")
        self.verticalLayout_2.addWidget(self.listWidget_2)
        self.gridLayout.addLayout(self.verticalLayout_2, 0, 1, 1, 1)


        #上面的插入模块
        self.gridLayoutWidget = QtWidgets.QWidget(self.centralwidget)
        self.gridLayoutWidget.setGeometry(QtCore.QRect(40, 30, 441, 51))
        self.gridLayoutWidget.setObjectName("gridLayoutWidget")
        self.gridLayout = QtWidgets.QGridLayout(self.gridLayoutWidget)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setObjectName("gridLayout")
        self.lineEdit = QtWidgets.QLineEdit(self.gridLayoutWidget)
        self.lineEdit.setObjectName("lineEdit")
        self.gridLayout.addWidget(self.lineEdit, 2, 0, 1, 1)
        self.label = QtWidgets.QLabel(self.gridLayoutWidget)
        self.label.setObjectName("label")
        self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
        self.lineEdit_3 = QtWidgets.QLineEdit(self.gridLayoutWidget)
        self.lineEdit_3.setObjectName("lineEdit_3")
        self.gridLayout.addWidget(self.lineEdit_3, 2, 2, 1, 1)
        self.label_2 = QtWidgets.QLabel(self.gridLayoutWidget)
        self.label_2.setObjectName("label_2")
        self.gridLayout.addWidget(self.label_2, 0, 1, 1, 1)
        self.lineEdit_2 = QtWidgets.QLineEdit(self.gridLayoutWidget)
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.gridLayout.addWidget(self.lineEdit_2, 2, 1, 1, 1)
        self.label_3 = QtWidgets.QLabel(self.gridLayoutWidget)
        self.label_3.setObjectName("label_3")
        self.gridLayout.addWidget(self.label_3, 0, 2, 1, 1)
        self.horizontalLayoutWidget = QtWidgets.QWidget(self.centralwidget)
        self.horizontalLayoutWidget.setGeometry(QtCore.QRect(40, 90, 441, 51))
        self.horizontalLayoutWidget.setObjectName("horizontalLayoutWidget")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget)
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.pushButton_5 = QtWidgets.QPushButton(self.horizontalLayoutWidget)
        self.pushButton_5.setObjectName("pushButton_5")
        self.horizontalLayout.addWidget(self.pushButton_5)


        #右边的一列按钮操作
        self.widget = QtWidgets.QWidget(MainWindow)
        self.widget.setGeometry(QtCore.QRect(400, 190, 191, 651))
        self.widget.setObjectName("widget")
        self.verticalLayout_3 = QtWidgets.QVBoxLayout(self.widget)
        self.verticalLayout_3.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.pushButton = QtWidgets.QPushButton(self.widget)
        self.pushButton.setObjectName("pushButton")
        self.verticalLayout_3.addWidget(self.pushButton)

        self.pushButton_2 = QtWidgets.QPushButton(self.widget)
        self.pushButton_2.setObjectName("pushButton_2")
        self.verticalLayout_3.addWidget(self.pushButton_2)

        self.pushButton_3 = QtWidgets.QPushButton(self.widget)
        self.pushButton_3.setObjectName("pushButton_3")
        self.verticalLayout_3.addWidget(self.pushButton_3)

        self.pushButton_9 = QtWidgets.QPushButton(self.widget)
        self.pushButton_9.setObjectName("pushButton_9")
        self.verticalLayout_3.addWidget(self.pushButton_9)


        self.pushButton_4 = QtWidgets.QPushButton(self.widget)
        self.pushButton_4.setObjectName("pushButton_4")
        self.verticalLayout_3.addWidget(self.pushButton_4)

        self.pushButton_7 = QtWidgets.QPushButton(self.widget)
        self.pushButton_7.setObjectName("pushButton_7")
        self.verticalLayout_3.addWidget(self.pushButton_7)

        # 这个是prim 的逐条显示增加
        self.pushButton_10 = QtWidgets.QPushButton(self.widget)
        self.pushButton_10.setObjectName("pushButton_10")
        self.verticalLayout_3.addWidget(self.pushButton_10)
        #逐条减少
        self.pushButton_13= QtWidgets.QPushButton(self.widget)
        self.pushButton_13.setObjectName("pushButton_13")
        self.verticalLayout_3.addWidget(self.pushButton_13)


        self.pushButton_8 = QtWidgets.QPushButton(self.widget)
        self.pushButton_8.setObjectName("pushButton_8")
        self.verticalLayout_3.addWidget(self.pushButton_8)

        # 这个是克鲁斯卡尔   逐条显示增加
        self.pushButton_11 = QtWidgets.QPushButton(self.widget)
        self.pushButton_11.setObjectName("pushButton_11")
        self.verticalLayout_3.addWidget(self.pushButton_11)
        #逐条减少
        self.pushButton_12 = QtWidgets.QPushButton(self.widget)
        self.pushButton_12.setObjectName("pushButton_12")
        self.verticalLayout_3.addWidget(self.pushButton_12)

        self.pushButton_6 = QtWidgets.QPushButton(self.widget)
        self.pushButton_6.setObjectName("pushButton_6")
        self.verticalLayout_3.addWidget(self.pushButton_6)
        MainWindow.setCentralWidget(self.centralwidget)








        #这个是最下面最小生成树的代价
        self.widget1 = QtWidgets.QWidget(MainWindow)
        self.widget1.setGeometry(QtCore.QRect(30, 890, 261, 41))
        self.widget1.setObjectName("widget1")
        self.horizontalLayout = QtWidgets.QHBoxLayout(self.widget1)
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.label_5 = QtWidgets.QLabel(self.widget1)
        self.label_5.setObjectName("label_5")
        self.horizontalLayout.addWidget(self.label_5)
        self.textBrowser = QtWidgets.QTextBrowser(self.widget1)
        self.textBrowser.setObjectName("textBrowser")
        self.horizontalLayout.addWidget(self.textBrowser)

        self.widget2 = QtWidgets.QWidget(MainWindow)
        self.widget2.setGeometry(QtCore.QRect(300, 890, 261, 41))
        self.widget2.setObjectName("widget2")
        self.horizontalLayout2 = QtWidgets.QHBoxLayout(self.widget2)
        self.horizontalLayout2.setContentsMargins(0, 0, 0, 0)
        self.horizontalLayout2.setObjectName("horizontalLayout2")
        self.label_6 = QtWidgets.QLabel(self.widget2)
        self.label_6.setObjectName("label_6")
        self.horizontalLayout2.addWidget(self.label_6)
        self.textBrowser2 = QtWidgets.QTextBrowser(self.widget2)
        self.textBrowser2.setObjectName("textBrowser2")
        self.horizontalLayout2.addWidget(self.textBrowser2)



        #右边的浏览器加载 html 文件
        self.stackedWidget = QtWidgets.QStackedWidget(MainWindow)
        self.stackedWidget.setFrameShape(QtWidgets.QFrame.Box)
        self.stackedWidget.setObjectName("stackedWidget")
        self.stackedWidget.setGeometry(600, 10, 1300, 950)
        self.browser = QWebEngineView(self.stackedWidget)
        self.browser.setGeometry(0, 0, 1300, 950)


        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)



        with open(self.new_kr.file, 'r', True, 'utf-8') as f:
            f.readline()
            f.readline()
            for line in f.readlines():
                list= line.replace('\n', '')
                item=QListWidgetItem()
                item.setText(list)
                self.listWidget_2.addItem(item)
        for i in range(len(self.new_kr.place_name)):
            item=QListWidgetItem()
            item.setText(self.new_kr.place_name[i])
            self.listWidget.addItem(item)
        self.pyecharts_update12(1,0,0,0,0,0,0)

        #插入操作
        self.pushButton_5.clicked.connect(self.update1)

        #删除操作
        self.listWidget.clicked.connect(self.check)
        self.pushButton.clicked.connect(self.remove)
        self.listWidget_2.clicked.connect(self.check1)
        self.pushButton_2.clicked.connect(self.remove1)



        # 进行写文件
        self.pushButton_6.clicked.connect(self.write)

        #prim 算法
        self.pushButton_3.clicked.connect(self.prim)
        #克鲁斯卡尔算法
        self.pushButton_9.clicked.connect(self.Kruskal)

        # 可视化
        self.pushButton_4.clicked.connect(lambda: (self.pyecharts_update12(1,0,0,0,0,0,0)))
        #prim 路径
        self.pushButton_7.clicked.connect(lambda:(self.pyecharts_update12(0,1,0,0,0,0,0)))
        # prim 增加边
        self.pushButton_10.clicked.connect(lambda: (self.pyecharts_update12(0,0,1,0,0,0,0)))
        # prim 减少边
        self.pushButton_13.clicked.connect(lambda: (self.pyecharts_update12(0,0,0,1,0,0,0)))
        #克鲁斯卡尔 路径
        self.pushButton_8.clicked.connect(lambda:(self.pyecharts_update12(0,0,0,0,1,0,0)))
        #克鲁斯卡尔增加边
        self.pushButton_11.clicked.connect(lambda: (self.pyecharts_update12(0,0,0,0,0,1,0)))
        #克鲁斯卡尔减少边
        self.pushButton_12.clicked.connect(lambda: (self.pyecharts_update12(0,0,0,0,0,0,1)))

    #删除点
    def check(self,index):
        self.listWidget_2.clearSelection()
    def remove(self):
        if self.listWidget.selectedItems():
            # print(self.listWidget.currentItem().text())
            item = self.listWidget.currentItem()
            self.listWidget.takeItem(self.listWidget.row(item))
            self.listWidget.clearSelection()

            self.new_kr.matrix=np.delete(self.new_kr.matrix,self.new_kr.dict[item.text()],0)
            self.new_kr.matrix = np.delete(self.new_kr.matrix, self.new_kr.dict[item.text()], 1)
            self.new_kr.place_name.remove(item.text())
            self.new_kr.m-=1
            self.new_kr.n= int(np.sum(self.new_kr.matrix!=float('inf'))/2)
            self.new_kr.dict = dict(zip(self.new_kr.place_name, range(self.new_kr.m)))
            self.new_kr.dict1=dict(zip( range(self.new_kr.m),self.new_kr.place_name))

            # print(self.new_kr.m,self.new_kr.n)
            # print(self.new_kr.matrix)
            # print(self.new_kr.place_name)
            # print(self.new_kr.dict)

            data=[]
            for i in range(self.listWidget_2.count()):
                if item.text() in self.listWidget_2.item(i).text().split(' '):
                    if i not in data:
                        data.append(i)
            data=np.array(data)
            for i in data:
                self.listWidget_2.takeItem(i)
                data-=1
        self.bian = list((self.new_kr.place_name[x], self.new_kr.place_name[y]) for x in range(self.new_kr.m) for y in
                         range(x + 1, self.new_kr.m) if self.new_kr.matrix[x][y] != float('inf'))

    #删除边的
    def check1(self,index):
        self.listWidget.clearSelection()
    def remove1(self):
        if self.listWidget_2.selectedItems():
            # print(self.listWidget_2.currentItem().text())
            item = self.listWidget_2.currentItem()
            self.listWidget_2.takeItem(self.listWidget_2.row(item))
            self.listWidget_2.clearSelection()
            #先进行判断处理, 点可以影响边
            if item.text().split(' ')[0] in self.new_kr.place_name and item.text().split(' ')[1] in self.new_kr.place_name :
                a,b=self.new_kr.dict[item.text().split(' ')[0]],self.new_kr.dict[item.text().split(' ')[1]]
                self.new_kr.matrix[a][b]=float('inf')
                self.new_kr.matrix[b][a]=float('inf')
                self.new_kr.n-=1
                # print(self.new_kr.matrix)
        self.bian = list((self.new_kr.place_name[x], self.new_kr.place_name[y]) for x in range(self.new_kr.m) for y in
                     range(x + 1, self.new_kr.m) if self.new_kr.matrix[x][y] != float('inf'))

    #每一个的显示问题
    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label.setText(_translate("MainWindow", "起始点"))
        self.label_2.setText(_translate("MainWindow", "终点"))
        self.label_3.setText(_translate("MainWindow", "权值"))
        self.label3.setText(_translate("MainWindow", "点"))
        self.label_4.setText(_translate("MainWindow", "边"))
        self.pushButton_5.setText(_translate("MainWindow", "插入"))
        self.pushButton.setText(_translate("MainWindow", "删除点"))
        self.pushButton_2.setText(_translate("MainWindow", "删除边"))
        self.pushButton_3.setText(_translate("MainWindow", "prim"))
        self.pushButton_4.setText(_translate("MainWindow", "可视化"))
        self.pushButton_6.setText(_translate("MainWindow", "记录到文件"))
        self.label_5.setText(_translate("MainWindow", "prim代价为"))
        self.label_6.setText(_translate("MainWindow", "Kruskal代价为"))
        self.pushButton_7.setText(_translate("MainWindow", "prim路径"))
        self.pushButton_8.setText(_translate("MainWindow", "Kruskal路径"))
        self.pushButton_9.setText(_translate("MainWindow", "Kruskal"))
        self.pushButton_10.setText(_translate("MainWindow", "prim上一条"))
        self.pushButton_13.setText(_translate("MainWindow", "prim下一条"))
        self.pushButton_11.setText(_translate("MainWindow", "Kruskal上一条"))
        self.pushButton_12.setText(_translate("MainWindow", "Kruskal下一条"))

    #插入点更新
    def update1(self):
        if (self.lineEdit.text()) and (self.lineEdit_2.text()) and (self.lineEdit_3.text()):
            if self.lineEdit.text() not in self.new_kr.place_name:
                item1=QListWidgetItem()
                item1.setText(self.lineEdit.text())
                self.listWidget.addItem(item1)
                self.new_kr.updata_node(self.lineEdit)
            if self.lineEdit_2.text() not in self.new_kr.place_name:
                item2 = QListWidgetItem()
                item2.setText(self.lineEdit_2.text())
                self.listWidget.addItem(item2)
                self.new_kr.updata_node(self.lineEdit_2)

            from1 = self.new_kr.dict[self.lineEdit.text()]
            to = self.new_kr.dict[self.lineEdit_2.text()]
            value = self.lineEdit_3.text()
            value = float(value)
            if self.new_kr.matrix[from1][to]==float('inf'):
                string=self.lineEdit.text()+' '+self.lineEdit_2.text()+' '+self.lineEdit_3.text()
                item = QListWidgetItem()
                item.setText(string)
                self.listWidget_2.addItem(item)
                self.new_kr.updata_edge(from1, to, value)


            # print(self.new_kr.matrix[from1][to],value,'-----')
            if  self.new_kr.matrix[from1][to]>value:
                self.new_kr.matrix[from1][to]=value
                self.new_kr.matrix[to][from1]=value
                for item3 in self.listWidget_2.selectedItems():
                    a,b=[(item3.text()).split(' ')][:2]
                    # print(a,b)
                    if a==self.listWidget.text() and b==self.listWidget_2.text() :
                        self.listWidget_2.takeItem(self.listWidget_2.row(item3))
                        break

                for i in range(self.listWidget_2.count()):
                    if self.lineEdit.text() in self.listWidget_2.item(i).text().split(' ') and self.lineEdit_2.text() in self.listWidget_2.item(i).text().split(' '):
                        self.listWidget_2.takeItem(i)
                        break
                string = self.lineEdit.text() + ' ' + self.lineEdit_2.text() + ' ' + self.lineEdit_3.text()
                item = QListWidgetItem()
                item.setText(string)
                self.listWidget_2.addItem(item)



        else:
            pass

        # print(self.new_kr.m, self.new_kr.n)
        # print(self.new_kr.matrix)
        self.bian = list((self.new_kr.place_name[x], self.new_kr.place_name[y]) for x in range(self.new_kr.m) for y in
                         range(x + 1, self.new_kr.m) if self.new_kr.matrix[x][y] != float('inf'))

        # print(self.new_kr.m,self.new_kr.n)
        # print(self.new_kr.place_name)
        # print(self.new_kr.dict)
        # print(self.new_kr.matrix)
        # print(self.new_kr.dict1)




    #克鲁斯卡尔算法
    def Kruskal(self):
        self.flag2 = 1                                                                                                  #初始化是要进行的
        self.ans_path2=[]
        self.i2=0
        def q_sort(L, left, right):
            if left < right:
                pivot = Partition(L, left, right)

                q_sort(L, left, pivot - 1)
                q_sort(L, pivot + 1, right)
            return L

        def Partition(L, left, right):
            pivotkey = L[left]

            while left < right:
                while left < right and L[right][2] >= pivotkey[2]:
                    right -= 1
                L[left] = L[right]
                while left < right and L[left][2] <= pivotkey[2]:
                    left += 1
                L[right] = L[left]

            L[left] = pivotkey
            return left

        def find(x):
            if x==child[x]:
                # print(x)
                return x

            else:
                child[x]=find(child[x])
                return child[x]

        edge=[]
        child=list(range(self.new_kr.m))

        # for i in range(self.listWidget_2.count()):
        #     item=self.listWidget_2.item(i).text().split(' ')
        #     x=int(self.new_kr.dict[item[0]])
        #     y=int(self.new_kr.dict[item[1]])
        #     z=float(item[2])
        #     edge1.append((x,y,z))

        edge= list((x, y,self.new_kr.matrix[x][y]) for x in range(self.new_kr.m) for y in
                         range(x + 1, self.new_kr.m) if self.new_kr.matrix[x][y] != float('inf'))

        q_sort(edge,0,len(edge)-1)
        # print(edge)
        ans = 0
        k=self.new_kr.m-1

        # print(child)

        for i in range(len(edge)):
            f1=find(edge[i][0])
            f2=find(edge[i][1])
            if  f1!=f2:
                k-=1
                # print(k)
                child[f1]=f2
                ans+=edge[i][2]
                self.ans_path2.append((self.new_kr.dict1[edge[i][0]],self.new_kr.dict1[edge[i][1]]))
        if k<=0:
            self.textBrowser2.setText(str(ans))
        else:
            self.textBrowser2.setText('构不成最小生成树')
            self.ans_path2.clear()
            self.flag2=0


    #prim算法
    def prim(self):
        self.i1=0
        self.flag1=1                                                                                                    #初始化
        ans=0
        self.ans_path=[]
        dis=[0]*100
        vis=[0]*100
        pre=[0]*100
        for i in range(self.new_kr.m):
                dis[i]=self.new_kr.matrix[0][i]
        vis[0]=1
        for i in range(1,self.new_kr.m):
            minv=float('inf')
            pos=-1
            for j in range(self.new_kr.m):
                if(not vis[j] and dis[j] <minv):
                    minv=dis[j]
                    pos=j
            if pos==-1:
                self.textBrowser.setText('构不成最小生成树')
                self.flag1=0
                break
            ans+=minv

            self.ans_path.append((self.new_kr.dict1[pre[pos]],self.new_kr.dict1[pos]))

            vis[pos]=1

            for j in range(self.new_kr.m):
                if(not vis[j] and  dis[j]>self.new_kr.matrix[pos][j] ):
                    dis[j]=self.new_kr.matrix[pos][j]
                    pre[j]=pos
        if self.flag1:
            self.textBrowser.setText(str(ans))
        else:
            self.ans_path.clear()




    #进行写入文件
    def write(self):
        k=0
        with open("in.txt",'w',encoding='utf-8') as f:
            f.write(str(self.new_kr.m)+' '+str(self.new_kr.n)+'\n')
            for i in range(self.listWidget.count()):
                if k:
                    f.write(' ')
                k=1
                f.write(self.listWidget.item(i).text())
            f.write('\n')
            for i in range(self.listWidget_2.count()):
                f.write(self.listWidget_2.item(i).text()+'\n')




    #一堆的显示图像
    def pyecharts_update12(self, show_all, show_prim, prim_dele,prim_add ,show_Kruskal,   Kruskal_dele,Kruskal_add):  #
        def diff_set(a, b):
            a_, b_ = map(lambda x: {frozenset(k): k for k in x}, [a, b])
            return [a_[k] for k in a_.keys() - b_.keys()]

        place = list(zip(self.new_kr.place_name, range(self.new_kr.m)))
        self.bian = list(
            (self.new_kr.place_name[x], self.new_kr.place_name[y]) for x in range(self.new_kr.m) for y in  # 算一下边
            range(x + 1, self.new_kr.m) if self.new_kr.matrix[x][y] != float('inf'))

        attr1 = self.bian
        if show_all:
            attr2 = []
            attr3 = attr1
            self.i1=self.i2=0
        elif show_prim:
            if self.flag1 == 0:
                self.ans_path.clear()
            attr2 = self.ans_path
            attr3 = diff_set(attr1, attr2)
            print('prim路径数量为',len(attr2))
        elif show_Kruskal:
            if self.flag2 == 0:
                self.ans_path2.clear()
            attr2 = self.ans_path2
            attr3 = diff_set(attr1, attr2)
            print('克鲁斯卡尔路径数量为', len(attr2))
        elif prim_add:
            self.i1+=1
            if self.i1>self.new_kr.m-1:
                self.i1 =0
            attr2 = self.ans_path[:self.i1]
            attr3 = diff_set(attr1, attr2)

            print('prim',self.i1)
        elif prim_dele:
            self.i1 -= 1
            if self.i1 < 0:
                self.i1 = self.new_kr.m-1
            attr2 = self.ans_path[:self.i1]
            attr3 = diff_set(attr1, attr2)
            print('prim',self.i1)

        elif Kruskal_add:
            self.i2+=1
            if self.i2>self.new_kr.m-1:
                self.i2=0
            attr2 = self.ans_path2[:self.i2]
            attr3 = diff_set(attr1, attr2)

            print('Kruskal',self.i2)
        elif Kruskal_dele:
            self.i2 -= 1
            if self.i2 < 0:
                self.i2 = self.new_kr.m-1
            attr2 = self.ans_path2[:self.i2]
            attr3 = diff_set(attr1, attr2)

            print('Kruskal',self.i2)

        geo = (
            Geo(init_opts={"width": 1300, "bg_color": "#2a59"})
                .add_schema(
                maptype="china",
                itemstyle_opts=opts.ItemStyleOpts(color="#323c48", border_color="#111"),
                # label_opts=opts.LabelOpts(is_show=True)
            )
                .add(  # 这个不用动
                "",
                place,
                type_=ChartType.EFFECT_SCATTER,
                color="green",
                label_opts=opts.LabelOpts(is_show=True)
            )
                .add(  # 路径以外的边
                "",
                attr3,
                type_=ChartType.LINES,
                linestyle_opts=opts.LineStyleOpts(curve=0.2, color='red'),
            )
                .add(  # 路径的边
                "",
                attr2,
                type_=ChartType.LINES,
                linestyle_opts=opts.LineStyleOpts(curve=0.2, color='white'),
            )

                .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
                .set_global_opts(title_opts=opts.TitleOpts(title="城市交通图"))
        )
        geo.render(path='D:/pycharm/untitled/GUI/图.html')
        self.browser.load(QUrl("file:///D:/pycharm/untitled/GUI/图.html"))
Example #31
0
class LocateRecognizeView(QWidget):

    def __init__(self, *args, **kwargs):
        super(LocateRecognizeView, self).__init__(*args, **kwargs)
        self.ori_image_path = None                  # 选中的原图像路径
        self.ori_label_list = []                    # 选中图像对应的文本信息, 若没有则为空
        self.res_image_list = None                  # [(定位出文本行的图像, [文本行图像])]
        self.start_flag = False                     # 当前是否正在定位识别
        self.show_diff_flag = False                 # 是否显示对比结果视图,默认为False(选中图像无对应txt文件)
        self.locate_start_timer = 0                 # 定位计时器起始时间
        self.locate_end_timer = 0                   # 定位计时器结束时间
        self.rec_start_timer = 0                    # 识别计时器起始时间
        self.rec_end_timer = 0                      # 识别计时器结束时间
        self.setStyleSheet(LRStylesheet)            # 初始化GUI样式
        self.initUi()                               # 初始化GUI布局

        self.texts_rect = []                        # 文本行图像位置

        self.dbnetThread = None                     # 初始化DBNet定位后台线程
        self.backThread = None                      # 初始化形态学定位后台线程
        self.recogBackThread = None                 # 初始化识别后台线程

    # 界面布局
    def initUi(self):

        # 内容视图, 管理所有的子视图
        self.content_view = QWidget(self)
        self.content_view.setObjectName("Content_View")
        self.content_view.setGeometry(QRect(0, 0, Sub_Win_Width, Sub_Win_Height))

        # 顶部状态栏
        self.top_state_bar = QWidget(self.content_view)
        self.top_state_bar.setObjectName("Top_State_Bar")
        self.top_state_bar.setGeometry(QRect(0, 0, Top_State_Bar_Width, Top_State_Bar_Height))
        # 选择文件按钮:
        self.choose_img_btn = QPushButton(self.top_state_bar)
        self.choose_img_btn.setGeometry(QRect(Top_State_Bar_Width / 2 - 50, 10, 100, 60))
        self.choose_img_btn.setObjectName("Choose_Img_Btn")
        self.choose_img_btn.setText("选择文件")
        self.choose_img_btn.clicked.connect(self.choose_img_file)

        # 启用DBNet按钮
        self.switch_button = SwitchButton(self.content_view)
        self.switch_button.setGeometry(QRect(680, 90, 70, 30))
        self.switch_button.setObjectName("Switch_Button")
        self.switch_label = QLabel(self.content_view)
        self.switch_label.setObjectName("Switch_Label")
        self.switch_label.setGeometry(QRect(665, 120, 100, 30))
        self.switch_label.setAlignment(Qt.AlignCenter)
        self.switch_label.setText("启用DBNet")

        # 全尺寸背景视图
        self.full_size_content_widget = QWidget(self.content_view)
        self.full_size_content_widget.setObjectName("Full_Size_Content_Widget")
        self.full_size_content_widget.setGeometry(QRect(60, 150, Locate_Show_Area_Width * 2 + 50 + 25 * 2, Locate_Show_Area_Height + 120))
        # 全尺寸webview
        self.full_size_web_view = QWebEngineView(self.full_size_content_widget)
        self.full_size_web_view.setObjectName("Full_Size_Web_View")
        self.full_size_web_view.setGeometry(QRect(20, 20, Locate_Show_Area_Width * 2 + 50 + 10, Locate_Show_Area_Height + 30))
        self.full_size_web_view.setHidden(True)  # 默认隐藏
        # 退出全尺寸按钮
        self.exit_full_button = QPushButton(self.full_size_content_widget)
        self.exit_full_button.setObjectName("Exit_Full_Button")
        self.exit_full_button.setGeometry(QRect(590, 765, 100, 40))
        self.exit_full_button.setText("退出")
        self.exit_full_button.clicked.connect(self.exit_full_size_view_mode)

        # 中间识别区域
        self.show_area_widget = QWidget(self.content_view)
        self.show_area_widget.setObjectName("Show_Area_Widget")
        self.show_area_widget.setGeometry(QRect(60, 150, Locate_Show_Area_Width * 2 + 50 + 25 * 2, Locate_Show_Area_Height + 120))

        # 左侧图像区域: 显示定位出文本行的图片
        self.ori_image_View = QLabel(self.show_area_widget)
        self.ori_image_View.setGeometry(QRect(25, 25, Locate_Show_Area_Width, Locate_Show_Area_Height))
        self.ori_image_View.setObjectName("Ori_Image_View")
        self.ori_image_View.setScaledContents(True)             # 对图像进行缩放显示
        # 中间放大按钮区域
        self.mid_circle_area = QLabel(self.show_area_widget)
        self.mid_circle_area.setObjectName("Mid_Circle_Area")
        self.mid_circle_area.setGeometry(QRect(Locate_Show_Area_Width+25, 320, 50, 50))
        self.mid_circle_area.setHidden(True)                # 默认隐藏, 显示对比视图时再显示
        # 放大按钮
        self.mid_zoom_btn = QPushButton(self.mid_circle_area)
        self.mid_zoom_btn.setObjectName("Mid_Zoom_Btn")
        self.mid_zoom_btn.setGeometry(QRect(5, 5, 40, 40))
        self.mid_zoom_btn.clicked.connect(self.show_full_size_view)

        # 右侧识别文字区域
        self.text_area_widget = QLabel(self.show_area_widget)
        self.text_area_widget.setGeometry(QRect(25 + Locate_Show_Area_Width + 50, 25, Locate_Show_Area_Width, Locate_Show_Area_Height))
        self.text_area_widget.setObjectName("Text_Area_Widget")
        # 自定义textview: 无对应标签时展示
        self.res_text_view = PaintTextView(self.text_area_widget)
        self.res_text_view.setGeometry(QRect(20, 20, Locate_Show_Area_Width - 20 * 2, Locate_Show_Area_Height - 20 * 2))
        self.res_text_view.setObjectName("Res_Text_View")
        # web界面: 有对应标签时展示
        self.diff_web_view = QWebEngineView(self.text_area_widget)
        self.diff_web_view.setObjectName("Diff_Web_View")
        self.diff_web_view.setGeometry(QRect(20, 20, Locate_Show_Area_Width - 20 * 2, Locate_Show_Area_Height - 20 * 2))
        self.diff_web_view.setHidden(True)              # 默认隐藏
        self.diff_web_view.setZoomFactor(0.70)          # 缩放

        # 下方状态信息栏
        self.bottom_state_bar = QWidget(self.show_area_widget)
        self.bottom_state_bar.setGeometry(QRect(250, 740, 800, 60))
        self.bottom_state_bar.setObjectName("Bottom_State_Bar")
        # 定位总时长Label
        self.locate_time_label = QLabel(self.bottom_state_bar)
        self.locate_time_label.setGeometry(QRect(20, 20, 200, 20))
        self.locate_time_label.setObjectName("Locate_Time_Label")
        self.locate_time_label.setAlignment(Qt.AlignLeft)
        # AR label
        self.ar_label = QLabel(self.bottom_state_bar)
        self.ar_label.setGeometry(QRect(260, 20, 100, 20))
        self.ar_label.setObjectName("AR_Label")
        self.ar_label.setAlignment(Qt.AlignLeft)
        # 相似度Label
        self.sim_ratio_label = QLabel(self.bottom_state_bar)
        self.sim_ratio_label.setGeometry(QRect(360, 20, 100, 20))
        self.sim_ratio_label.setObjectName("Sim_Ratio_Label")
        self.sim_ratio_label.setAlignment(Qt.AlignCenter)
        # CR label
        self.cr_label = QLabel(self.bottom_state_bar)
        self.cr_label.setGeometry(QRect(500, 20, 100, 20))
        self.cr_label.setObjectName("CR_Label")
        self.cr_label.setAlignment(Qt.AlignLeft)
        # 识别总时长Label
        self.rec_time_label = QLabel(self.bottom_state_bar)
        self.rec_time_label.setGeometry(QRect(560, 20, 200, 20))
        self.rec_time_label.setObjectName("Rec_Time_Label")
        self.rec_time_label.setAlignment(Qt.AlignRight)


    # 事件响应
    @pyqtSlot()
    # 选择单个图像文件
    def choose_img_file(self):
        if self.start_flag:                 # 正在处理中,则不再响应
            return

        # 获取图像路径: 支持的图像类型(jpg, png)
        file_path, file_type = QFileDialog.getOpenFileName(self, "选取文件", fm.get_Curr_Dir(), "Images (*.jpg *.png)")
        if file_path == "":  # 取消选择
            return

        # 重置参数
        self.show_diff_flag = False
        self.ori_image_path = None
        self.ori_label_list = []
        self.res_image_list = None
        self.locate_start_timer = 0
        self.locate_end_timer = 0
        self.rec_start_timer = 0
        self.rec_end_timer = 0
        self.backThread = None
        self.dbnetThread = None
        self.exit_full_size_view_mode()
        self.mid_circle_area.setHidden(True)                                # 默认隐藏放大按钮区域
        self.res_text_view.clear_text_for_update()                          # 清除上次显示的残留信息
        self.diff_web_view.load(QUrl(""))                                   # 清除上次显示的残留信息

        txt_file_path = file_path.split('.')[0] + ".txt"                    # 查找与选择图像同名的txt文件
        if os.path.exists(txt_file_path):                                   # 图像有对应的标签txt文件
            self.res_text_view.setHidden(True)                              # 隐藏自定义textview
            self.diff_web_view.setHidden(False)                             # 显示对比视图
            self.show_diff_flag = True                                      # 修改对比视图显示标志, 也即存在标签标志

            with open(txt_file_path, 'r', encoding='gbk') as f:             # gbk格式打开
                texts = f.readlines()
                for line in texts:
                    self.ori_label_list.append(line.strip('\n'))
            f.close()
        else:                                                               # 图像没有对应的标签txt文件
            self.res_text_view.setHidden(False)                             # 显示自定义textview
            self.diff_web_view.setHidden(True)                              # 隐藏对比视图
            self.show_diff_flag = False                                     # 修改对比视图显示标志

        self.start_flag = True                                              # 开始处理, 修改Start_Flag
        self.ori_image_path = file_path
        self.ori_image_View.setPixmap(QPixmap(file_path))                   # 先显示原图像
        self.locate_start_timer = time.perf_counter()                       # 定位计时器开始计时

        self.locate_time_label.setText("DBNet定位中,请等待...")
        self.rec_time_label.setText("")                                     # 状态栏label置空
        self.sim_ratio_label.setText("")
        self.ar_label.setText("")
        self.cr_label.setText("")

        if self.switch_button.state:                                        # True, 启用DBNet
            print("启用DBNet")
            self.dbnetThread = DBNetBackThread(self.ori_image_path)         # 初始化 DBNet 后台线程处理图片
            self.dbnetThread._signal.connect(self.update_dbnet_res_img)     # 设置 DBNet 后台线程回调函数
            self.dbnetThread.start()                                        # 启动DBNet后台线程
        else:                                                               # False, 启用形态学
            print("启用形态学")
            self.backThread = LocateBackThread([self.ori_image_path])       # 初始化 形态学 后台线程处理图片
            self.backThread._signal.connect(self.update_Res_ImageView)      # 设置 形态学 后台线程回调函数
            self.backThread.start()                                         # 启动形态学后台线程

    # 更新 DBNet 定位结果视图, qImg:(定位出文本行的图像, [文本行图像], [文本行图像位置])
    def update_dbnet_res_img(self, qImg):
        self.ori_image_View.setPixmap(QPixmap.fromImage(qImg[0]))                        # 更新定位出文本行的图像
        self.texts_rect = qImg[2]                                                        # 保存文本行图像位置
        self.locate_end_timer = time.perf_counter()                                      # 定位计时器结束计时
        duration = (self.locate_end_timer - self.locate_start_timer) * 1000              # 更新计时Label
        self.locate_time_label.setText("DBNet 定位时长: {:.2f} ms".format(duration))
        self.rec_time_label.setText("CRNN识别中,请等待...")

        # 识别定位出的文本行
        self.rec_start_timer = time.perf_counter()                                      # 识别计时器开始计时
        self.recogBackThread = RecogBackThread([qImg[1]])                               # 初始化识别后台线程处理图片
        self.recogBackThread._signal.connect(self.update_texts_in_textView)             # 设置后台线程回调函数
        self.recogBackThread.start()                                                    # 启动后台线程


    # 刷新形态学定位结果视图
    def update_Res_ImageView(self, qImg):
        self.res_image_list = qImg                                                       # [(定位出文本行的图像, [文本行图像], [文本行图像位置])]
        self.ori_image_View.setPixmap(QPixmap.fromImage(self.res_image_list[0][0]))      # 结果数组中只有一个元素(只选择一张图片定位)
        self.texts_rect = self.res_image_list[0][2]                                      # 保存文本行图像位置
        self.locate_end_timer = time.perf_counter()                                      # 定位计时器结束计时
        duration = (self.locate_end_timer - self.locate_start_timer) * 1000              # 更新计时Label
        self.locate_time_label.setText("形态学 定位时长: {:.2f} ms".format(duration))

        # 识别定位出的文本行
        self.rec_start_timer = time.perf_counter()                            # 识别计时器开始计时
        self.recogBackThread = RecogBackThread([self.res_image_list[0][1]])   # 初始化一个新的后台线程处理图片
        self.recogBackThread._signal.connect(self.update_texts_in_textView)   # 设置后台线程回调函数
        self.recogBackThread.start()                                          # 启动后台线程

    # 更新识别出的文字信息, texts: [[str1,str2,...], [str1, str2, ....]]
    def update_texts_in_textView(self, texts):
        self.start_flag = False                                               # 定位识别完成,修改当前状态
        self.rec_end_timer = time.perf_counter()                              # 识别计时器结束计时
        duration = (self.rec_end_timer - self.rec_start_timer) * 1000         # 更新计时Label
        self.rec_time_label.setText("识别时长: {:.2f} ms".format(duration))

        self.sim_ratio_label.setText("相似度计算中,请等待...")
        if self.show_diff_flag:                                                                         # 显示对比视图
            self.mid_circle_area.setHidden(False)                                                       # 显示放大按钮区域
            diff = difflib.HtmlDiff().make_file(self.ori_label_list, texts[0])                          #
            save_path = "/Users/soyou/Documents/EProjects/HWExplorer/diff.html"
            outfile = open(save_path, 'w')                                                              # TODO: 绝对路径修改
            outfile.write(diff)                                                                         # 保存html文件
            outfile.close()
            self.diff_web_view.load(QUrl.fromLocalFile(save_path))                                      # 显示对比视图
            seq = difflib.SequenceMatcher(None, '.'.join(self.ori_label_list), '.'.join(texts[0]))
            ratio = seq.ratio()
            self.sim_ratio_label.setText("相似度: {:.3f}".format(ratio))                                 # 设置文本相似度

            num, ar_num, cr_num = calculate_ar_cr('.'.join(self.ori_label_list), '.'.join(texts[0]))
            self.ar_label.setText("AR: {:.2f}".format(ar_num/num))                                      # 计算AR
            self.cr_label.setText("CR: {:.2f}".format(cr_num/num))                                      # 计算CR

        else:                                                                                           # 隐藏对比视图
            self.sim_ratio_label.setText(" ")                                                           # 文本相似度置空
            self.res_text_view.redraw_text_in_view(texts[0], self.texts_rect)                           # 自定义textview绘制文字信息

    # 显示全尺寸视图
    def show_full_size_view(self):
        self.show_area_widget.setHidden(True)
        self.full_size_web_view.setHidden(False)
        # TODO:  使用项目内相对路径
        self.full_size_web_view.load(QUrl.fromLocalFile("/Users/soyou/Documents/EProjects/HWExplorer/diff.html"))

    # 退出全尺寸视图模式
    def exit_full_size_view_mode(self):
        self.show_area_widget.setHidden(False)
        self.full_size_web_view.setHidden(True)
Example #32
0
class BrowserWindow(QtWidgets.QDialog):
    def __init__(self, vendor_dict, vendor_list):
        super(BrowserWindow, self).__init__()
        self.pd_dict = vendor_dict
        self.vendor_list = vendor_list
        self.onevendor_sum = []
        self.onevendor_daysum = []
        self.features = Features.Features(self.pd_dict)
        self.onevendor_daysum = self.features.filter_one_col_sum('公司名称', '总人天')
        self.onevendor_sum = self.features.filter_one_col_sum('公司名称', '付款金额')
        self.all_sum = self.features.get_one_col_sum('付款金额')
        self.all_manday = self.features.get_one_col_sum('总人天')
        self.url_string = ''
        self.initUI()
        self.msg = QtWidgets.QMessageBox()

    def initUI(self):
        self.setWindowTitle('数据中心')
        self.setGeometry(5, 30, 1920, 1080)
        self.tabWidget = QtWidgets.QTabWidget(self)
        self.tabWidget.setGeometry(QtCore.QRect(0, 0, 1900, 1000))
        self.tabWidget.setTabPosition(QtWidgets.QTabWidget.North)
        self.tabWidget.setTabShape(QtWidgets.QTabWidget.Rounded)
        self.tabWidget.setDocumentMode(False)
        self.tabWidget.setMovable(False)

        # Tab1
        self.tab = QtWidgets.QWidget()
        self.label_5 = QtWidgets.QLabel(self.tab)
        self.label_5.setGeometry(QtCore.QRect(0, 0, 100, 32))
        self.label_4 = QtWidgets.QLabel(self.tab)
        self.label_5.setGeometry(QtCore.QRect(0, 20, 200, 32))
        self.groupBox = {}
        self.label_groupBox = {}
        self.scrollArea = QtWidgets.QScrollArea(self.tab)
        self.scrollArea.setGeometry(QtCore.QRect(0, 50, 631, 800))

        self.scrollAreaWidgetContents = QtWidgets.QWidget()
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 600, 700))

        for i in range(len(self.vendor_list)):
            self.groupBox[i] = QtWidgets.QGroupBox(self.scrollAreaWidgetContents)
            self.groupBox[i].setGeometry(QtCore.QRect(0, 90 * i + 5, 500, 80))
            self.groupBox[i].setTitle(self.vendor_list[i])
            font = QtGui.QFont()
            font.setBold(True)
            font.setPointSize(10)
            self.groupBox[i].setFont(font)
            self.label_groupBox[i] = QtWidgets.QLabel(self.groupBox[i])
            self.label_groupBox[i].setText('总支出:%.2f元' % self.onevendor_sum[i][1])
            self.label_groupBox[i].setGeometry(QtCore.QRect(10, 20, 400, 40))
            font.setBold(False)
            font.setPointSize(8)
            self.label_groupBox[i].setFont(font)
            self.label_groupBox[i + 1] = QtWidgets.QLabel(self.groupBox[i])
            self.label_groupBox[i + 1].setText('总人天:%.1f' % self.onevendor_daysum[i][1])
            self.label_groupBox[i + 1].setGeometry(QtCore.QRect(10, 40, 400, 40))
            self.label_groupBox[i + 1].setFont(font)
        self.label_4.setText("总支出:%.2f元" % self.all_sum)
        self.label_5.setText("总人天:%.1f" % self.all_manday)
        self.scrollAreaWidgetContents.resize(600, 90 * len(self.vendor_list))
        self.scrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded)
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        self.tabWidget.addTab(self.tab, "")
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), "常规数据")
        # Tab2
        self.tab_2 = QtWidgets.QWidget()
        self.horizontalLayoutWidget_3 = QtWidgets.QWidget(self.tab_2)
        self.horizontalLayoutWidget_3.setGeometry(QtCore.QRect(0, 0, 1000, 41))
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout(self.horizontalLayoutWidget_3)
        self.horizontalLayout_3.setContentsMargins(0, 0, 0, 0)
        self.label_3 = QtWidgets.QLabel(self.horizontalLayoutWidget_3)
        self.label_3.setTextFormat(QtCore.Qt.AutoText)
        self.horizontalLayout_3.addWidget(self.label_3)
        self.label_2 = QtWidgets.QLabel(self.horizontalLayoutWidget_3)
        self.label_2.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
        self.horizontalLayout_3.addWidget(self.label_2)
        self.comboBox_01 = QtWidgets.QComboBox(self.horizontalLayoutWidget_3)
        self.horizontalLayout_3.addWidget(self.comboBox_01)
        # self.pushButton_insert = QtWidgets.QPushButton(self.horizontalLayoutWidget_3)
        # self.horizontalLayout_3.addWidget(self.pushButton_insert)
        # self.pushButton_insert.setText("插入")
        self.label = QtWidgets.QLabel(self.horizontalLayoutWidget_3)
        self.label.setAlignment(QtCore.Qt.AlignRight | QtCore.Qt.AlignTrailing | QtCore.Qt.AlignVCenter)
        self.horizontalLayout_3.addWidget(self.label)
        self.comboBox_02 = QtWidgets.QComboBox(self.horizontalLayoutWidget_3)
        self.horizontalLayout_3.addWidget(self.comboBox_02)
        self.checkBox = QtWidgets.QCheckBox(self.horizontalLayoutWidget_3)
        self.horizontalLayout_3.addWidget(self.checkBox)
        self.pushButton = QtWidgets.QPushButton(self.horizontalLayoutWidget_3)
        self.horizontalLayout_3.addWidget(self.pushButton)
        self.saveButton = QtWidgets.QPushButton(self.horizontalLayoutWidget_3)
        self.horizontalLayout_3.addWidget(self.saveButton)
        self.tabWidget.addTab(self.tab_2, "")
        self.tabWidget.setCurrentIndex(0)
        self.label_3.setText("柱状图:")
        self.label_2.setText("根据")
        self.label.setText("搜索:")
        self.checkBox.setText("饼图")
        self.pushButton.setText("OK")
        self.saveButton.setText("Save as")
        self.browser = QWebEngineView(self.tab_2)
        self.browser.setGeometry(QtCore.QRect(0, 50, 1500, 1080))

        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), "图表数据分析")
        item1 = ['公司名称', '游戏项目', '类型', '项目部门']
        self.comboBox_01.addItems(item1)
        item2 = ['付款金额', '不含税金额', '总人天']
        self.comboBox_02.addItems(item2)
        # self.pushButton_insert.clicked.connect(self.get_barlist)
        self.pushButton.clicked.connect(self.show_bar)
        self.saveButton.clicked.connect(self.save_file)

    # comboBox_01 公司名称   comboBox_01_02 钱    comboBox_02 项目
    # def get_barlist(self):
    #     self.vendor_name = self.comboBox_01.currentText()
    #     self.project_name = self.comboBox_02.currentText()
    #     # self.result = self.comboBox_01_02.currentText()
    #     self.get_res = self.features.get_project_sum(self.vendor_name, self.project_name, self.result)
    #     self.y_list.append([self.get_res[0], self.get_res[2]])
    #     self.msg.information(self.msg, '提示', '添加成功', self.msg.Ok)
    #     # print(self.y_list)

    def show_bar(self):
        # print(x)
        # print(self.x_list)
        # print(self.y_list)
        self.x_list = []
        self.y_list = []
        val01 = self.comboBox_01.currentText()
        val02 = self.comboBox_02.currentText()
        for i in self.features.filter_one_col_sum(val01, val02):
            self.y_list.append(i[1])
            self.x_list.append(i[0])
        if self.checkBox.isChecked():
            Features.create_pie(val01, self.features.filter_one_col_sum(val01, val02))
            self.url_string = Features.legal_url('pie')
        else:
            Features.create_bar(self.x_list, val01, self.y_list)
            self.url_string = Features.legal_url('bar')
        self.browser.load(QtCore.QUrl(self.url_string))

    def save_file(self):
        path, _ = QtWidgets.QFileDialog.getSaveFileName(None,
                                                        'SaveFile',
                                                        'E:\\Test\\',
                                                        'HTML (*.html)')
        if path != '':
            source_file = self.url_string[8:]
            Features.save_file(source_file, path)
            self.msg.information(self.msg, '提示', '保存完成', self.msg.Ok)