def createSummaryBar(self): # self.dp.dfinal series = QPieSeries() labelfont = QFont() labelfont.setPixelSize(11) try: series.append("Linked", len(self.linked.index)) series.append("Unlinked", len(self.unlinked.index)) # slices = QPieSlice() slices1 = series.slices()[1] slices1.setExploded() slices1.setLabelVisible() slices1.setPen(QPen(QColor(0x57B1FD), 2)) slices1.setBrush(QBrush(QColor(0xfdb157))) slices1.setLabelPosition(QPieSlice.LabelOutside) slices1.setLabel( ("{0} {1:.2f}%").format("Unlinked", 100 * slices1.percentage())) slices1.setLabelFont(labelfont) # slices.setPen(QPen(Qt.darkGreen, 2)) # slices.setBrush(QBrush(QColor(0xfdb157))) except AttributeError: self.statusbar.showMessage('Data not ready') series.append("Total", 1) slices = series.slices()[0] slices.setBrush(QBrush(QColor(0x57B1FD))) # slices.setLabel(("%1%").format(100*slices.percentage(), 0, 'f', 1)) # slices.setLabelPosition(QPieSlice.LabelInsideHorizontal) if len(series.slices() ) == 2: # display "linked" label only at data was processed slices.setLabelVisible() slices.setLabel(("{0} {1:.2f}%").format("Linked", 100 * slices.percentage())) slices.setLabelFont(labelfont) chart = QChart() font = QFont() font.setPixelSize(18) chart.setTitleFont(font) chart.addSeries(series) chart.setAnimationOptions(QChart.SeriesAnimations) chart.setTitle("Total") chart.legend().hide() chartView = QChartView(chart) chartView.setRenderHint(QPainter.Antialiasing) return chartView
def createUnlinkedBar(self): pushed_bin = 0 slipping_bin = 0 others = 0 try: total_bins = self.total_bins scanner_linked_rfid = self.scanner_linked_rfid unlinked_bins = total_bins - scanner_linked_rfid slipping_bin = len(self.slipping.index) pushed_bin = len(self.pushed.index) others = unlinked_bins-pushed_bin-slipping_bin except AttributeError: self.statusbar.showMessage('Data not ready') series = QPieSeries() series.setHoleSize(0.35) series.append("Pushed", pushed_bin) series.append("Slipping", slipping_bin) series.append("Others", others) slices = series.slices()[0] slices.setLabelVisible() slices.setLabel("{0} {1:.2f}".format("Pushed", 100*slices.percentage())) slices1 = series.slices()[1] slices1.setLabelVisible() slices1.setLabel("{0} {1:.2f}".format("Slipping", 100*slices1.percentage())) # set exploded slice if pushed_bin > slipping_bin: slices.setExploded() else: slices1.setExploded() slices2 = series.slices()[2] slices2.setLabelVisible() slices2.setLabel("{0} {1:.2f}".format("Others", 100*slices2.percentage())) chart = QChart() chart.setTheme(QChart.ChartThemeBlueCerulean) chart.legend().hide() font = QFont() font.setPixelSize(16) chart.setTitleFont(font) chart.setTitle("Unlinked Details") chart.addSeries(series) chart.setAnimationOptions(QChart.SeriesAnimations) chartView = QChartView(chart) chartView.setRenderHint(QPainter.Antialiasing) return chartView
class Chart(QWidget): def __init__(self, chartKey, data, frame, parent=None): super(Chart, self).__init__(parent) self.frame = frame self.data = data self.create_chart(chartKey) def create_chart(self, chartKey): self.series = QPieSeries() self.series.setHoleSize(0.35) self.chart = QChart() #Add series to the chart self.addSeries(chartKey) # for the background and title self.chart.setAnimationOptions(QChart.SeriesAnimations) self.chart.setTitle("Code Size Visualizer") self.chart.legend().setVisible(True) self.chart.legend().setAlignment(Qt.AlignRight) self.chart.setTheme(QChart.ChartThemeBlueCerulean) self.chartview = QChartView(self.chart) self.chartview.setRenderHint(QPainter.Antialiasing) #each section of the pie chart def addSeries(self, key): self.chart.removeAllSeries() self.series = QPieSeries() self.series.setHoleSize(0.35) #Show chartview only if the content length is less than 6. Otherwise show a table view if len(self.data[key]) < 6: #print('length',self.data, key) for key, value in self.data[key].items(): print('key, value', key, value) slice_ = QPieSlice(str(key), value) self.series.append(slice_) self.series.setLabelsVisible() self.series.setLabelsPosition(QPieSlice.LabelInsideHorizontal) for slice in self.series.slices(): #slice.setLabel(slice.label()) slice.setLabel(slice.label() + ' - ' + str(slice.value()) + ' B ') self.chart.addSeries(self.series) self.frame.frame.hide() self.chart.show() else: self.table = TableView(self.data[key], len(self.data[key]), 1) if self.frame.ly.count() > 0: self.frame.ly.itemAt(0).widget().setParent(None) self.frame.ly.addWidget(self.table) self.frame.frame.show() self.chart.hide()
def set_slice(self, pie_series: QPieSeries, mark_data) -> QPieSeries: for i in range(len(mark_data)): slice_ = pie_series.slices()[i] # 地道饼图的某一个元素切片 slice_.setLabelVisible() # 设置各区域文本标签 slice_.setPen(QPen(Qt.darkGreen, 0)) # 设置画笔类型——边界线颜色 slice_.setBrush(mark_data[i][2]) # 设置笔刷——区域颜色 return pie_series
def afterDelayPieChart(self): series = QPieSeries() labelfont = QFont() labelfont.setPixelSize(11) total_running_after_delay, total_stopped_after_delay = [], [] try: total_running_after_delay = self.tm.total_running_after_delay total_stopped_after_delay = self.tm.total_stopped_after_delay # slices.setPen(QPen(Qt.darkGreen, 2)) # slices.setBrush(QBrush(QColor(0xfdb157))) except AttributeError: self.statusbar.showMessage('Data not ready') series.append("Run", sum(total_running_after_delay)) series.append("Stop", sum(total_stopped_after_delay)) # slices = QPieSlice() slices = series.slices()[0] # Run time slice slices.setBrush(QBrush(QColor(0x57B1FD))) # Blue slices.setLabelVisible() # Set label visible slices.setLabel(("{0} {1:.2f}%").format("Run time", 100*slices.percentage())) # Set percentage slices.setLabelFont(labelfont) # Set label font slices1 = series.slices()[1] # Stop time slice slices1.setExploded() # Set stop slice exploded slices1.setLabelVisible() # Set label visible slices1.setPen(QPen(QColor(0x57B1FD), 2)) # Blue slices1.setBrush(QBrush(QColor(0xA6E22E))) # Orange # slices1.setLabelPosition(QPieSlice.LabelOutside) # Set label outside slices1.setLabel(("{0} {1:.2f}%").format("Stop time", 100*slices1.percentage())) # Set percentage slices1.setLabelFont(labelfont) # Set label font chart = QChart() font = QFont() font.setPixelSize(18) chart.setTitleFont(font) chart.addSeries(series) chart.setAnimationOptions(QChart.SeriesAnimations) chart.setTitle("Total Time (after)") chart.legend().hide() chartView = QChartView(chart) chartView.setRenderHint(QPainter.Antialiasing) return chartView
def beforeDelayPieChart(self): series = QPieSeries() labelfont = QFont() labelfont.setPixelSize(11) total_running_time, total_stopped_time = [], [] try: total_running_time = self.tm.total_running_time total_stopped_time = self.tm.total_stopped_time # slices.setPen(QPen(Qt.darkGreen, 2)) # slices.setBrush(QBrush(QColor(0xfdb157))) except AttributeError: self.statusbar.showMessage('Data not ready') series.append("Run", sum(total_running_time)) series.append("Stop", sum(total_stopped_time)) slices = series.slices()[0] slices.setBrush(QBrush(QColor(0x57B1FD))) slices.setLabelVisible() slices.setLabel(("{0} {1:.2f}%").format("Run Time", 100*slices.percentage())) slices.setLabelFont(labelfont) slices1 = series.slices()[1] slices1.setExploded() slices1.setLabelVisible() slices1.setPen(QPen(QColor(0x57B1FD), 2)) slices1.setBrush(QBrush(QColor(0xfdb157))) slices1.setLabel(("{0} {1:.2f}%").format("Stop Time", 100*slices1.percentage())) slices1.setLabelFont(labelfont) chart = QChart() font = QFont() font.setPixelSize(18) chart.setTitleFont(font) chart.addSeries(series) chart.setAnimationOptions(QChart.SeriesAnimations) chart.setTitle("Total Time (before)") chart.legend().hide() chartView = QChartView(chart) chartView.setRenderHint(QPainter.Antialiasing) return chartView
def createSummaryBar(self): series = QPieSeries() labelfont = QFont() labelfont.setPixelSize(11) linked_bag, unlinked_bag = 0, 0 try: linked_bag = self.scanner_linked_rfid unlinked_bag = self.total_bins - linked_bag except AttributeError: self.statusbar.showMessage('Data not ready') series.append("Linked", linked_bag) series.append("Unlinked", unlinked_bag) slices = series.slices()[0] slices.setBrush(QBrush(QColor(0x57B1FD))) slices.setLabelVisible() slices.setLabel(("{0} {1:.2f}%").format("Linked", 100*slices.percentage())) slices.setLabelFont(labelfont) slices1 = series.slices()[1] slices1.setExploded() slices1.setLabelVisible() slices1.setPen(QPen(QColor(0x57B1FD), 2)) slices1.setBrush(QBrush(QColor(0xfdb157))) slices1.setLabel(("{0} {1:.2f}%").format("Unlinked", 100*slices1.percentage())) slices1.setLabelFont(labelfont) chart = QChart() chart.setTheme(QChart.ChartThemeHighContrast) font = QFont() font.setPixelSize(16) chart.setTitleFont(font) chart.addSeries(series) chart.setAnimationOptions(QChart.SeriesAnimations) chart.setTitle("Total") chart.legend().hide() chartView = QChartView(chart) chartView.setRenderHint(QPainter.Antialiasing) return chartView
def drawChart(self, mui): series = QPieSeries() series.append("Main", mui.keyfunc.mainActivityFrame) series.append("Key", mui.keyfunc.keyActivityFrame) slice1 = series.slices()[0] #slice1.setExploded() slice1.setLabelVisible() slice1.setPen(QPen(QColor(40, 100, 240, 250), 2)) slice1.setBrush(QColor(40, 100, 240, 200)) slice2 = series.slices()[1] slice2.setLabelVisible() slice2.setPen(QPen(QColor(20, 150, 240, 250), 2)) slice2.setBrush(QColor(20, 150, 240, 200)) chart = QChart() chart.addSeries(series) #chart.setTitle("Activity Details") #chart.legend().hide() self.chartView.setChart(chart)
class DonutBreakdownChart(QChart): def __init__(self, parent=None): super(DonutBreakdownChart, self).__init__(parent) self.mainSeries = QPieSeries() self.mainSeries.setPieSize(0.7) self.addSeries(self.mainSeries) def addBreakdownSeries(self, series, color): # Add breakdown series as a slice to center pie. slice = self.mainSeries.append(series.name(), series.sum()) # Customize the slice. slice.setBrush(color) slice.setLabelVisible() slice.setLabelColor(Qt.white) slice.setLabelPosition(QPieSlice.LabelInsideHorizontal) # Position and customize the breakdown series. series.setPieSize(0.8) series.setHoleSize(0.7) series.setLabelsVisible() color = QColor(color) for slice in series.slices(): color = color.lighter(115) slice.setBrush(color) slice.setLabelFont(QFont("Arial", 8)) # Add the series to the chart. self.addSeries(series) # Recalculate breakdown donut segments. self.recalculateAngles() def recalculateAngles(self): angle = 0.0 for slice in self.mainSeries.slices(): series = self.find(slice.label()) if series is not None: series.setPieStartAngle(angle) angle += slice.percentage() * 360.0 series.setPieEndAngle(angle) def find(self, seriesName): for series in self.series(): if isinstance(series, QPieSeries) and series.name() == seriesName: return series return None
def create_chart(self): self.chart.setTitle( 'Grafiek aantal externe werken per status - opnameweek ' + jrwk) font = QFont("Sans Serif", 10) font.setWeight(QFont.Bold) self.chart.setTitleFont(font) series = QPieSeries() slice_ = QPieSlice() series.setUseOpenGL(enable=True) series.append('Status A = ' + str(rpr[0][2]), rpr[0][2]) series.append('Status B = ' + str(rpr[1][2]), rpr[1][2]) series.append('Status C = ' + str(rpr[2][2]), rpr[2][2]) series.append('Status D = ' + str(rpr[3][2]), rpr[3][2]) series.append('Status E = ' + str(rpr[4][2]), rpr[4][2]) series.append('Status F = ' + str(rpr[5][2]), rpr[5][2]) series.append('Status G = ' + str(rpr[6][2]), rpr[6][2]) series.append('Status H = ' + str(rpr[7][2]), rpr[7][2]) for i, slice_ in enumerate(series.slices()): slice_.setLabelVisible() #slice_.setLabelPosition(3) if i == 0: slice_.setPen(QPen(Qt.black, 2)) slice_.setBrush(Qt.green) elif i == 1: slice_.setPen(QPen(Qt.black, 2)) slice_.setBrush(Qt.red) elif i == 2: slice_.setExploded() slice_.setPen(QPen(Qt.black, 2)) slice_.setBrush(Qt.yellow) elif i == 3: slice_.setPen(QPen(Qt.black, 2)) slice_.setBrush(Qt.magenta) elif i == 4: slice_.setPen(QPen(Qt.black, 2)) slice_.setBrush(Qt.cyan) elif i == 5: slice_.setPen(QPen(Qt.black, 2)) slice_.setBrush(Qt.blue) elif i == 6: slice_.setPen(QPen(Qt.black, 2)) slice_.setBrush(Qt.darkYellow) elif i == 7: slice_.setPen(QPen(Qt.black, 2)) slice_.setBrush(Qt.darkRed) self.chart.addSeries(series)
def make_cake( self ): score_1 = self.players[ 0 ].score score_2 = self.players[ 1 ].score series = QPieSeries() free_score = 120 - score_1 - score_2 series.append( f"{free_score}", free_score ) series.append( f"{score_1}", score_1 ) series.append( f"{score_2}", score_2 ) series.setPieStartAngle( 3 * score_2 ) series.setPieEndAngle( 3 * score_2 + 360 ) slices = series.slices() for slice in slices: slice.setLabelVisible( True ) if slice.angleSpan() < 45: slice.setLabelPosition( QPieSlice.LabelPosition.LabelInsideNormal ) elif slice.angleSpan() < 90: slice.setLabelPosition( QPieSlice.LabelPosition.LabelInsideTangential ) else: slice.setLabelPosition( QPieSlice.LabelPosition.LabelInsideHorizontal ) slice.setLabelColor( QColor( "#00000" ) ) slice.setLabelFont( QFont( "Fira Sans", 60, weight=QFont.Weight.Black ) ) slice.setBorderWidth( 0 ) slices[ 0 ].setLabelPosition( QPieSlice.LabelPosition.LabelInsideHorizontal ) if score_1 < 10: slices[ 1 ].setLabelFont( QFont( "Fira Sans", score_1 * 6, weight=QFont.Weight.Black ) ) if score_2 < 10: slices[ 2 ].setLabelFont( QFont( "Fira Sans", score_2 * 6, weight=QFont.Weight.Black ) ) slices[ 0 ].setLabelColor( QColor( "#FFFFFF" ) ) slices[ 0 ].setColor( remaining_points_color ) slices[ 1 ].setColor( player_1.color ) slices[ 2 ].setColor( player_2.color ) chart = QChart() chart.legend().hide() chart.addSeries( series ) chart.createDefaultAxes() chart.setBackgroundVisible( False ) chart.setContentsMargins( -120, -120, -120, -120 ) chart.layout().setContentsMargins( 0, 0, 0, 0 ) chart_view = QChartView( chart ) chart_view.setRenderHint( QPainter.Antialiasing ) return chart_view
def update_diagram(self): year = self.date_edit.get_year() month = self.date_edit.get_month() date_format = f"WHERE strftime(\"%Y\",DATE) = \"{year}\" AND strftime(\"%m\",DATE) = \"{month:02}\"" series = QPieSeries() for item in self.db.get_sum_by_category(date_format, self.type_inout): series.append(item[1], item[0]) for slice in series.slices(): slice.setLabel( slice.label() + ", " + f"{slice.value()}₽" + f" ({round(slice.value() / (series.sum() / 100))}%)") series.clicked.connect(self.pressed) self.chart.removeAllSeries() self.chart.addSeries(series) self.chart.setTitle("Доходы" if self.type_inout else "Расходы")
class AccountPieChart(QChartView): """ Chart that displays certaing accounts with their respective balance on a Pie Chart. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.series = QPieSeries() self.chart = QChart() self.chart.setTheme(QChart.ChartThemeDark) self.chart.legend().hide() self.chart.addSeries(self.series) self.chart.createDefaultAxes() self.chart.setAnimationOptions(QChart.SeriesAnimations) self.chart.setBackgroundBrush(QBrush(QColor('#19232d'))) self.chart.setTitle("") self.chart.setTitleBrush(QBrush(QColor('white'))) self.chart.legend().setAlignment(Qt.AlignBottom) self.chart.legend().setLabelColor(QColor('white')) self.setChart(self.chart) self.setRenderHint(QPainter.Antialiasing) self.setStyleSheet("border: 0px") # self.setMinimumWidth(300) def updateWithToken(self, token): """ Updates series with all accounts that have a certain token """ entries_with_token = cbalances.get_entries_with_token(token) self.series.clear() for entry in entries_with_token: account = entry[0] amount = entry[2] self.series.append(account, amount) self.showSliceLabels(token) def allMode(self): """Updates series with all accounts""" self.series.clear() data = cbalances.get_all_accounts_with_amount() for d in data: account = d[0] balance = d[1] self.series.append(account, balance) self.showSliceLabels("btc") self.hideLittleSlices() def showSliceLabels(self, token): """ Formats the Slices so that they show the percentage """ for slce in self.series.slices(): slce.setLabel("{} {}% ({})".format( slce.label(), int(100*slce.percentage()), str(prices.to_btc(token, slce.value())) + " BTC")) slce.setLabelPosition(QPieSlice.LabelInsideNormal) # slce.setLabelPosition(QPieSlice.LabelOutside) slce.setLabelColor(QColor('white')) slce.setLabelVisible(True) self.hideLittleSlices() def selectSlice(self, account): """ Explodes a certaing slice that corresponds to an account """ for slce in self.series.slices(): if account in slce.label(): # Explode slice slce.setExploded(True) font = QFont() font.setBold(True) font.setUnderline(True) slce.setLabelFont(font) slce.setLabelPosition(QPieSlice.LabelOutside) else: slce.setExploded(False) slce.setLabelFont(QFont()) # slce.setLabelPosition(QPieSlice.LabelInsideTangential) slce.setLabelPosition(QPieSlice.LabelInsideNormal) self.hideLittleSlices(selected=account) def hideLittleSlices(self, selected=''): """ If a slice is not big enough for the label to be properly seen, the label gets hidden """ for slce in self.series.slices(): if slce.angleSpan() < 5 and slce.label().split(' ')[0] != selected: # Slice too little to show, and it's not selected slce.setLabelVisible(False) else: slce.setLabelVisible(True)
class StatisticsView(QWidget): def __init__(self, parent): super().__init__(parent) self.ui = Ui_statistics_window() self.ui.setupUi(self) self.genre_series = QPieSeries() self.filmDirector_series = QPieSeries() self.status_series = QPieSeries() self.createChart('Movie percentages genre', self.genre_series) self.createChart('Movie percentages film director', self.filmDirector_series) self.createChart('Movie percentages status', self.status_series) self.show() def getValues(self): movies = movie_session.query(Movie).count() filmDirectors = movie_session.query(Film_director).count() genres = movie_session.query(Genre).count() self.ui.moviesCounter_label.setText(str(movies)) self.ui.filmDirectorsCounter_label.setText(str(filmDirectors)) self.ui.genresCounter_label.setText(str(genres)) def createChart(self, title, series): chart = QChart() chart.addSeries(series) chart.setAnimationOptions(QChart.SeriesAnimations) chart.setTitle(title) #sslice.setLabel("{:.1f}%".format(100 * slice.percentage())) chartview = QChartView(chart) chartview.setRenderHint(QPainter.Antialiasing) #setChart(chartview) self.ui.pieChart_container.addWidget(chartview) def updateValues(self): try: counter_movies = movie_session.query(Movie).count() genres = movie_session.query(Genre).all() self.genre_series.clear() for genre in genres: genre_movies = movie_session.query(Movie).filter_by(genre_id=genre.id).count() self.genre_series.append(genre.name, genre_movies/counter_movies) for i in range(len(self.genre_series)): slice = QPieSlice() slice = self.genre_series.slices()[i] slice.setLabelVisible(True) film_directors = movie_session.query(Film_director).all() self.filmDirector_series.clear() for film_director in film_directors: filmDirector_movie = movie_session.query(Movie).filter_by(film_director_id=film_director.id).count() self.filmDirector_series.append(film_director.name + " " + film_director.surname, filmDirector_movie/counter_movies) for i in range(len(self.filmDirector_series)): slice = QPieSlice() slice = self.filmDirector_series.slices()[i] slice.setLabelVisible(True) self.status_series.clear() all_status = movie_session.query(MovieStatus).all() counter_status = {} for status in all_status: movie_status = movie_session.query(Movie).filter_by(status_id = status.id).count() self.status_series.append(status.name, movie_status/counter_movies) for i in range(len(self.status_series)): slice = QPieSlice() slice = self.status_series.slices()[i] slice.setLabelVisible(True) if slice.label() == 'Not watched': slice.setColor(QColor(255, 0, 0)) elif slice.label() == 'Watched': slice.setColor(QColor(0, 100, 0)) except ZeroDivisionError: home_window = self.parent().findChild(QWidget, 'home_window') self.parent().setCurrentWidget(home_window) openDialog(QMessageBox.Critical, 'Insufficient data for chart', 'Error')
class DistributionPieChart(QChartView): """ Pie chart that shows the distribution of capital according to several criteria """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Chart self.chart = QChart() self.chart.setTheme(QChart.ChartThemeDark) self.chart.legend().hide() self.chart.createDefaultAxes() self.chart.setAnimationOptions(QChart.SeriesAnimations) self.chart.setBackgroundVisible(False) self.chart.setTitle(" ") self.chart.setTitleBrush(QBrush(QColor('white'))) self.setChart(self.chart) self.setRenderHint(QPainter.Antialiasing) self.setStyleSheet("border: 0px; background-color: rgba(0,0,0,0)") self.setupSeries() # Initialize to all mode def setupSeries(self, mode="all"): """ Chart gets updated displaying the new data. Modes: - all : distribution between all accounts - accs : distribution between portfolio accounts - cryptoaccs : distribution between crypto accounts - strategies : distribution between strategies """ # Series self.chart.removeAllSeries() # Remove any previous series self.series = QPieSeries() # Get data if mode == "all": data = balances.get_all_accounts( ) + cbalances.get_all_accounts_with_amount_fiat() elif mode == "accounts": data = balances.get_all_accounts() elif mode == "crypto": data = cbalances.get_all_accounts_with_amount_fiat() elif mode == "currency": data = [(confighandler.get_fiat_currency().upper(), balances.get_total_balance_all_accounts( )), ("BTC", cbalances.get_total_balance_all_accounts_fiat())] data.sort(key=lambda x: x[1]) # Sort # Set Chart Title self.total = sum([i[1] for i in data]) self.setDefaultTitle() # Add to series for d in data: self.series.append(d[0], d[1]) # Hide little slices' labels self.series.setLabelsVisible(True) for slc in self.series.slices(): if slc.angleSpan() < 5: slc.setLabelVisible(False) slc.setLabelArmLengthFactor(0.05) self.chart.addSeries(self.series) # Signals and functionality self.series.hovered.connect(self.selectSlice) def selectSlice(self, _slice, state): """ Highlight selected slice """ font = ChartTitleFont() if state: font.setPointSize(20) _slice.setLabelVisible(True) self.chart.setTitle( f"{int(_slice.value())} {confighandler.get_fiat_currency().upper()} {round(_slice.percentage()*100,1)}%") else: font.setBold(False) if _slice.angleSpan() < 5: _slice.setLabelVisible(False) _slice.setExploded(False) self.setDefaultTitle() _slice.setLabelFont(font) def setDefaultTitle(self): """ Sets title as total balance from all pie slices """ self.chart.setTitle( f"{int(self.total)} {confighandler.get_fiat_currency().upper()}") font = ChartTitleFont(fontsize=20) self.chart.setTitleFont(font)
def create_piechart(self): Date = date.today() breakfastData = SQLStatements.getTotalBreakfastCalories( self.userID, Date) breakfastData = str(breakfastData) breakfastData = (breakfastData.replace("[", "")) breakfastData = (breakfastData.replace("]", "")) breakfastData = (breakfastData.replace("(", "")) breakfastData = (breakfastData.replace(")", "")) breakfastData = (breakfastData.replace(",", "")) breakfastData = int(breakfastData) lunchData = SQLStatements.getTotalLunchCalories(self.userID, Date) lunchData = str(lunchData) lunchData = (lunchData.replace("[", "")) lunchData = (lunchData.replace("]", "")) lunchData = (lunchData.replace("(", "")) lunchData = (lunchData.replace(")", "")) lunchData = (lunchData.replace(",", "")) lunchData = int(lunchData) dinnerData = SQLStatements.getTotalDinnerCalories(self.userID, Date) dinnerData = str(dinnerData) dinnerData = (dinnerData.replace("[", "")) dinnerData = (dinnerData.replace("]", "")) dinnerData = (dinnerData.replace("(", "")) dinnerData = (dinnerData.replace(")", "")) dinnerData = (dinnerData.replace(",", "")) dinnerData = int(dinnerData) snackData = SQLStatements.getTotalSnacksCalories(self.userID, Date) snackData = str(snackData) snackData = (snackData.replace("[", "")) snackData = (snackData.replace("]", "")) snackData = (snackData.replace("(", "")) snackData = (snackData.replace(")", "")) snackData = (snackData.replace(",", "")) snackData = int(snackData) series = QPieSeries() series.append("Breakfast calories", breakfastData) series.append("Lunch calories", lunchData) series.append("Dinner calories", dinnerData) series.append("Snack calories", snackData) labelFont = QFont("Sans Serif", ) labelFont.setPixelSize(16) slice = QPieSlice() slice.setLabelFont(labelFont) slice = series.slices()[0] slice.setExploded(True) slice.setLabelVisible(True) slice.setPen(QPen(Qt.green, 2)) slice.setBrush(Qt.green) slice = QPieSlice() slice.setLabelFont(labelFont) slice = series.slices()[1] slice.setExploded(True) slice.setLabelVisible(True) slice.setPen(QPen(Qt.white, 2)) slice.setBrush(Qt.white) slice = QPieSlice() slice.setLabelFont(labelFont) slice = series.slices()[2] slice.setExploded(True) slice.setLabelVisible(True) slice.setPen(QPen(Qt.yellow, 2)) slice.setBrush(Qt.yellow) slice = QPieSlice() slice.setLabelFont(labelFont) slice = series.slices()[3] slice.setExploded(True) slice.setLabelVisible(True) slice.setPen(QPen(Qt.yellow, 2)) slice.setBrush(Qt.yellow) chart = QChart() chart.legend().hide() chart.addSeries(series) chart.createDefaultAxes() chart.setAnimationOptions(QChart.SeriesAnimations) chart.setTitle("Daily Calories") chart.setTheme(QChart.ChartThemeBlueCerulean) chart.setBackgroundVisible(False) # Title Font size font = QFont("Sans Serif", ) font.setPixelSize(18) chart.setTitleFont(font) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignBottom) chartview = QChartView(chart) chartview.setRenderHint(QPainter.Antialiasing) return chartview
def dunya(self): if self.bilgiEkran == "dunya": series = QPieSeries() series.append("Hasta", float(self.hasta)) series.append("Olu", float(self.olum)) series.append("Kurtulan", float(self.kurtulan)) #kurtulan slice = QPieSlice() slice = series.slices()[2] slice.setExploded(True) slice.setLabelVisible(True) slice.setPen(QPen(Qt.darkGreen, 2)) slice.setBrush(Qt.green) #olü slice = QPieSlice() sliceozel = series.slices()[1] sliceozel.setExploded(False) sliceozel.setLabelVisible(True) sliceozel.setPen(QPen(Qt.black, 2)) sliceozel.setBrush(Qt.black) #hasta slice = QPieSlice() slice = series.slices()[0] slice.setExploded(False) slice.setLabelVisible(True) slice.setPen(QPen(Qt.darkGray, 2)) slice.setBrush(Qt.gray) chart = QChart() chart.legend().hide() chart.addSeries(series) chart.createDefaultAxes() chart.setAnimationOptions(QChart.AllAnimations) chart.setTitle("Dünya Geneli COVID-19") chart.setTitleFont(QFont("Berlin Sans FB Demi", 22)) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignTop) chart.legend().setFont(QFont("Berlin Sans FB Demi", 16)) chartview = QChartView(chart) chartview.setRenderHint(QPainter.Antialiasing) return chartview elif self.bilgiEkran == "en": series = QPieSeries() series.append("Hasta", float(self.hastaEn)) series.append("Olu", float(self.olumEn)) series.append("Kurtulan", float(self.kurtulanEn)) #kurtulan slice = QPieSlice() slice = series.slices()[2] slice.setExploded(True) slice.setLabelVisible(True) slice.setPen(QPen(Qt.darkGreen, 2)) slice.setBrush(Qt.green) #olü slice = QPieSlice() sliceozel = series.slices()[1] sliceozel.setExploded(False) sliceozel.setLabelVisible(True) sliceozel.setPen(QPen(Qt.black, 2)) sliceozel.setBrush(Qt.black) #hasta slice = QPieSlice() slice = series.slices()[0] slice.setExploded(False) slice.setLabelVisible(True) slice.setPen(QPen(Qt.darkGray, 2)) slice.setBrush(Qt.gray) chart = QChart() chart.legend().hide() chart.addSeries(series) chart.createDefaultAxes() chart.setAnimationOptions(QChart.AllAnimations) chart.setTitle("İngiltere Geneli COVID-19") chart.setTitleFont(QFont("Berlin Sans FB Demi", 22)) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignTop) chart.legend().setFont(QFont("Berlin Sans FB Demi", 16)) chartview = QChartView(chart) chartview.setRenderHint(QPainter.Antialiasing) return chartview else: series = QPieSeries() series.append("Hasta", float(self.hastaTr)) series.append("Olu", float(self.olumTr)) series.append("Kurtulan", float(self.kurtulanTr)) #kurtulan slice = QPieSlice() slice = series.slices()[2] slice.setExploded(True) slice.setLabelVisible(True) slice.setPen(QPen(Qt.darkGreen, 2)) slice.setBrush(Qt.green) #olü slice = QPieSlice() sliceozel = series.slices()[1] sliceozel.setExploded(False) sliceozel.setLabelVisible(True) sliceozel.setPen(QPen(Qt.black, 2)) sliceozel.setBrush(Qt.black) #hasta slice = QPieSlice() slice = series.slices()[0] slice.setExploded(False) slice.setLabelVisible(True) slice.setPen(QPen(Qt.darkGray, 2)) slice.setBrush(Qt.gray) chart = QChart() chart.legend().hide() chart.addSeries(series) chart.createDefaultAxes() chart.setAnimationOptions(QChart.AllAnimations) chart.setTitle("Türkiye Geneli COVID-19") chart.setTitleFont(QFont("Berlin Sans FB Demi", 22)) chart.legend().setVisible(True) chart.legend().setAlignment(Qt.AlignTop) chart.legend().setFont(QFont("Berlin Sans FB Demi", 16)) chartview = QChartView(chart) chartview.setRenderHint(QPainter.Antialiasing) return chartview
class StatisticsView(QWidget): def __init__(self, parent): super().__init__(parent) self.ui = Ui_statistics_window() self.ui.setupUi(self) self.genre_series = QPieSeries() self.author_series = QPieSeries() self.status_series = QPieSeries() self.createChart('Book percentages genre', self.genre_series) self.createChart('Book percentages author', self.author_series) self.createChart('Book percentages status', self.status_series) self.show() def getValues(self): books = book_session.query(Book).count() authors = book_session.query(Author).count() genres = book_session.query(Genre).count() self.ui.booksCounter_label.setText(str(books)) self.ui.authorsCounter_label.setText(str(authors)) self.ui.genresCounter_label.setText(str(genres)) def createChart(self, title, series): chart = QChart() chart.addSeries(series) chart.setAnimationOptions(QChart.SeriesAnimations) chart.setTitle(title) #sslice.setLabel("{:.1f}%".format(100 * slice.percentage())) chartview = QChartView(chart) chartview.setRenderHint(QPainter.Antialiasing) #setChart(chartview) self.ui.horizontalLayout.addWidget(chartview) def updateValues(self): try: counter_books = book_session.query(Book).count() genres = book_session.query(Genre).all() self.genre_series.clear() for genre in genres: genre_books = book_session.query(Book).filter_by( genre_id=genre.id).count() self.genre_series.append(genre.name, genre_books / counter_books) for i in range(len(self.genre_series)): slice = QPieSlice() slice = self.genre_series.slices()[i] slice.setLabelVisible(True) authors = book_session.query(Author).all() self.author_series.clear() for author in authors: author_books = book_session.query(Book).filter_by( author_id=author.id).count() self.author_series.append(author.name + " " + author.surname, author_books / counter_books) for i in range(len(self.author_series)): slice = QPieSlice() slice = self.author_series.slices()[i] slice.setLabelVisible(True) self.status_series.clear() all_status = book_session.query(BookStatus).all() counter_status = {} for status in all_status: book_status = book_session.query(Book).filter_by( status_id=status.id).count() self.status_series.append(status.name, book_status / counter_books) for i in range(len(self.status_series)): slice = QPieSlice() slice = self.status_series.slices()[i] slice.setLabelVisible(True) if slice.label() == 'Not readed': slice.setColor(QColor(255, 0, 0)) elif slice.label() == 'In progress': slice.setColor(QColor(0, 0, 255)) elif slice.label() == 'Readed': slice.setColor(QColor(0, 100, 0)) except ZeroDivisionError: home_window = self.parent().findChild(QWidget, 'home_window') self.parent().setCurrentWidget(home_window) openDialog(QMessageBox.Critical, 'Insufficient data for chart', 'Error')
class TokenPieChart(QChartView): """ Chart that displays certaing tokens with their respective balance on a Pie Chart. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.series = QPieSeries() self.chart = QChart() # self.chart.setTheme(QChart.ChartThemeBrownSand) self.chart.setTheme(QChart.ChartThemeQt) self.chart.legend().hide() self.chart.addSeries(self.series) self.chart.createDefaultAxes() self.chart.setAnimationOptions(QChart.SeriesAnimations) self.chart.setBackgroundBrush(QBrush(QColor('#19232d'))) self.chart.setTitle("") self.chart.setTitleBrush(QBrush(QColor('white'))) self.chart.legend().setAlignment(Qt.AlignBottom) self.setChart(self.chart) self.setRenderHint(QPainter.Antialiasing) self.setStyleSheet('border: 0px') # self.setMinimumWidth(300) def updateWithAccount(self, account): """Changes the series so that only tokens from a certain account are shown""" entries_with_account = cbalances.get_entries_with_account(account) self.series.clear() for entry in entries_with_account: token = entry[1].upper() amount = entry[2] amount_btc = prices.to_btc(token, amount) self.series.append(token, amount_btc) self.showSliceLabels() def allMode(self): """Changes the series to show all tokens""" self.series.clear() data = cbalances.get_all_tokens_with_amount() for d in data: token = d[0].upper() amount = d[1] total_in_btc = prices.to_btc(token, amount) self.series.append(token, total_in_btc) self.showSliceLabels() self.hideLittleSlices() def showSliceLabels(self): """ Formats the Slices so that they show the percentage """ for slce in self.series.slices(): slce.setLabel("{} {}% ({})".format( slce.label(), int(100*slce.percentage()), str(round(slce.value(), 4)) + " BTC")) slce.setLabelPosition(QPieSlice.LabelInsideNormal) # slce.setLabelPosition(QPieSlice.LabelOutside) slce.setLabelVisible(True) self.hideLittleSlices() def selectSlice(self, account): """ Explodes a certaing slice that corresponds to an account """ for slce in self.series.slices(): if slce.label().split(' ')[0] == account: # Explode slice slce.setExploded(True) font = QFont() font.setBold(True) font.setWeight(QFont.ExtraBold) font.setUnderline(True) slce.setLabelFont(font) slce.setLabelColor(QColor("white")) slce.setLabelPosition(QPieSlice.LabelOutside) else: slce.setExploded(False) slce.setLabelFont(QFont()) # # slce.setLabelPosition(QPieSlice.LabelInsideTangential) font = QFont() slce.setLabelColor(QColor("#3f3f39")) slce.setLabelFont(font) slce.setLabelPosition(QPieSlice.LabelInsideNormal) self.hideLittleSlices(selected=account) def hideLittleSlices(self, selected=''): """ If a slice is not big enough for the label to be properly seen, the label gets hidden """ for slce in self.series.slices(): if slce.angleSpan() < 5 and slce.label().split(' ')[0] != selected: # Slice too little to show, and it's not selected slce.setLabelVisible(False) else: slce.setLabelVisible(True)
class VCPieAlone(VCCommons): def __init__(self): VCCommons.__init__(self) self.clear() ## If you use VCPieAlone you can add a context menu setting boolean to True def setCustomContextMenu(self, boolean): self.customContextMenuRequested.connect( self.on_customContextMenuRequested) def appendData(self, name, value, exploded=False): self.data.append([name, value]) slice = self.serie.append(name, object2value(value)) #only float slice.setExploded(exploded) slice.setLabelVisible() ## To clean pie, removes serie and everithing is like create an empty pie def clear(self): self._chart = QChart() self.setChart(self._chart) self.setRenderHint(QPainter.Antialiasing) self.data = [] self.serie = QPieSeries() self.serie.setPieStartAngle(90) self.serie.setPieEndAngle(450) self.chart().legend().hide() ## To show pie def display(self): self.chart().layout().setContentsMargins(0, 0, 0, 0) if self._animations == True: self.chart().setAnimationOptions(QChart.AllAnimations) else: self.chart().setAnimationOptions(QChart.NoAnimation) self._display_set_title() for slice in self.serie.slices(): slice.setLabel("{}: {}".format(slice.label(), Percentage(slice.percentage(), 1))) if slice.percentage() < 0.005: slice.setLabelVisible(False) self.chart().addSeries(self.serie) self.repaint() self.displayed.emit() def sum_values(self): if len(self.data) == 0: return None cls = self.data[0][1].__class__.__name__ if cls in ["int", "float", "Decimal"]: s = 0 elif cls in [ "Currency", ]: s = self.data[0][1].__class__(0, self.data[0][1].currency) elif cls in [ "Money", ]: s = self.data[0][1].__class__(self.data[0][1].mem, 0, self.data[0][1].currency) for row in self.data: s = s + row[1] return s ## Returns a qmenu to be used in other qmenus def qmenu(self, title="Pie chart options"): menu = QMenu(self) menu.setTitle(self.tr(title)) menu.addAction(self.actionSave) return menu def on_customContextMenuRequested(self, pos): self.qmenu().exec_(self.mapToGlobal(pos))
class LeftBarPieChart(QWidget): def __init__(self, parent): super(LeftBarPieChart, self).__init__() self.parent = parent self.setParent(parent) self.chart = None self.inputs = [] self.layout = None self.layout_inp = None self.btn_add = None self.w_inp = None self.header = None self.init_ui() def init_ui(self): self.chart = QChart() self.chart.setTheme(QChart.ChartThemeBlueIcy) self.chart.setAnimationDuration(1000) self.chart.setAnimationOptions(QChart.AllAnimations) self.serie = QPieSeries() self.layout = QVBoxLayout() self.layout_inp = QVBoxLayout() self.w_inp = QWidget() self.w_inp.setStyleSheet(""" .QWidget{ background-color: transparent; } """) self.w_inp.setLayout(self.layout_inp) self.setLayout(self.layout) self.inputs.append(InputPieChart(self)) self.btn_add = QPushButton("+") self.btn_remove = QPushButton("-") self.btn_add.clicked.connect(self.add_input) self.btn_remove.clicked.connect(self.remove_input) self.btn_add.setStyleSheet(""" border: 0px; background: green; color: white; """) self.btn_remove.setStyleSheet(""" border: 0px; background: red; color: white; """) self.header = HeaderPieChartInput() self.layout.addWidget(self.header) self.layout.addWidget(self.w_inp) self.layout.addStretch(-1) self.layout.addWidget(self.btn_remove) self.layout.addWidget(self.btn_add) self.layout_inp.addWidget(self.inputs[0]) self.serie.append(self.inputs[0].name.text(), 2) # self.slice.setExploded() # self.slice.setLabelVisible() # self.slice.setPen(QPen(Qt.darkGreen,2)) # self.slice.setBrush(Qt.green) self.chart.addSeries(self.serie) self.chart.setTitle("Pie Chart") def add_input(self): if len(self.inputs) < 10: self.inputs.append(InputPieChart(self)) self.layout_inp.addWidget(self.inputs[-1]) self.serie.append(self.inputs[-1].name.text(), int(self.inputs[-1].value.text())) # for slice in self.serie.slices(): # slice.setBrush(Qt.green) def remove_input(self): if len(self.inputs) >= 1: self.layout_inp.removeWidget(self.inputs[-1]) self.inputs[-1].hide() self.inputs.remove(self.inputs[-1]) self.slc = self.serie.slices()[-1] self.serie.remove(self.slc) # for slice in self.serie.slices(): # slice.setBrush(Qt.green) def input_changed(self, txt): if self.serie in self.chart.series(): self.chart.removeSeries(self.serie) self.serie = QPieSeries() for inp in self.inputs: self.serie.append(inp.name.text(), int(inp.value.text())) self.chart.addSeries(self.serie)
class MainUI(QtWidgets.QMainWindow): def __init__(self): super().__init__() self.initUI() def initUI(self): self.filename = '' self.json = () self.datax = [] self.percent = 0.0 self.setFixedSize(1280, 720) self.center() # self.setWindowOpacity(0.9) self.setWindowFlag(QtCore.Qt.FramelessWindowHint) self.setWindowTitle('恶意函数预测系统') spin_icon = qtawesome.icon('fa5b.github', color='black') self.setWindowIcon(spin_icon) self.main_widget = QtWidgets.QWidget() # 创建窗口主部件 self.main_layout = QtWidgets.QGridLayout() # 创建主部件的网格布局 self.main_widget.setLayout(self.main_layout) # 设置窗口主部件布局为网格布局 self.left_widget = QtWidgets.QWidget() # 创建左侧部件 self.left_widget.setObjectName('left_widget') self.left_layout = QtWidgets.QGridLayout() # 创建左侧部件的网格布局层 self.left_widget.setLayout(self.left_layout) # 设置左侧部件布局为网格 self.left_up_widget = QtWidgets.QWidget() # 创建左侧部件的上半部件 self.left_up_widget.setObjectName('left_up_widget') self.left_up_layout = QtWidgets.QGridLayout() # 创建左侧部件的网格布局层 self.left_up_widget.setLayout(self.left_up_layout) # 设置左侧部件布局为网格 self.left_down_widget = QtWidgets.QWidget() # 创建左侧部件的下半部件 self.left_down_widget.setObjectName('left_down_widget') self.left_down_layout = QtWidgets.QGridLayout() # 创建左侧部件的网格布局层 self.left_down_widget.setLayout(self.left_down_layout) # 设置左侧部件布局为网格 self.left_layout.addWidget(self.left_up_widget, 0, 0, 3, 2) self.left_layout.addWidget(self.left_down_widget, 3, 0, 9, 2) self.main_layout.addWidget(self.left_widget, 0, 0, 12, 8) # 左侧部件在第0行第0列,占8行3列 self.setCentralWidget(self.main_widget) # 设置窗口主部件 self.pushButton = QtWidgets.QPushButton() self.pushButton.setObjectName("pushButton") self.pushButton.setText("选择文件") self.pushButton.setFont(QFont("Times", 18)) self.pushButton.setFixedWidth(300) self.pushButton.setFixedHeight(100) self.pushButton.setStyleSheet('''QPushButton{background:#6DDF6D;border-radius:15px;} QPushButton:hover{background:green;}''') self.left_up_layout.addWidget(self.pushButton, 0, 0, 1, 1) self.pushButton.clicked.connect(self.openfile) self.show() def center(self): qr = self.frameGeometry() cp = QDesktopWidget().availableGeometry().center() qr.moveCenter(cp) self.move(qr.topLeft()) def openfile(self): openfile_name = QFileDialog.getOpenFileName(self, '请选择文件夹路径', '', 'All Files (*)') self.filename = openfile_name[0] self.json = self.algorithm(self.filename) self.write(self.json) print(self.filename) def algorithm(self,filename): cmd = "ida64 -A -S\"Z:\\Users\\zhangbo\\Desktop\\PredictionSystem\\code_prediction\\extract_trace_v3.py\" \"Z:\\Users\\zhangbo\\Desktop\\linux程序\\bc\"" cmd2 = "ida64 -A -S\"Z:\\Users\\zhangbo\\Desktop\\PredictionSystem\\code_prediction\\extract_trace_v3.py\" " +"\""+filename+"\"" print(cmd2) # print(cmd) os.system(cmd2) test_path = filename[:filename.rfind("/")+1]+"test.csv" while(1): if(os.path.exists(test_path)): break j = pc.prediction(test_path) j = json.loads(j) os.remove(test_path) # print(j) return j def paintEvent(self, event): # set background_img painter = QPainter(self) painter.drawRect(self.rect()) # pixmap = QPixmap("./img.jpeg") # 换成自己的图片的相对路径 pixmap = QPixmap("./img.jpeg") # 换成自己的图片的相对路径 painter.drawPixmap(self.rect(), pixmap) def write(self, jsonfile): self.right_widget = QtWidgets.QTableWidget() # 创建右侧部件 self.right_widget.setObjectName('right_widget') self.right_layout = QtWidgets.QGridLayout() self.right_widget.setLayout(self.right_layout) # 设置右侧部件布局为网格 self.main_layout.addWidget(self.right_widget, 0, 8, 12, 4) # 右侧部件在第0行第3列,占8行9列 self.right_widget.setColumnCount(2) self.right_widget.setRowCount(len(jsonfile)) self.right_widget.setHorizontalHeaderLabels(['函数名', '状态']) self.right_widget.verticalHeader().setSectionResizeMode(QHeaderView.Stretch) self.right_widget.setEditTriggers(QAbstractItemView.NoEditTriggers) # self.right_widget.setStyleSheet("selection-background-color:pink") self.right_widget.setColumnWidth(0, 100) self.right_widget.setColumnWidth(1, 100) i = 0 x = 0 for key, value in jsonfile.items(): print([key, value]) newItem = QTableWidgetItem(key) self.right_widget.setItem(i, 0, newItem) newItem = QTableWidgetItem(str(value)) self.right_widget.setItem(i, 1, newItem) if value == 0: self.right_widget.item(i, 0).setBackground(QBrush(QColor(255, 0, 0))) self.right_widget.item(i, 1).setBackground(QBrush(QColor(255, 0, 0))) x += 1 i = i + 1 self.percent = x / i self.show() self.chartx() def chartx(self): self.pieseries = QPieSeries() # 定义PieSeries self.pieseries.append("正常程序", 1 - self.percent) # 插入第一个元素 self.pieseries.append("恶意程序", self.percent) self.slice = self.pieseries.slices()[0] # 得到饼图的某一个元素切片,在这取得为第一个 # self.slice.setExploded() # 设置为exploded self.slice.setLabelVisible() # 设置Lable self.slice.setPen(QPen(Qt.darkGreen, 1)) # 设置画笔类型 self.slice.setBrush(Qt.green) # 设置笔刷 self.slice1 = self.pieseries.slices()[1] # 得到饼图的某一个元素切片,在这取得为第一个 self.slice1.setExploded() # 设置为exploded self.slice1.setLabelVisible() # 设置Lable self.slice1.setPen(QPen(Qt.darkRed, 1)) # 设置画笔类型 self.slice1.setBrush(Qt.red) # 设置笔刷 self.chart = QChart() # 定义QChart self.chart.addSeries(self.pieseries) # 将 pieseries添加到chart里 self.chart.setTitle("恶意程序预测结果饼状图") # 设置char的标题 self.chart.legend().hide() # 将char的legend设置为隐藏 self.charview = QChartView(self.chart, self.left_down_widget) # 定义charView窗口,添加chart元素,设置主窗口为父窗体,既将chartView嵌入到父窗体 self.charview.setGeometry(0, 0, 800, 500) # 设置charview在父窗口的大小、位置 self.charview.setRenderHint(QPainter.Antialiasing) # 设置抗锯齿 self.charview.show() # 将CharView窗口显示出来
class Chart(QWidget): def __init__(self, chartKey, data, frame, parent=None): super(Chart, self).__init__(parent) self.frame = frame self.data = data self.pt = self.parent() #add the to the main window #self.toolbar = QToolBar("Edit", self) #self.pt.addToolBar(self.toolbar) #ly = QtWidgets.QVBoxLayout() #self.frame = QtWidgets.QFrame() #self.frame.setLayout(ly) #self.layout = QtWidgets.QGridLayout() #print('----------------',self.frame) self.create_chart(chartKey) clicked = QtCore.pyqtSignal(QtCore.QModelIndex) #self.pt.addToolBar(self.navigationBar(data)) def create_chart(self, chartKey): self.series = QPieSeries() self.series.setHoleSize(0.35) self.chart = QChart() #Add series to the chart self.addSeries(chartKey) # for the background and title self.chart.setAnimationOptions(QChart.SeriesAnimations) self.chart.setTitle("DonutChart Example") self.chart.setTheme(QChart.ChartThemeBlueCerulean) self.chartview = QChartView(self.chart) self.chartview.setRenderHint(QPainter.Antialiasing) #navigation = Navigation(classObj, self) #self.addToolBar(navigation.toolbar) #clicked = QtCore.pyqtSignal(QtCore.QModelIndex) def navigationBar(self, data): self.toolbar = QtWidgets.QToolBar() self.toolbar.actionTriggered.connect(self.on_actionTriggered) self.model = QtGui.QStandardItemModel(self) dict_to_model(self.model.invisibleRootItem(), data) it = self.model.item(0, 0) ix = self.model.indexFromItem(it) root_action = self.toolbar.addAction(it.text()) root_action.setData(QtCore.QPersistentModelIndex(ix)) self.listview = QtWidgets.QListView() self.listview.setEditTriggers( QtWidgets.QAbstractItemView.NoEditTriggers) #self.series.doubleClicked.connect(self.on_clicked) self.listview.setModel(self.model) self.listview.setRootIndex(ix) self.a = 10 return self.toolbar #make the listed items clickable #@QtCore.pyqtSlot(QtCore.QModelIndex) def on_clicked(self, index): if not self.model.hasChildren(index): self.clicked.emit(index) return action = self.toolbar.addAction(index.data()) action.setData(QtCore.QPersistentModelIndex(index)) self.listview.setRootIndex(index) print(index.data()) self.chart.addSeries(index.data()) #make the breadcrumbs clickable in order to go back and forth #@QtCore.pyqtSlot(QtWidgets.QAction) def on_actionTriggered(self, action): ix = action.data() self.chart.addSeries(ix.data()) model = ix.model() self.listview.setRootIndex(QtCore.QModelIndex(ix)) self.toolbar.clear() ixs = [] while ix.isValid(): ixs.append(ix) ix = ix.parent() for ix in reversed(ixs): action = self.toolbar.addAction(ix.data()) action.setData(ix) def addSeries(self, key): self.chart.removeAllSeries() self.series = QPieSeries() self.series.setHoleSize(0.35) #Show chartview only if the content length is less than 6. Otherwise show a table view if len(self.data[key]) < 6: for key, value in self.data[key].items(): slice_ = QPieSlice(str(key), value) self.series.append(slice_) for slice in self.series.slices(): slice.setLabel(slice.label()) self.chart.addSeries(self.series) self.frame.frame.hide() self.chart.show() else: for m, item in self.data[key].items(): print(m, item) self.table = TableView(self.data[key], len(self.data[key]), 1) if self.frame.ly.count() > 0: self.frame.ly.itemAt(0).widget().setParent(None) self.frame.ly.addWidget(self.table) self.frame.frame.show() self.chart.hide() self.series.doubleClicked.connect(self.handle_double_clicked) #Show the update chart with the distribution of the selected slice def handle_double_clicked(self, slice): slice.setExploded() slice.setLabelVisible() if slice.label() in self.data.keys(): print("slice", slice.label()) self.addSeries(slice.label())