Example #1
0
class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(442, 824)
        Form.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
        Form.setWindowFlags(QtCore.Qt.CustomizeWindowHint)
    
        self.commandLinkButton = QtWidgets.QCommandLinkButton(Form)
        self.commandLinkButton.setGeometry(QtCore.QRect(300, 754, 142, 70))
        self.commandLinkButton.setObjectName("commandLinkButton")
        self.commandLinkButton.setStyleSheet("background-color: rgb(209, 175, 222);\n""color: rgb(64, 0, 64);")

        self.commandLinkButton1 = QtWidgets.QCommandLinkButton(Form)
        self.commandLinkButton1.setGeometry(QtCore.QRect(0, 754, 142, 70))
        self.commandLinkButton1.setObjectName("commandLinkButton")
        self.commandLinkButton1.setStyleSheet("background-color: rgb(209, 175, 222);\n""color: rgb(64, 0, 64);")

        self.commandLinkButton.clicked.connect(self.select)
        self.commandLinkButton1.clicked.connect(self.analy)

        
        
        
        self.combobox = QtWidgets.QComboBox(Form)
        self.combobox.setGeometry(QtCore.QRect(146, 754, 140, 35))
        self.combobox.addItems(["AQI散点","AQI热图","分时AQI"])
        #self.combobox.currentIndexChanged.connect(self.analy)
        self.combobox.show()
        
        
        self.combobox1 = QtWidgets.QComboBox(Form)
        self.combobox1.setGeometry(QtCore.QRect(146, 794, 140, 35))
        self.combobox1.addItems(["逃脱路线","推荐城市"])
        self.combobox1.show()
        
        
        self.webView = QWebEngineView(Form)
        self.webView.setGeometry(0,0,440,750)
        self.webView.load(QUrl("file:///D:/源代码/aqi.html"))
       
        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "逃离阴霾"))
        self.commandLinkButton.setText(_translate("Form", "\n获取AQI"))
        self.commandLinkButton1.setText(_translate("Form", "\n计划逃跑"))
    
    def analy(self,lastcity):
        if self.combobox1.currentText()==u"推荐城市":
            print('查看更多信息')
            self.best()
            
        if self.combobox1.currentText()==u"逃脱路线":
            print('逃脱')
            self.escape()

            #self.combobox.hide()
            #self.combobox.clear()
            
    def select(self):
        if self.combobox.currentText()==u"分时AQI":
            self.draw_city_aqi(nowTime)
        if self.combobox.currentText()==u"AQI散点":
            self.draw1(nowTime)
            #self.combobox.show()
        if self.combobox.currentText()==u"AQI热图":
            self.draw(nowTime)
        #if self.combobox1.currentText()==u"逃脱路线":
            
    #def draw2(self,time = None):
    def draw_city_aqi(self, time = None):
        #from opendatatools import aqi
        line = Line("长沙当日AQI",
                         width=425,
                         height=730)
        data_dict = {}
        city=local
        print("getting data for %s" % city)
        #df_aqi = aqi.get_daily_aqi_onecity(city)
        aqi_hour=pd.read_csv('daylocal.csv')
    
            #print(df_aqi)
            #print(aqi_hour)
        aqi_hour.set_index('time', inplace=True)
        aqi_hour.sort_index(ascending=True, inplace=True)
        if time is not None:
            aqi_hour = aqi_hour[aqi_hour.index <= time]
            
        data_dict[city] = aqi_hour
        axis_x = aqi_hour.index
        axis_y = aqi_hour['aqi']
        line.add("%s" % (city), axis_x, axis_y, mark_point=["max","min"])
        line.render('aqi.html')
        #return line

        self.webView.load(QUrl("file:///D:/源代码/aqi.html"))

       # self.webView.reload()
        self.webView.repaint()
        self.webView.update()
        
    def draw1(self,time = None):
        global local

        # some city cannot by process by echart
        echart_unsupported_city = [
        "菏泽市", "襄阳市", "恩施州", "湘西州","阿坝州", "延边州",
        "甘孜州", "凉山州", "黔西南州", "黔东南州", "黔南州", "普洱市", "楚雄州", "红河州",
        "文山州", "西双版纳州", "大理州", "德宏州", "怒江州", "迪庆州", "昌都市", "山南市",
        "林芝市", "临夏州", "甘南州", "海北州", "黄南州", "海南州", "果洛州", "玉树州", "海西州",
        "昌吉州", "博州", "克州", "伊犁哈萨克州"]
        if time is None and len(df_aqi) > 0:
            time = df_aqi['time'][0]
        data = []
        for index, row in df_aqi.iterrows():
            city = row['city']
            aqi = row['aqi']
            if city=='长沙市':
                print(city)
                localAQI=aqi
            if city in echart_unsupported_city:
                continue
            data.append( (city, aqi) )
        
        #lcaqi=''.join(localAQI)
        #print(lcaqi)
        if localAQI<70:
            geo = Geo("全国最新主要城市空气质量(AQI) \n 当前城市:长沙 AQI:%s \n \n您在的城市不错,不开心的话,也出去走走吧" % localAQI, "数据来源于环保部网站",
                     title_color="#fff",
                     title_pos="center", width=425,
                     height=730, background_color='#404a59')
        else:
            geo = Geo("全国最新主要城市空气质量(AQI) \n 当前城市:长沙 AQI:%s \n \n环境很差!!出去走走吧,已经为您规划路线" % localAQI, "数据来源于环保部网站",
                     title_color="#fff",
                     title_pos="center", width=425,
                     height=730, background_color='#404a59')
                 
        attr, value = geo.cast(data)
        
        geo.add("", attr, value, visual_range=[0, 150],
            maptype='china',visual_text_color="#fff",
            symbol_size=10, is_visualmap=True,
            label_formatter='{b}', # 指定 label 只显示城市名
            tooltip_formatter='{c}', # 格式:经度、纬度、值
            label_emphasis_textsize=15, # 指定标签选中高亮时字体大小
            label_emphasis_pos='right' # 指定标签选中高亮时字体位置
            )
        #print(data)
        geo.render('aqi.html')
        self.webView.load(QUrl("file:///D:/源代码/aqi.html"))

        #self.webView.reload()
        self.webView.repaint()
        self.webView.update()
        #return geo        
    def draw(self,time = None):
        
        # some city cannot by process by echart
        echart_unsupported_city = [
        "菏泽市", "襄阳市", "恩施州", "湘西州","阿坝州", "延边州",
        "甘孜州", "凉山州", "黔西南州", "黔东南州", "黔南州", "普洱市", "楚雄州", "红河州",
        "文山州", "西双版纳州", "大理州", "德宏州", "怒江州", "迪庆州", "昌都市", "山南市",
        "林芝市", "临夏州", "甘南州", "海北州", "黄南州", "海南州", "果洛州", "玉树州", "海西州",
        "昌吉州", "博州", "克州", "伊犁哈萨克州"]
        if time is None and len(df_aqi) > 0:
            time = df_aqi['time'][0]
        data = []
        for index, row in df_aqi.iterrows():
            city = row['city']
            aqi = row['aqi']
            if city=='长沙市':
                print(city)
                localAQI=aqi
            if city in echart_unsupported_city:
                continue
            data.append( (city, aqi) )
            
            
        if localAQI<70:
            geo = Geo("全国最新主要城市空气质量(AQI) \n 当前城市:长沙 AQI:%s \n \n您在的城市不错,不开心的话,也出去走走吧" % localAQI, "数据来源于环保部网站",
                     title_color="#fff",
                     title_pos="center", width=425,
                     height=730, background_color='#404a59')
        else:
            
            geo = Geo("全国最新主要城市空气质量(AQI) \n 当前城市:长沙 AQI:%s \n \n环境很差!!出去走走吧,已经为您规划路线" % localAQI, "数据来源于环保部网站",
                     title_color="#fff",
                     title_pos="center", width=425,
                     height=730, background_color='#404a59')
                 
        attr, value = geo.cast(data)
        geo.add("", attr, value, type="heatmap", is_visualmap=True, visual_range=[0, 600],
        visual_text_color='#fff')
        #print(data)
        geo.render('aqi.html')
        self.webView.load(QUrl("file:///D:/源代码/aqi.html"))

        #self.webView.reload()
        self.webView.repaint()
        self.webView.update()
        #return geo
        
    def escape(self):
        echart_unsupported_city = [
        "菏泽市", "襄阳市", "恩施州", "湘西州","阿坝州", "延边州",
        "甘孜州", "凉山州", "黔西南州", "黔东南州", "黔南州", "普洱市", "楚雄州", "红河州",
        "文山州", "西双版纳州", "大理州", "德宏州", "怒江州", "迪庆州", "昌都市", "山南市",
        "林芝市", "临夏州", "甘南州", "海北州", "黄南州", "海南州", "果洛州", "玉树州", "海西州",
        "昌吉州", "博州", "克州", "伊犁哈萨克州"]

        data = []
        
        for index, row in df_aqi.iterrows():
            city = row['city']
            aqi = row['aqi']
            if city=='长沙市':
                print(city)
                localAQI=aqi
            if city in echart_unsupported_city:
                continue
        for index, row in df_aqi.iterrows():
            city = row['city']
            aqi = row['aqi']
            if city in echart_unsupported_city:
                continue
            if aqi < localAQI and aqi<20 :
                data.append( ['长沙',city] )
                global lastcity
                lastcity=city
                                
        style = Style(
            title_top="#fff",
            title_pos = "center",
            title_color="#fff",
            width=425,
            height=730,
            background_color="#404a59"
        )
        
        style_geo = style.add(
            is_label_show=True,
            line_curve=0.2,#线条曲度
            line_opacity=0.6,
            legend_text_color="#fff",#图例文字颜色
            legend_pos="right",#图例位置
            geo_effect_symbol="plane",#特效形状
            geo_effect_symbolsize=15,#特效大小
            label_color=['#a6c84c', '#ffa022', '#46bee9'],
            label_pos="right",
            label_formatter="{b}",#//标签内容格式器
            label_text_color="#fff",
        )
        print(data)
        print(lastcity)
        geolines = GeoLines("逃离路线", **style.init_style)
        geolines.add("出发", data, **style_geo)
        geolines.render('aqi.html')
        
        self.webView.load(QUrl("file:///D:/源代码/aqi.html"))
        #self.webView.reload()
        self.webView.repaint()
        self.webView.update()
    
    def best(self):
        global lastcity
        url='https://m.baidu.com/s?from=1019146b&bd_page_type=1&word='+lastcity
        print(url)
        self.webView.load(QUrl(url))
        #self.webView.reload()

        self.webView.repaint()
        self.webView.update()
Example #2
0
class ZhuNote(QWidget):
    html_hi = '<html> <body> <p> HTML Viewer </p> </body> </html>'
    html_no = '<html> <body> <p> No HTML </p> </body> </html>'

    def __init__(self, path=None):
        QWidget.__init__(self)
        self.setPath(path)
        self.initUi()
        self.setFont()
        self.loadMaster()

    def setPath(self, path):
        if path is None:
            self.path = os.getcwd()
        else:
            self.path = path
        print('Working directory:', self.path)

    def initUi(self):
        print('Initializing GUI...')
        w, h = 1000, 1000

        self.find = ZhuNoteFind(self)  # self as parent
        self.tree = ZhuNoteTree()
        self.form = ZhuNoteForm(self.path)
        self.wbrs = QWebEngineView()

        splitter1 = QSplitter(Qt.Horizontal)
        splitter1.addWidget(self.form)
        splitter1.addWidget(self.wbrs)
        splitter1.setSizes([w / 2, w / 2])

        splitter = QSplitter(Qt.Vertical)
        splitter.addWidget(self.tree)
        splitter.addWidget(splitter1)
        splitter.setStretchFactor(0, 1)
        splitter.setStretchFactor(1, 2)

        vbox = QVBoxLayout()
        vbox.addWidget(self.find)
        vbox.addWidget(splitter)
        self.setLayout(vbox)

        self.wbrs.setHtml(self.html_hi)

        self.tree.sigViewItem.connect(self.form.viewDict)
        self.tree.sigViewItem.connect(self.viewHtml)
        self.find.sigClear.connect(self.clear)
        self.find.sigString.connect(self.search)
        self.find.sigUpdateMaster.connect(self.updateMaster)
        self.find.sigFont.connect(self.setFont)

        self.setWindowTitle('Main - ZhuNote')
        #self.setGeometry(x, y, w, h)
        #self.move(x, y)
        self.resize(w, h)
        #self.show()
        #self.tree.show()
        #self.form.show()

        styleName = 'Cleanlooks'  # QStyleFactory.keys()
        # ['Windows', 'Motif', 'CDE', 'Plastique', 'GTK+', 'Cleanlooks']
        QApplication.setStyle(QStyleFactory.create(styleName))

        self.find.txtSearch.setFocus()  # not work yet

        self.actExit = QAction('Exit', self)
        self.actExit.setShortcut('Ctrl+Q')
        self.actExit.triggered.connect(self.closeAllWindows)
        self.addAction(self.actExit)

    def viewHtml(self, dictNote):
        htmlfn = dictNote['HTML']
        fn = os.path.join(self.path, htmlfn)
        if os.path.isfile(fn):
            url = QUrl.fromLocalFile(fn)
            self.wbrs.load(url)
        else:
            #self.wbrs.setHtml('') # blank page
            self.wbrs.setHtml(self.html_no)

    def setFont(self, font=None):
        if font is None:
            font = QFont()  # default font
            font.setFamily('Courier New')
            font.setPointSize(11)
        self.find.txtSearch.setFont(font)
        self.tree.setFont(font)
        self.form.setFont(font)

    def closeAllWindows(self):
        app = QApplication.instance()
        app.closeAllWindows()

    def loadMaster(self):
        fn = 'notemaster.pickle'
        self.masterfn = os.path.join(self.path, fn)
        if os.path.isfile(self.masterfn):
            print('Loading database:', self.masterfn)
            with open(self.masterfn, 'rb') as f:
                self.dod = pickle.load(f)

    def clear(self):
        self.find.txtSearch.clear()
        self.tree.clear()
        self.form.clear()
        self.wbrs.setHtml(self.html_hi)

    def search(self, string):
        self.tree.clear()  # clear tree before a new search
        self.tree.lod = []  # used in tree class
        # break string to words by space
        stringLC = string.lower()
        words = stringLC.split()
        for key in self.dod:
            dictNote = self.dod[key]
            keyword = dictNote['Keyword']
            title = dictNote['Title']
            sstring = title + ' ' + keyword  # string to be searched
            sstring = sstring.lower()
            if any(word in sstring for word in words):  # weak search
                #if all(word in kw for word in words): # strong search
                self.tree.addItem(dictNote)
        self.tree.sortItems(0, Qt.AscendingOrder)

    def updateMaster(self):
        """
        i self.path : string, path
        o file : write pickle file (list of dictionaries)
        In path, each pkl file contains one dictionary.
        This method merges all the dictionaries to a list for search.
        """
        print('Number of entries old =', len(self.dod))
        mt_master = os.path.getmtime(self.masterfn)

        for fn in os.listdir(self.path):
            if fn.endswith(".pkl"):
                ffn = os.path.join(self.path, fn)
                mt_entry = os.path.getmtime(ffn)
                if mt_entry >= mt_master:
                    #                if True:
                    with open(ffn, 'rb') as f:
                        dictNote = pickle.load(f)
                    title = dictNote['Title']
                    if title in self.dod:
                        print("Modify existing entry:", ffn)
                    else:
                        print("Add new entry:", ffn)
                    self.dod[title] = dictNote

        with open(self.masterfn, 'wb') as f:
            pickle.dump(self.dod, f, -1)
        print('Merged file is', self.masterfn)
        print('Number of entries new =', len(self.dod))
Example #3
0
class Playground(QtWidgets.QSplitter):
    def __init__(self,
                 img_path,
                 no_docs,
                 disable_info_widgets,
                 parent=None,
                 *args,
                 **kwargs):
        super().__init__(parent=parent, *args, **kwargs)
        self.img_path = str(img_path)
        self.show_docs = not no_docs
        self.show_info_widgets = not disable_info_widgets
        self.docview = None
        self.pipe_stack = None
        self.added_pipes = {}

        self.setOrientation(Qt.Orientation.Horizontal)
        self._build_layout()
        # TODO: Distribution based on screen size
        self.setSizes([0.1 * 800, 0.5 * 800, 0.4 * 800])

    def _build_layout(self):
        """Build the main layout"""
        tlist = TransformList()
        # TODO: Use some max based on largest object in list size
        tlist.setMinimumWidth(150)
        tlist.setMaximumWidth(200)
        self.addWidget(tlist)

        # Connect change handlers for the transform list
        tlist.builtin_list.selectionModel().currentChanged.connect(
            self._handle_changed)
        tlist.builtin_list.selectionModel().currentChanged.connect(
            self._reload_pipeline)

        # Document Viewer
        if self.show_docs:
            self.docview = QWebEngineView(self)
            self.addWidget(self.docview)

        # PipeWindow
        self.pipe_stack = QtWidgets.QStackedWidget(parent=self)
        self.addWidget(self.pipe_stack)

    @Slot(QModelIndex, QModelIndex)
    def _reload_pipeline(self, current, previous):
        """Creates or Loads selected Transform into PipeWindow"""
        model = current.model()
        transform = model.items[current.row()]
        tname = transform.__name__

        # Add or select a PipeWindow from the stack
        if self.pipe_stack.currentIndex(
        ) == -1 or tname not in self.added_pipes:
            window = get_transform_window(transform, self.img_path)
            pipe = Pipeline(window)
            pipe_win = PipeWindow(window,
                                  parent=self,
                                  show_info_widget=self.show_info_widgets)
            img, _ = pipe.run_pipeline()
            pipe_win.update_image(img, pipe_win.viewer)
            self.pipe_stack.addWidget(pipe_win)
            self.added_pipes[tname] = self.pipe_stack.count() - 1
            self.pipe_stack.setCurrentIndex(self.added_pipes[tname])
        else:
            self.pipe_stack.setCurrentIndex(self.added_pipes[tname])

    @Slot(QModelIndex, QModelIndex)
    def _handle_changed(self, current, previous):
        """Reloads documentation for selected Transform"""
        if not self.show_docs:
            return
        model = current.model()
        transform = model.items[current.row()]
        doc_fname = RENDERED_DIR.joinpath(transform.get_doc_filename())
        url = QUrl.fromLocalFile(str(doc_fname))
        self.docview.load(url)
        self.docview.show()