def __init__(self, show_time=True):
        """Opens a progress bar widget
        :type show_time: bool
        :param show_time: If the time should be shown below the progress bar"""
        super().__init__()
        # Setup parameters
        self._show_time: bool = show_time
        self._timer_start: float = 0

        # General layout
        self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
        self._layout = QVBoxLayout()
        self.setLayout(self._layout)
        # The progress bar itself
        self._progress_bar = QProgressBar(self)
        self._progress_bar.setMaximum(100)
        self._progress_bar.setGeometry(0, 0, 350, 25)
        self._progress_bar.setValue(0)
        self._layout.addWidget(self._progress_bar)
        # Setup time display
        self._time_wrapper = QHBoxLayout()
        self._time_expired_label = QLabel("")
        self._time_expired_label.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
        self._time_left_label = QLabel("")
        self._time_left_label.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
        self._time_wrapper.addWidget(self._time_expired_label)
        self._time_wrapper.addWidget(self._time_left_label)
        self._layout.addLayout(self._time_wrapper)
        # Set Size
        self.resize(500, 80)
        # Register progress update handler
        # noinspection PyUnresolvedReferences
        self.set_progress.connect(self._set_progress)
Beispiel #2
0
    def __init__(self):
        super().__init__()

        layout = QVBoxLayout()

        self.progress = QProgressBar()

        button = QPushButton("START IT UP")
        button.pressed.connect(self.execute)

        self.status = QLabel("0 workers")

        layout.addWidget(self.progress)
        layout.addWidget(button)
        layout.addWidget(self.status)

        w = QWidget()
        w.setLayout(layout)

        # Dictionary holds the progress of current workers.
        self.worker_progress = {}

        self.setCentralWidget(w)

        self.show()

        self.threadpool = QThreadPool()
        print("Multithreading with maximum %d threads" %
              self.threadpool.maxThreadCount())

        self.timer = QTimer()
        self.timer.setInterval(100)
        self.timer.timeout.connect(self.refresh_progress)
        self.timer.start()
Beispiel #3
0
class MainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__()

        layout = QVBoxLayout()
        self.progress = QProgressBar()
        button = QPushButton("START IT UP")
        button.pressed.connect(self.execute)

        layout.addWidget(self.progress)
        layout.addWidget(button)

        w = QWidget()
        w.setLayout(layout)

        self.setCentralWidget(w)

        self.show()

        self.threadpool = QThreadPool()
        print("Multithreading with maximum %d threads" %
              self.threadpool.maxThreadCount())

    def execute(self):
        worker = Worker()
        worker.signals.progress.connect(self.update_progress)
        # Execute
        self.threadpool.start(worker)

    def update_progress(self, progress):
        self.progress.setValue(progress)
Beispiel #4
0
 def __init__(self, worker_name, *args):
     super().__init__(*args)
     self.setLayout(QVBoxLayout())
     self.layout().setAlignment(Qt.AlignTop)
     self.label = QLabel(self)
     self.label.setText(worker_name.replace("\\", "/").split("/")[-1] + ":")
     self.progress = QProgressBar(self)
     self.layout().addWidget(self.label)
     self.layout().addWidget(self.progress)
     self.progress.setValue(0)
Beispiel #5
0
 def setupUi(self):
     layout = QVBoxLayout()
     self.timer = QBasicTimer()
     self.pbar = QProgressBar(self)
     self.setWindowTitle("isutils: Executing op (1/1)...")
     self.resize(400, 250)
     layout.addWidget(self.lblh)
     layout.addWidget(self.lblo)
     layout.addWidget(self.pbar)
     self.setLayout(layout)
    def _createProgressBar(self):

        self.progress_bar = QProgressBar()
        self.progress_bar.minimum = 0
        self.progress_bar.maximum = 100
        self.progress_bar.setValue(0)
        self.progress_bar.setTextVisible(False)
        self.progress_bar.setGeometry(50, 50, 10, 10)
        self.progress_bar.setAlignment(QtCore.Qt.AlignRight)
        self.progress_bar.adjustSize()
        self.statusBar().addPermanentWidget(self.progress_bar)
        self.ChangeAppStatus(False)
Beispiel #7
0
 def setupUi(self):
     self.setWindowTitle('QProgressBar Example')
     self.btn = QPushButton('Click Me!')
     self.btn.clicked.connect(self.btnFunc)
     self.pBar = QProgressBar()
     self.pBar.setValue(0)
     self.resize(300, 100)
     self.vbox = QVBoxLayout()
     self.vbox.addWidget(self.pBar)
     self.vbox.addWidget(self.btn)
     self.setLayout(self.vbox)
     self.show()
Beispiel #8
0
 def __init__(self):
     super().__init__()
     self.setWindowTitle("Example")
     self.layout = QGridLayout()
     self.layout.setContentsMargins(6, 6, 6, 6)
     self.layout.addWidget(QTableWidget(), 0, 0, 1, 3)
     self.loading_bar = QProgressBar()
     self.loading_bar.setTextVisible(False)
     self.loading_bar.setValue(25)
     self.layout.addWidget(self.loading_bar, 1, 0, 1, 1)
     self.refresh_btn = FixedWindowsButton("Refresh")
     self.layout.addWidget(self.refresh_btn, 1, 1, 1, 1)
     self.execute_btn = FixedWindowsButton("Execute")
     self.layout.addWidget(self.execute_btn, 1, 2, 1, 1)
     self.setLayout(self.layout)
Beispiel #9
0
 def __init__(self,
              curr_op: Type[Op] = Shell,
              len: int = 1,
              ix=0,
              parent: Any | None = None):
     super().__init__(parent)
     self.index = ix
     self.lblh = self.toplabel()
     self.lblh = QLabel(self)
     self.lblo = self.oplabel()
     self.opmsg = QLabel("", self)
     self.pbar = QProgressBar(self)
     self.pbar.setValue(0)
     self.len = len
     self.setupUi()
Beispiel #10
0
    def __init__(self, language):
        QMainWindow.__init__(self, None)
        self.running = False
        self.setupUi(self)
        self.restoreGeometry(base64.decodebytes(JalSettings().getValue('WindowGeometry', '').encode('utf-8')))
        self.restoreState(base64.decodebytes(JalSettings().getValue('WindowState', '').encode('utf-8')))

        self.ledger = Ledger()

        # Customize Status bar and logs
        self.ProgressBar = QProgressBar(self)
        self.StatusBar.addPermanentWidget(self.ProgressBar)
        self.ProgressBar.setVisible(False)
        self.ledger.setProgressBar(self, self.ProgressBar)
        self.Logs.setStatusBar(self.StatusBar)
        self.logger = logging.getLogger()
        self.logger.addHandler(self.Logs)
        log_level = os.environ.get('LOGLEVEL', 'INFO').upper()
        self.logger.setLevel(log_level)

        self.currentLanguage = language

        self.downloader = QuoteDownloader()
        self.statements = Statements(self)
        self.reports = Reports(self, self.mdiArea)
        self.backup = JalBackup(self, get_dbfilename(get_app_path()))
        self.estimator = None
        self.price_chart = None

        self.actionImportSlipRU.setEnabled(dependency_present(['pyzbar', 'PIL']))

        self.actionAbout = QAction(text=self.tr("About"), parent=self)
        self.MainMenu.addAction(self.actionAbout)

        self.langGroup = QActionGroup(self.menuLanguage)
        self.createLanguageMenu()

        self.statementGroup = QActionGroup(self.menuStatement)
        self.createStatementsImportMenu()

        self.reportsGroup = QActionGroup(self.menuReports)
        self.createReportsMenu()

        self.setWindowIcon(load_icon("jal.png"))

        self.connect_signals_and_slots()

        self.actionOperations.trigger()
    def setupWidgets(self):
        """
        Set up the widgets and layouts for interface.
        """
        dir_label = QLabel("Choose Directory:")
        self.dir_line_edit = QLineEdit()

        dir_button = QPushButton('...')
        dir_button.setToolTip("Select file directory.")
        dir_button.clicked.connect(self.setDirectory)

        self.change_name_edit = QLineEdit()
        self.change_name_edit.setToolTip(
            "Files will be appended with numerical values.For example: filename <b> 01 </b >.jpg")
        self.change_name_edit.setPlaceholderText("Change file names to...")

        rename_button = QPushButton("Rename Files")
        rename_button.setToolTip("Begin renaming files in directory.")
        rename_button.clicked.connect(self.renameFiles)

        file_exts = [".jpg", ".jpeg", ".png", ".gif", ".txt"]

        # Create combo box for selecting file extensions.
        ext_cb = QComboBox()
        self.cb_value = file_exts[0]
        ext_cb.setToolTip("Only files with this extension will be changed.")
        ext_cb.addItems(file_exts)
        ext_cb.currentTextChanged.connect(self.updateCbValue)

        # Text edit is for displaying the file names as they are updated.
        self.display_files_edit = QTextEdit()
        self.display_files_edit.setReadOnly(True)
        self.progress_bar = QProgressBar()
        self.progress_bar.setValue(0)

        # Set layout and widgets.
        grid = QGridLayout()
        grid.addWidget(dir_label, 0, 0)
        grid.addWidget(self.dir_line_edit, 1, 0, 1, 2)
        grid.addWidget(dir_button, 1, 2)
        grid.addWidget(self.change_name_edit, 2, 0)
        grid.addWidget(ext_cb, 2, 1)
        grid.addWidget(rename_button, 2, 2)
        grid.addWidget(self.display_files_edit, 3, 0, 1, 3)
        grid.addWidget(self.progress_bar, 4, 0, 1, 3)
        self.setLayout(grid)
Beispiel #12
0
class ProgressExample(QWidget):
    """The main ui components"""
    def __init__(self, parent=None):
        super(ProgressExample, self).__init__(parent)
        self.setupUi()

    def setupUi(self):
        self.setWindowTitle('QProgressBar Example')
        self.btn = QPushButton('Click Me!')
        self.btn.clicked.connect(self.btnFunc)
        self.pBar = QProgressBar()
        self.pBar.setValue(0)
        self.resize(300, 100)
        self.vbox = QVBoxLayout()
        self.vbox.addWidget(self.pBar)
        self.vbox.addWidget(self.btn)
        self.setLayout(self.vbox)
        self.show()

    def btnFunc(self):
        self.thread = Thread()
        self.thread._signal.connect(self.signal_accept)
        self.thread.start()
        self.btn.setEnabled(False)

    def signal_accept(self, msg):
        self.pBar.setValue(int(msg))
        if self.pBar.value() == 99:
            self.pBar.setValue(0)
            self.btn.setEnabled(True)
 def __init__(self):
     super().__init__()
     self.setWindowTitle("Example")
     self.layout = QHBoxLayout()
     self.layout.setContentsMargins(6, 6, 6, 6)
     self.loading_bar = QProgressBar()
     self.loading_bar.setTextVisible(False)
     self.loading_bar.setFixedHeight(25)
     self.layout.addWidget(self.loading_bar)
     self.quit_btn = FixedWindowsButton("Quit")
     self.quit_btn.setFixedHeight(25)
     self.quit_btn.clicked.connect(self.onQuitBtnClicked)
     self.layout.addWidget(self.quit_btn)
     self.run_btn = FixedWindowsButton("Run")
     self.run_btn.setFixedHeight(25)
     self.run_btn.clicked.connect(self.onRunBtnClicked)
     self.layout.addWidget(self.run_btn)
     self.setLayout(self.layout)
Beispiel #14
0
 def __init__(self):
     super().__init__()
     # 设置属性
     self.resize(400, 300)
     self.setWindowTitle("测试Qt进度条和aria2的联合")
     # 注册组件
     self.labelUrl = QLabel("下载链接")
     self.lineEditorUrl = QLineEdit(
         "https://download.cnki.net/CAJViewer-x86_64-buildubuntu1604-210401.AppImage"
     )
     self.labelProgress = QLabel("下载进度")
     self.downloadProgress = QProgressBar()
     self.textResult = QTextBrowser()
     self.buttonStart = QPushButton("开始")
     self.buttonPause = QPushButton("暂停")
     self.buttonUnpause = QPushButton("继续")
     self.buttonRemove = QPushButton("移除")
     self.buttonDebug = QPushButton("Debug")
     # 设置组件
     self.lineEditorUrl.setClearButtonEnabled(True)
     self.buttonStart.setIcon(self.style().standardIcon(
         QStyle.SP_MediaPlay))
     self.buttonPause.setIcon(self.style().standardIcon(
         QStyle.SP_MediaPause))
     self.buttonUnpause.setIcon(self.style().standardIcon(
         QStyle.SP_MediaPlay))
     self.buttonRemove.setIcon(self.style().standardIcon(
         QStyle.SP_MediaStop))
     # self.buttonPause.setDisabled(True)
     # self.buttonStop.setDisabled(True)
     # 添加组件
     self.layout = QGridLayout(self)
     self.layout.addWidget(self.labelUrl, 0, 0, 1, 1)
     self.layout.addWidget(self.lineEditorUrl, 0, 1, 1, 5)
     self.layout.addWidget(self.labelProgress, 1, 0, 1, 1)
     self.layout.addWidget(self.downloadProgress, 1, 1, 1, 5)
     self.layout.addWidget(self.textResult, 2, 0, 2, 5)
     self.layout.addWidget(self.buttonStart, 4, 0, 1, 1)
     self.layout.addWidget(self.buttonPause, 4, 1, 1, 1)
     self.layout.addWidget(self.buttonUnpause, 4, 2, 1, 1)
     self.layout.addWidget(self.buttonRemove, 4, 3, 1, 1)
     self.layout.addWidget(self.buttonDebug, 4, 4, 1, 1)
Beispiel #15
0
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__()

        layout = QVBoxLayout()
        self.progress = QProgressBar()
        button = QPushButton("START IT UP")
        button.pressed.connect(self.execute)

        layout.addWidget(self.progress)
        layout.addWidget(button)

        w = QWidget()
        w.setLayout(layout)

        self.setCentralWidget(w)

        self.show()

        self.threadpool = QThreadPool()
        print("Multithreading with maximum %d threads" %
              self.threadpool.maxThreadCount())
Beispiel #16
0
 def __init__(self, parent=None) -> None:
     super().__init__()
     self.parent = parent
     #
     self.message_label = QLabel(self)
     self.sep1 = QLabel("|", self)
     self.curr_pos_label = QLabel(self)
     self.sep2 = QLabel("|", self)
     self.file_name_label = QLabel(self)
     self.sep3 = QLabel("|", self)
     self.resolution_label = QLabel(self)
     self.sep4 = QLabel("|", self)
     # self.memory_label = QLabel(self)
     # self.sep5 = QLabel("|", self)
     self.mode_label = QLabel(self)
     self.sep5 = QLabel("|", self)
     self.progressbar = QProgressBar(self)
     self.progressbar.setMaximumWidth(150)
     self.progressbar.setMaximumHeight(15)
     self.progressbar.hide()
     #
     layout = QHBoxLayout()
     layout.setContentsMargins(0, 0, 0, 0)
     self.setLayout(layout)
     self.layout().addWidget(self.message_label)
     self.layout().addWidget(self.sep1)
     self.layout().addWidget(self.curr_pos_label)
     self.layout().addWidget(self.sep2)
     self.layout().addWidget(self.resolution_label)
     self.layout().addWidget(self.sep3)
     self.layout().addWidget(self.file_name_label)
     self.layout().addWidget(self.sep4)
     # self.layout().addWidget(self.memory_label)
     # self.layout().addWidget(self.sep5)
     self.layout().addWidget(self.mode_label)
     self.layout().addWidget(self.sep5)
     self.layout().addWidget(self.progressbar)
     #
     self.message_timer = None
Beispiel #17
0
class MyClass(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.resize(300, 200)
        # 载入进度条控件
        self.verticalLayout = QVBoxLayout()
        self.pgb = QProgressBar(self)
        self.verticalLayout.addWidget(self.pgb, 0, 0, 1, 1)
        #self.pgb.move(50, 50)
        #self.pgb.resize(250, 20)

        # 配置一个值表示进度条的当前进度
        self.pv = 0

        # 申明一个时钟控件
        self.timer1 = QBasicTimer()

        # 设置进度条的范围
        self.pgb.setMinimum(0)
        self.pgb.setMaximum(100)
        self.pgb.setValue(self.pv)
        # 载入按钮
        self.btn = QPushButton("开始", self)
        self.btn.move(50, 100)
        self.btn.clicked.connect(self.myTimerState)
        self.show()

    def myTimerState(self):
        if self.pv == 100:
            self.close()
        if self.timer1.isActive():
            self.timer1.stop()
            self.btn.setText("开始")
        else:
            self.timer1.start(100, self)
            self.btn.setText("停止")

    def timerEvent(self, e):
        if self.pv == 100:
            self.timer1.stop()
            self.btn.setText("完成")
        else:
            self.pv += 1
            self.pgb.setValue(self.pv)
Beispiel #18
0
    def initUI(self):
        self.resize(300, 200)
        # 载入进度条控件
        self.verticalLayout = QVBoxLayout()
        self.pgb = QProgressBar(self)
        self.verticalLayout.addWidget(self.pgb, 0, 0, 1, 1)
        #self.pgb.move(50, 50)
        #self.pgb.resize(250, 20)

        # 配置一个值表示进度条的当前进度
        self.pv = 0

        # 申明一个时钟控件
        self.timer1 = QBasicTimer()

        # 设置进度条的范围
        self.pgb.setMinimum(0)
        self.pgb.setMaximum(100)
        self.pgb.setValue(self.pv)
        # 载入按钮
        self.btn = QPushButton("开始", self)
        self.btn.move(50, 100)
        self.btn.clicked.connect(self.myTimerState)
        self.show()
    def createRotableGroupBox(self):
        self.rotableGroupBox = QGroupBox("Rotable Widgets")

        self.rotableWidgets.append(QSpinBox())
        self.rotableWidgets.append(QSlider())
        self.rotableWidgets.append(QDial())
        self.rotableWidgets.append(QProgressBar())
        count = len(self.rotableWidgets)
        for i in range(count):
            self.rotableWidgets[i].valueChanged[int].\
                connect(self.rotableWidgets[(i+1) % count].setValue)

        self.rotableLayout = QGridLayout()
        self.rotableGroupBox.setLayout(self.rotableLayout)

        self.rotateWidgets()
class Window(QWidget):
    """The main application Window."""

    def __init__(self):
        super().__init__()
        self.setWindowTitle("Example")
        self.layout = QHBoxLayout()
        self.layout.setContentsMargins(6, 6, 6, 6)
        self.loading_bar = QProgressBar()
        self.loading_bar.setTextVisible(False)
        self.loading_bar.setFixedHeight(25)
        self.layout.addWidget(self.loading_bar)
        self.quit_btn = FixedWindowsButton("Quit")
        self.quit_btn.setFixedHeight(25)
        self.quit_btn.clicked.connect(self.onQuitBtnClicked)
        self.layout.addWidget(self.quit_btn)
        self.run_btn = FixedWindowsButton("Run")
        self.run_btn.setFixedHeight(25)
        self.run_btn.clicked.connect(self.onRunBtnClicked)
        self.layout.addWidget(self.run_btn)
        self.setLayout(self.layout)

    def onRunBtnClicked(self):
        self.run_btn.setText("Loading...")
        self.run_btn.setEnabled(False)
        self.quit_btn.setEnabled(False)
        self.quit_btn.setHidden(True)
        self.calc = LongRunningProcess()
        self.calc.progress_changed.connect(self.onProgressChanged)
        self.calc.finished.connect(self.onProgressFinished)
        self.calc.start()

    def onQuitBtnClicked(self):
        self.close()

    def onProgressChanged(self, value):
        self.loading_bar.setValue(value)

    def onProgressFinished(self):
        self.quit_btn.setHidden(False)
        self.quit_btn.setEnabled(True)
        self.run_btn.setEnabled(True)
        self.run_btn.setText("Run")
        self.loading_bar.setValue(0)
    def init_ui(self):
        label = QLabel('カプチーノを入れています...', self)
        label.setAlignment(Qt.AlignCenter)

        pbar = QProgressBar(self)
        pbar.setRange(0, DOUNLOAD_COUNT)
        pbar.setTextVisible(False)

        vbox = QVBoxLayout(self)
        vbox.addWidget(label)
        vbox.addWidget(pbar)
        vbox.setContentsMargins(QMargins(16, 16, 16, 16))
        self.setLayout(vbox)

        self.__progress_bar = pbar
Beispiel #22
0
    def buildStatistics(self):
        self.buildWindow(self.window())
        self.statTableMain = QTableView(self.window())
        self.statTableMain.setObjectName(u"statTableMain")
        statTableHeader = QHeaderView(Qt.Orientation.Vertical)
        # self.statTableMain.commitData()
        # https://doc.qt.io/qt-5/sql-model.html
        self.statTableMain.setVerticalHeader(statTableHeader)
        self.statTableMain.setGeometry(self.winw(5), self.winh(10),
                                       self.winw(90), self.winh(80))
        hypixelAPILabel = QLabel("Hypixel API Load:", self.window())
        hypixelAPILabel.setGeometry(self.winw(5), self.winh(90), self.winw(15),
                                    self.winh(5))
        minecraftAPILabel = QLabel("Minecraft API Load:", self.window())
        minecraftAPILabel.setGeometry(self.winw(20), self.winh(90),
                                      self.winw(15), self.winh(5))
        overlayProgressLabel = QLabel("Overlay Load:", self.window())
        overlayProgressLabel.setGeometry(self.winw(35), self.winh(90),
                                         self.winw(15), self.winh(5))
        self.hypixelProgressBar = QProgressBar(self.window())
        self.hypixelProgressBar.setValue(self.hypixelAPILoad)
        self.hypixelProgressBar.setGeometry(self.winw(5), self.winh(95),
                                            self.winw(15), self.winh(3))
        self.minecraftProgressBar = QProgressBar(self.window())
        self.minecraftProgressBar.setValue(self.minecraftAPILoad)
        self.minecraftProgressBar.setGeometry(self.winw(20), self.winh(95),
                                              self.winw(15), self.winh(3))
        self.overlayProgressBar = QProgressBar(self.window())
        self.overlayProgressBar.setValue(self.overlayLoad)
        self.overlayProgressBar.setGeometry(self.winw(35), self.winh(95),
                                            self.winw(15), self.winh(3))
        self.statisticsButton = QPushButton("&Stats", self.window())
        self.statisticsButton.setGeometry(self.winw(5), self.winh(4),
                                          self.winw(10), self.winh(4))
        self.statisticsButton.setObjectName(u"menuButton")
        self.optionsButton = QPushButton("&Options", self.window())
        self.optionsButton.setGeometry(self.winw(16), self.winh(4),
                                       self.winw(10), self.winh(4))
        self.optionsButton.setObjectName(u"menuButton")
        self.exitButton = QPushButton("&Exit", self.window())
        self.exitButton.setGeometry(self.winw(85), self.winh(4), self.winw(10),
                                    self.winh(4))
        self.exitButton.setObjectName(u"menuButton")

        self.statisticsButton.clicked.connect(
            lambda: self.statisticsButtonClick())
        self.optionsButton.clicked.connect(lambda: self.optionsButtonClick())
        self.exitButton.clicked.connect(lambda: self.exitButtonClick())
Beispiel #23
0
        self.movie.stop()

    def paintEvent(self, event: PySide6.QtGui.QPaintEvent) -> None:
        painter = QPainter(self)
        pixmap = self.movie.currentPixmap()
        pixmap = pixmap.scaled(self.my_size)
        painter.drawPixmap(0, 0, pixmap)


if __name__ == '__main__':
    app = QApplication()
    progressbar_value = 30
    path_to_gif = 'loading_gifs/1.gif'

    splash = MovieSplashScreen(path_to_gif)
    progressbar = QProgressBar(splash)
    progressbar.setMaximum(progressbar_value)
    progressbar.setTextVisible(False)
    progressbar.setGeometry(0,
                            splash.my_size.height() - 50,
                            splash.my_size.width(), 20)

    splash.show()

    for i in range(progressbar_value):
        progressbar.setValue(i)
        t = time.time()
        while time.time() < t + 0.1:
            app.processEvents()

    time.sleep(1)
Beispiel #24
0
class Progress(QtWidgets.QWidget):
    pbar: QProgressBar
    index: int
    len: int

    def __init__(self,
                 curr_op: Type[Op] = Shell,
                 len: int = 1,
                 ix=0,
                 parent: Any | None = None):
        super().__init__(parent)
        self.index = ix
        self.lblh = self.toplabel()
        self.lblh = QLabel(self)
        self.lblo = self.oplabel()
        self.opmsg = QLabel("", self)
        self.pbar = QProgressBar(self)
        self.pbar.setValue(0)
        self.len = len
        self.setupUi()

    # @pyqtSlot(Type[Op])
    def upd(self, op_type: Type[Op]) -> None:
        self.curr_op = op_type
        if self.index < self.len:
            self.lblh = self.toplabel()
            self.lblo = self.oplabel()
        else:
            self.lblh.setText(
                f"All {self.len} operations completed successfully.")
            self.close()

    @Slot(str)
    def set_opmsg(self, msg: str) -> None:
        self.opmsg.setText(msg)

    def toplabel(self) -> QLabel:
        return QLabel(
            "Running operations... " + str(self.index + 1) + "of" +
            str(self.len + 1) + ", self", self)

    def oplabel(self) -> QLabel:
        return QLabel("Operation {str(self.curr_op)} in progress", self)

    def set_optype(self, ot: Type[Op]):
        self.curr_op = ot

    @Slot(int)
    def progress(self, val: int):
        self.pbar.setValue(val)
        self.lblh = self.toplabel()
        self.lblo = self.oplabel()

    @Slot(Status)
    def handle_status(
        self,
        st: Status,
    ):
        if st == Status.Canceled:
            self.lblh.setText("Canceled")
            self.lblo.setText(f"{self.curr_op} was canceled by the user.")
        elif st == Status.Done:
            self.lblh.setText("Finished")
            self.lblo.setText(f"{self.curr_op} is complete.")
        elif st == Status.Failed:
            self.lblh.setText("Failed")
            self.lblo.setText(f"{self.curr_op} failed.")
        elif st == Status.InProgress:
            self.lblh = self.toplabel()
            self.lblo = self.oplabel()

    def setupUi(self):
        layout = QVBoxLayout()
        self.timer = QBasicTimer()
        self.pbar = QProgressBar(self)
        self.setWindowTitle("isutils: Executing op (1/1)...")
        self.resize(400, 250)
        layout.addWidget(self.lblh)
        layout.addWidget(self.lblo)
        layout.addWidget(self.pbar)
        self.setLayout(layout)

    def timerEvent(self, e: QTimerEvent):
        if self.timer.isActive() or self.pbar.value() >= 100:
            self.timer.stop()
            self.lblh.setText("finished")
            return
        self.index += 1
        self.set(self.index)

    @Slot()
    def start(self):
        self.timer.start(100, self)

    @Slot()
    def finish(self):
        self.lblh.setText("Finished")
        self.lblo.setText(f"{self.curr_op} is complete.")

    def set(self, amt: int | float):
        self.pbar.setValue(int(amt))
Beispiel #25
0
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        layout = QVBoxLayout()

        self.progress = QProgressBar()

        button = QPushButton("START IT UP")
        button.pressed.connect(self.execute)

        self.status = QLabel("0 workers")

        layout.addWidget(self.progress)
        layout.addWidget(button)
        layout.addWidget(self.status)

        w = QWidget()
        w.setLayout(layout)

        # Dictionary holds the progress of current workers.
        self.worker_progress = {}

        self.setCentralWidget(w)

        self.show()

        self.threadpool = QThreadPool()
        print("Multithreading with maximum %d threads" %
              self.threadpool.maxThreadCount())

        self.timer = QTimer()
        self.timer.setInterval(100)
        self.timer.timeout.connect(self.refresh_progress)
        self.timer.start()

    def execute(self):
        worker = Worker()
        worker.signals.progress.connect(self.update_progress)
        worker.signals.finished.connect(self.cleanup)  # 任务完成后清除对应进度

        # Execute
        self.threadpool.start(worker)

    def cleanup(self, job_id):
        if job_id in self.worker_progress:
            del self.worker_progress[job_id]  # 对完成的任务,删除
            # Update the progress bar if we've removed a value.
            self.refresh_progress()

    def update_progress(self, job_id, progress):
        self.worker_progress[job_id] = progress

    def calculate_progress(self):
        if not self.worker_progress:
            return 0

        return sum(v for v in self.worker_progress.values()) / len(
            self.worker_progress)

    def refresh_progress(self):
        # Calculate total progress.
        progress = self.calculate_progress()
        print(self.worker_progress)
        self.progress.setValue(progress)
        self.status.setText("%d workers" % len(self.worker_progress))
Beispiel #26
0
class MyWidget(QWidget):
    def __init__(self):
        super().__init__()
        # 设置属性
        self.resize(400, 300)
        self.setWindowTitle("测试Qt进度条和aria2的联合")
        # 注册组件
        self.labelUrl = QLabel("下载链接")
        self.lineEditorUrl = QLineEdit(
            "https://download.cnki.net/CAJViewer-x86_64-buildubuntu1604-210401.AppImage"
        )
        self.labelProgress = QLabel("下载进度")
        self.downloadProgress = QProgressBar()
        self.textResult = QTextBrowser()
        self.buttonStart = QPushButton("开始")
        self.buttonPause = QPushButton("暂停")
        self.buttonUnpause = QPushButton("继续")
        self.buttonRemove = QPushButton("移除")
        self.buttonDebug = QPushButton("Debug")
        # 设置组件
        self.lineEditorUrl.setClearButtonEnabled(True)
        self.buttonStart.setIcon(self.style().standardIcon(
            QStyle.SP_MediaPlay))
        self.buttonPause.setIcon(self.style().standardIcon(
            QStyle.SP_MediaPause))
        self.buttonUnpause.setIcon(self.style().standardIcon(
            QStyle.SP_MediaPlay))
        self.buttonRemove.setIcon(self.style().standardIcon(
            QStyle.SP_MediaStop))
        # self.buttonPause.setDisabled(True)
        # self.buttonStop.setDisabled(True)
        # 添加组件
        self.layout = QGridLayout(self)
        self.layout.addWidget(self.labelUrl, 0, 0, 1, 1)
        self.layout.addWidget(self.lineEditorUrl, 0, 1, 1, 5)
        self.layout.addWidget(self.labelProgress, 1, 0, 1, 1)
        self.layout.addWidget(self.downloadProgress, 1, 1, 1, 5)
        self.layout.addWidget(self.textResult, 2, 0, 2, 5)
        self.layout.addWidget(self.buttonStart, 4, 0, 1, 1)
        self.layout.addWidget(self.buttonPause, 4, 1, 1, 1)
        self.layout.addWidget(self.buttonUnpause, 4, 2, 1, 1)
        self.layout.addWidget(self.buttonRemove, 4, 3, 1, 1)
        self.layout.addWidget(self.buttonDebug, 4, 4, 1, 1)
        # 添加组件功能

        # class函数

    @Slot(str)
    def updateProgress(self, value):
        self.downloadProgress.setMaximum(int(value['totalLength']))
        self.downloadProgress.setValue(
            int(value['files'][0]['completedLength']))
        if value["status"] == "complete":
            self.downloadProgress.setValue(int(value['totalLength']))

    shutdown_aria2 = Signal()

    @Slot()
    def clearProgress(self):
        self.downloadProgress.setValue(0)

    def closeEvent(self, event):
        if QMessageBox.question(self, "退出程序", "确定退出吗?") == QMessageBox.No:
            event.ignore()
        else:
            event.accept()
            self.shutdown_aria2.emit()
Beispiel #27
0
    def setupUi(self):
        self.centralwidget = QWidget(self)
        with open(resource_path('style.css'), 'r') as file:
            self.centralwidget.setStyleSheet(file.read())
        self.appswidget = QWidget(self.centralwidget)
        self.appswidget.setGeometry(50, 0, 490, 470)
        self.appswidget.setProperty('class', 'appswidget')
        self.sidebar = QFrame(self.centralwidget)
        self.sidebar.setFrameShape(QFrame.StyledPanel)
        self.sidebar.setGeometry(0, 0, 50, 470)
        self.sidebar.setProperty('class', 'sidebar')

        self.refresh_btn = QPushButton(self.sidebar)
        self.refresh_btn.setGeometry(QRect(0, 0, 51, 51))
        self.refresh_btn.setProperty('class', 'sidebar_btns')
        self.refresh_btn.setIcon(QIcon(':/icon/refresh_icon.png'))
        self.refresh_btn.setIconSize(QSize(24, 24))
        self.refresh_bind = QShortcut(QKeySequence('Ctrl+R'), self)

        self.store_btn = QPushButton(self.sidebar)
        self.store_btn.setGeometry(QRect(0, 51, 51, 51))
        self.store_btn.setProperty('class', 'sidebar_btns')
        self.store_btn.setIcon(QIcon(':/icon/store_icon.png'))
        self.store_btn.setIconSize(QSize(24, 24))
        self.store_bind = QShortcut(QKeySequence('Ctrl+S'), self)

        self.homepage_btn = QPushButton(self.sidebar)
        self.homepage_btn.setGeometry(QRect(0, 102, 51, 51))
        self.homepage_btn.setProperty('class', 'sidebar_btns')
        self.homepage_btn.setIcon(QIcon(':/icon/github_icon.png'))
        self.homepage_btn.setIconSize(QSize(24, 24))
        self.homepage_bind = QShortcut(QKeySequence('Ctrl+G'), self)

        self.about_btn = QPushButton(self.sidebar)
        self.about_btn.setGeometry(QRect(0, 153, 51, 51))
        self.about_btn.setProperty('class', 'sidebar_btns')
        self.about_btn.setIcon(QIcon(':/icon/about_icon.png'))
        self.about_btn.setIconSize(QSize(24, 24))
        self.about_bind = QShortcut(QKeySequence('Ctrl+A'), self)

        self.quit_btn = QPushButton(self.sidebar)
        self.quit_btn.setGeometry(QRect(0, 420, 51, 51))
        self.quit_btn.setProperty('class', 'sidebar_btns_quit')
        self.quit_btn.setIcon(QIcon(':/icon/quit_icon.png'))
        self.quit_btn.setIconSize(QSize(24, 24))
        self.quit_bind = QShortcut(QKeySequence('Ctrl+Q'), self)

        self.font = QFont()
        self.font.setPointSize(8)
        self.font.setStyleStrategy(QFont.PreferAntialias)

        self.label_refresh = QLabel(self.appswidget)
        self.label_refresh.setFont(self.font)
        self.label_refresh.setGeometry(QRect(20, 10, 441, 15))

        self.label_info = QLabel(self.appswidget)
        self.label_info.setFont(self.font)
        self.label_info.setGeometry(QRect(20, 10, 441, 30))

        self.progressbar = QProgressBar(self.appswidget)
        self.progressbar.setGeometry(QRect(20, 30, 441, 20))

        self.layout_widget_checkboxes = QWidget(self.appswidget)
        self.layout_widget_checkboxes.setGeometry(QRect(20, 55, 155, 311))
        self.layout_checkboxes = QVBoxLayout(self.layout_widget_checkboxes)
        self.layout_checkboxes.setContentsMargins(0, 0, 0, 0)

        self.layout_widget_checkboxes_2 = QWidget(self.appswidget)
        self.layout_widget_checkboxes_2.setGeometry(QRect(175, 55, 155, 311))
        self.layout_checkboxes_2 = QVBoxLayout(self.layout_widget_checkboxes_2)
        self.layout_checkboxes_2.setContentsMargins(0, 0, 0, 0)

        self.layout_widget_checkboxes_3 = QWidget(self.appswidget)
        self.layout_widget_checkboxes_3.setGeometry(QRect(330, 55, 155, 311))
        self.layout_checkboxes_3 = QVBoxLayout(self.layout_widget_checkboxes_3)
        self.layout_checkboxes_3.setContentsMargins(0, 0, 0, 0)

        self.layout_widget_labels = QWidget(self.appswidget)
        self.layout_widget_labels.setGeometry(QRect(20, 390, 350, 16))
        self.layout_labels = QHBoxLayout(self.layout_widget_labels)
        self.layout_labels.setContentsMargins(0, 0, 0, 0)
        self.label_space = QLabel(self.appswidget)
        self.label_space.setFont(self.font)
        self.layout_labels.addWidget(self.label_space)
        self.label_size = QLabel(self.appswidget)
        self.label_size.setFont(self.font)
        self.layout_labels.addWidget(self.label_size)

        self.layout_widget_buttons = QWidget(self.appswidget)
        self.layout_widget_buttons.setGeometry(QRect(20, 420, 454, 31))
        self.layout_buttons = QHBoxLayout(self.layout_widget_buttons)
        self.layout_buttons.setContentsMargins(0, 0, 0, 0)
        self.button_select_all = QPushButton(self.layout_widget_buttons)
        self.button_select_all.setIcon(QIcon(':/icon/check_icon.png'))
        self.button_select_all.setIconSize(QSize(18, 18))
        self.button_select_all.setLayoutDirection(Qt.RightToLeft)
        self.layout_buttons.addWidget(self.button_select_all)
        self.button_select_all.setMinimumSize(100, 30)
        self.button_select_all.setProperty('class', 'Aqua')
        self.button_deselect_all = QPushButton(self.layout_widget_buttons)
        self.button_deselect_all.setIcon(QIcon(':/icon/cancel_icon.png'))
        self.button_deselect_all.setIconSize(QSize(18, 18))
        self.button_deselect_all.setLayoutDirection(Qt.RightToLeft)
        self.layout_buttons.addWidget(self.button_deselect_all)
        self.button_deselect_all.setMinimumSize(100, 30)
        self.button_deselect_all.setProperty('class', 'Aqua')
        self.layout_buttons.addStretch()
        self.button_uninstall = QPushButton(self.layout_widget_buttons)
        self.button_uninstall.setIcon(QIcon(':/icon/trash_icon.png'))
        self.button_uninstall.setIconSize(QSize(18, 18))
        self.button_uninstall.setLayoutDirection(Qt.RightToLeft)
        self.layout_buttons.addWidget(self.button_uninstall)
        self.button_uninstall.setMinimumSize(100, 30)
        self.button_uninstall.setProperty('class', 'Grapefruit')

        self.setCentralWidget(self.centralwidget)
        self.retranslateUi()
        QMetaObject.connectSlotsByName(self)
Beispiel #28
0
class Ui_MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowIcon(QIcon(resource_path('icon.ico')))
        self.setFixedSize(540, 470)

    def setupUi(self):
        self.centralwidget = QWidget(self)
        with open(resource_path('style.css'), 'r') as file:
            self.centralwidget.setStyleSheet(file.read())
        self.appswidget = QWidget(self.centralwidget)
        self.appswidget.setGeometry(50, 0, 490, 470)
        self.appswidget.setProperty('class', 'appswidget')
        self.sidebar = QFrame(self.centralwidget)
        self.sidebar.setFrameShape(QFrame.StyledPanel)
        self.sidebar.setGeometry(0, 0, 50, 470)
        self.sidebar.setProperty('class', 'sidebar')

        self.refresh_btn = QPushButton(self.sidebar)
        self.refresh_btn.setGeometry(QRect(0, 0, 51, 51))
        self.refresh_btn.setProperty('class', 'sidebar_btns')
        self.refresh_btn.setIcon(QIcon(':/icon/refresh_icon.png'))
        self.refresh_btn.setIconSize(QSize(24, 24))
        self.refresh_bind = QShortcut(QKeySequence('Ctrl+R'), self)

        self.store_btn = QPushButton(self.sidebar)
        self.store_btn.setGeometry(QRect(0, 51, 51, 51))
        self.store_btn.setProperty('class', 'sidebar_btns')
        self.store_btn.setIcon(QIcon(':/icon/store_icon.png'))
        self.store_btn.setIconSize(QSize(24, 24))
        self.store_bind = QShortcut(QKeySequence('Ctrl+S'), self)

        self.homepage_btn = QPushButton(self.sidebar)
        self.homepage_btn.setGeometry(QRect(0, 102, 51, 51))
        self.homepage_btn.setProperty('class', 'sidebar_btns')
        self.homepage_btn.setIcon(QIcon(':/icon/github_icon.png'))
        self.homepage_btn.setIconSize(QSize(24, 24))
        self.homepage_bind = QShortcut(QKeySequence('Ctrl+G'), self)

        self.about_btn = QPushButton(self.sidebar)
        self.about_btn.setGeometry(QRect(0, 153, 51, 51))
        self.about_btn.setProperty('class', 'sidebar_btns')
        self.about_btn.setIcon(QIcon(':/icon/about_icon.png'))
        self.about_btn.setIconSize(QSize(24, 24))
        self.about_bind = QShortcut(QKeySequence('Ctrl+A'), self)

        self.quit_btn = QPushButton(self.sidebar)
        self.quit_btn.setGeometry(QRect(0, 420, 51, 51))
        self.quit_btn.setProperty('class', 'sidebar_btns_quit')
        self.quit_btn.setIcon(QIcon(':/icon/quit_icon.png'))
        self.quit_btn.setIconSize(QSize(24, 24))
        self.quit_bind = QShortcut(QKeySequence('Ctrl+Q'), self)

        self.font = QFont()
        self.font.setPointSize(8)
        self.font.setStyleStrategy(QFont.PreferAntialias)

        self.label_refresh = QLabel(self.appswidget)
        self.label_refresh.setFont(self.font)
        self.label_refresh.setGeometry(QRect(20, 10, 441, 15))

        self.label_info = QLabel(self.appswidget)
        self.label_info.setFont(self.font)
        self.label_info.setGeometry(QRect(20, 10, 441, 30))

        self.progressbar = QProgressBar(self.appswidget)
        self.progressbar.setGeometry(QRect(20, 30, 441, 20))

        self.layout_widget_checkboxes = QWidget(self.appswidget)
        self.layout_widget_checkboxes.setGeometry(QRect(20, 55, 155, 311))
        self.layout_checkboxes = QVBoxLayout(self.layout_widget_checkboxes)
        self.layout_checkboxes.setContentsMargins(0, 0, 0, 0)

        self.layout_widget_checkboxes_2 = QWidget(self.appswidget)
        self.layout_widget_checkboxes_2.setGeometry(QRect(175, 55, 155, 311))
        self.layout_checkboxes_2 = QVBoxLayout(self.layout_widget_checkboxes_2)
        self.layout_checkboxes_2.setContentsMargins(0, 0, 0, 0)

        self.layout_widget_checkboxes_3 = QWidget(self.appswidget)
        self.layout_widget_checkboxes_3.setGeometry(QRect(330, 55, 155, 311))
        self.layout_checkboxes_3 = QVBoxLayout(self.layout_widget_checkboxes_3)
        self.layout_checkboxes_3.setContentsMargins(0, 0, 0, 0)

        self.layout_widget_labels = QWidget(self.appswidget)
        self.layout_widget_labels.setGeometry(QRect(20, 390, 350, 16))
        self.layout_labels = QHBoxLayout(self.layout_widget_labels)
        self.layout_labels.setContentsMargins(0, 0, 0, 0)
        self.label_space = QLabel(self.appswidget)
        self.label_space.setFont(self.font)
        self.layout_labels.addWidget(self.label_space)
        self.label_size = QLabel(self.appswidget)
        self.label_size.setFont(self.font)
        self.layout_labels.addWidget(self.label_size)

        self.layout_widget_buttons = QWidget(self.appswidget)
        self.layout_widget_buttons.setGeometry(QRect(20, 420, 454, 31))
        self.layout_buttons = QHBoxLayout(self.layout_widget_buttons)
        self.layout_buttons.setContentsMargins(0, 0, 0, 0)
        self.button_select_all = QPushButton(self.layout_widget_buttons)
        self.button_select_all.setIcon(QIcon(':/icon/check_icon.png'))
        self.button_select_all.setIconSize(QSize(18, 18))
        self.button_select_all.setLayoutDirection(Qt.RightToLeft)
        self.layout_buttons.addWidget(self.button_select_all)
        self.button_select_all.setMinimumSize(100, 30)
        self.button_select_all.setProperty('class', 'Aqua')
        self.button_deselect_all = QPushButton(self.layout_widget_buttons)
        self.button_deselect_all.setIcon(QIcon(':/icon/cancel_icon.png'))
        self.button_deselect_all.setIconSize(QSize(18, 18))
        self.button_deselect_all.setLayoutDirection(Qt.RightToLeft)
        self.layout_buttons.addWidget(self.button_deselect_all)
        self.button_deselect_all.setMinimumSize(100, 30)
        self.button_deselect_all.setProperty('class', 'Aqua')
        self.layout_buttons.addStretch()
        self.button_uninstall = QPushButton(self.layout_widget_buttons)
        self.button_uninstall.setIcon(QIcon(':/icon/trash_icon.png'))
        self.button_uninstall.setIconSize(QSize(18, 18))
        self.button_uninstall.setLayoutDirection(Qt.RightToLeft)
        self.layout_buttons.addWidget(self.button_uninstall)
        self.button_uninstall.setMinimumSize(100, 30)
        self.button_uninstall.setProperty('class', 'Grapefruit')

        self.setCentralWidget(self.centralwidget)
        self.retranslateUi()
        QMetaObject.connectSlotsByName(self)

    def retranslateUi(self):
        QToolTip.setFont(self.font)

        self.setWindowTitle(QCoreApplication.translate("Title", "PyDebloatX"))
        self.label_info.setText(QCoreApplication.translate("Label", ""))

        self.app_name_list = list(
            (  # Convert tuple to list, because lupdate ignores initial lists
                QCoreApplication.translate("AppName", "3D Builder"),
                QCoreApplication.translate("AppName", "3D Viewer"),
                QCoreApplication.translate("AppName", "Alarms and Clock"),
                QCoreApplication.translate("AppName", "Calculator"),
                QCoreApplication.translate("AppName", "Calendar and Mail"),
                QCoreApplication.translate("AppName", "Camera"),
                QCoreApplication.translate("AppName", "Feedback Hub"),
                QCoreApplication.translate("AppName", "Get Help"),
                QCoreApplication.translate("AppName", "Groove Music"),
                QCoreApplication.translate("AppName", "Maps"),
                QCoreApplication.translate("AppName", "Messaging"),
                QCoreApplication.translate("AppName", "Mixed Reality Portal"),
                QCoreApplication.translate("AppName", "Mobile Plans"),
                QCoreApplication.translate("AppName", "Money"),
                QCoreApplication.translate("AppName", "Movies && TV"),
                QCoreApplication.translate("AppName", "News"),
                QCoreApplication.translate("AppName", "Office"),
                QCoreApplication.translate("AppName", "OneNote"),
                QCoreApplication.translate("AppName", "Paint 3D"),
                QCoreApplication.translate("AppName", "People"),
                QCoreApplication.translate("AppName", "Photos"),
                QCoreApplication.translate("AppName", "Print 3D"),
                QCoreApplication.translate("AppName", "Skype"),
                QCoreApplication.translate("AppName", "Snip && Sketch"),
                QCoreApplication.translate("AppName", "Solitaire"),
                QCoreApplication.translate("AppName", "Sports"),
                QCoreApplication.translate("AppName", "Spotify"),
                QCoreApplication.translate("AppName", "Sticky Notes"),
                QCoreApplication.translate("AppName", "Tips"),
                QCoreApplication.translate("AppName", "Translator"),
                QCoreApplication.translate("AppName", "Voice Recorder"),
                QCoreApplication.translate("AppName", "Weather"),
                QCoreApplication.translate("AppName", "Xbox"),
                QCoreApplication.translate("AppName", "Xbox Game Bar"),
                QCoreApplication.translate("AppName", "Your Phone")))
        self.tooltip_list = list((
            QCoreApplication.translate(
                "ToolTip", "View, create, and personalize 3D objects."),
            QCoreApplication.translate(
                "ToolTip", "View 3D models and animations in real-time."),
            QCoreApplication.translate(
                "ToolTip",
                "A combination of alarm clock, world clock, timer, and stopwatch."
            ),
            QCoreApplication.translate(
                "ToolTip",
                "A calculator that includes standard, scientific, and programmer modes, as well as a unit converter."
            ),
            QCoreApplication.translate(
                "ToolTip",
                "Stay up to date with email and schedule managing."),
            QCoreApplication.translate(
                "ToolTip", "Point and shoot to take pictures on Windows 10."),
            QCoreApplication.translate(
                "ToolTip",
                "Provide feedback about Windows and apps by sharing suggestions or problems."
            ),
            QCoreApplication.translate(
                "ToolTip",
                "Provide a way to ask a question and get recommended solutions or contact assisted support."
            ),
            QCoreApplication.translate(
                "ToolTip",
                "Listen to music on Windows, iOS, and Android devices."),
            QCoreApplication.translate(
                "ToolTip",
                "Search for places to get directions, business info, and reviews."
            ),
            QCoreApplication.translate(
                "ToolTip",
                "Quick, reliable SMS, MMS and RCS messaging from your phone."),
            QCoreApplication.translate(
                "ToolTip",
                "Discover Windows Mixed Reality and dive into more than 3,000 games and VR experiences from Steam VR and Microsoft Store."
            ),
            QCoreApplication.translate(
                "ToolTip",
                "Sign up for a data plan and connect with mobile operators in your area. You will need a supported SIM card."
            ),
            QCoreApplication.translate(
                "ToolTip",
                "Finance calculators, currency exchange rates and commodity prices from around the world."
            ),
            QCoreApplication.translate(
                "ToolTip",
                "All your movies and TV shows, all in one place, on all your devices."
            ),
            QCoreApplication.translate(
                "ToolTip",
                "Deliver breaking news and trusted, in-depth reporting from the world\'s best journalists."
            ),
            QCoreApplication.translate(
                "ToolTip",
                "Find all your Office apps and files in one place."),
            QCoreApplication.translate(
                "ToolTip",
                "Digital notebook for capturing and organizing everything across your devices."
            ),
            QCoreApplication.translate(
                "ToolTip",
                "Make 2D masterpieces or 3D models that you can play with from all angles."
            ),
            QCoreApplication.translate(
                "ToolTip",
                "Connect with all your friends, family, colleagues, and acquaintances in one place."
            ),
            QCoreApplication.translate(
                "ToolTip",
                "View and edit your photos and videos, make movies, and create albums."
            ),
            QCoreApplication.translate(
                "ToolTip",
                "Quickly and easily prepare objects for 3D printing on your PC."
            ),
            QCoreApplication.translate(
                "ToolTip",
                "Instant message, voice or video call application."),
            QCoreApplication.translate(
                "ToolTip",
                "Quickly annotate screenshots, photos and other images and save, paste or share with other apps."
            ),
            QCoreApplication.translate(
                "ToolTip",
                "Solitaire is one of the most played computer card games of all time."
            ),
            QCoreApplication.translate(
                "ToolTip",
                "Live scores and in-depth game experiences for more than 150 leagues."
            ),
            QCoreApplication.translate(
                "ToolTip",
                "Play your favorite songs and albums free on Windows 10 with Spotify."
            ),
            QCoreApplication.translate(
                "ToolTip",
                "Create notes, type, ink or add a picture, add text formatting, or stick them to the desktop."
            ),
            QCoreApplication.translate(
                "ToolTip",
                "Provide users with information and tips about operating system features."
            ),
            QCoreApplication.translate(
                "ToolTip",
                "Translate text and speech, have translated conversations, and even download AI-powered language packs to use offline."
            ),
            QCoreApplication.translate(
                "ToolTip",
                "Record sounds, lectures, interviews, and other events."),
            QCoreApplication.translate(
                "ToolTip",
                "Latest weather conditions, accurate 10-day and hourly forecasts."
            ),
            QCoreApplication.translate(
                "ToolTip",
                "Browse the catalogue, view recommendations, and discover PC games with Xbox Game Pass."
            ),
            QCoreApplication.translate(
                "ToolTip",
                "Instant access to widgets for screen capture and sharing, and chatting with Xbox friends."
            ),
            QCoreApplication.translate(
                "ToolTip",
                "Link your Android phone and PC to view and reply to text messages, access mobile apps, and receive notifications."
            )))
        self.app_data_list = [{
            "name": "*Microsoft.3DBuilder*",
            "link": "/?PFN=Microsoft.3DBuilder_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*Microsoft.Microsoft3DViewer*",
            "link": "/?PFN=Microsoft.Microsoft3DViewer_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*Microsoft.WindowsAlarms*",
            "link": "/?PFN=Microsoft.WindowsAlarms_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*Microsoft.WindowsCalculator*",
            "link": "/?PFN=Microsoft.WindowsCalculator_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*microsoft.windowscommunicationsapps*",
            "link": "/?PFN=Microsoft.windowscommunicationsapps_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*Microsoft.WindowsCamera*",
            "link": "/?PFN=Microsoft.WindowsCamera_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*Microsoft.WindowsFeedbackHub*",
            "link": "/?PFN=Microsoft.WindowsFeedbackHub_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*Microsoft.GetHelp*",
            "link": "/?PFN=Microsoft.Gethelp_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*Microsoft.ZuneMusic*",
            "link": "/?PFN=Microsoft.ZuneMusic_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*Microsoft.WindowsMaps*",
            "link": "/?PFN=Microsoft.WindowsMaps_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*Microsoft.Messaging*",
            "link": "/?PFN=Microsoft.Messaging_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*Microsoft.MixedReality.Portal*",
            "link": "/?PFN=Microsoft.MixedReality.Portal_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*Microsoft.OneConnect*",
            "link": "/?PFN=Microsoft.OneConnect_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*Microsoft.BingFinance*",
            "link": "/?PFN=Microsoft.BingFinance_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*Microsoft.ZuneVideo*",
            "link": "/?PFN=Microsoft.ZuneVideo_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*Microsoft.BingNews*",
            "link": "/?PFN=Microsoft.BingNews_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*Microsoft.MicrosoftOfficeHub*",
            "link": "/?PFN=Microsoft.MicrosoftOfficeHub_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*Microsoft.Office.OneNote*",
            "link": "/?PFN=Microsoft.Office.OneNote_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*Microsoft.MSPaint*",
            "link": "/?PFN=Microsoft.MSPaint_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*Microsoft.People*",
            "link": "/?PFN=Microsoft.People_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*Microsoft.Windows.Photos*",
            "link": "/?PFN=Microsoft.Windows.Photos_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*Microsoft.Print3D*",
            "link": "/?PFN=Microsoft.Print3D_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*Microsoft.SkypeApp*",
            "link": "/?PFN=Microsoft.SkypeApp_kzf8qxf38zg5c",
            "size": 0
        }, {
            "name": "*Microsoft.ScreenSketch*",
            "link": "/?PFN=Microsoft.ScreenSketch_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*Microsoft.MicrosoftSolitaireCollection*",
            "link":
            "/?PFN=Microsoft.MicrosoftSolitaireCollection_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*Microsoft.BingSports*",
            "link": "/?PFN=Microsoft.BingSports_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*SpotifyAB.SpotifyMusic*",
            "link": "/?PFN=SpotifyAB.SpotifyMusic_zpdnekdrzrea0",
            "size": 0
        }, {
            "name": "*Microsoft.MicrosoftStickyNotes*",
            "link": "/?PFN=Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*Microsoft.Getstarted*",
            "link": "/?PFN=Microsoft.Getstarted_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*Microsoft.BingTranslator*",
            "link": "/?PFN=Microsoft.BingTranslator_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*Microsoft.WindowsSoundRecorder*",
            "link": "/?PFN=Microsoft.WindowsSoundRecorder_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*Microsoft.BingWeather*",
            "link": "/?PFN=Microsoft.BingWeather_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*Microsoft.GamingApp*",
            "link": "/?PFN=Microsoft.GamingApp_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*Xbox*",
            "link": "/?PFN=Microsoft.XboxGameOverlay_8wekyb3d8bbwe",
            "size": 0
        }, {
            "name": "*Microsoft.YourPhone*",
            "link": "/?PFN=Microsoft.YourPhone_8wekyb3d8bbwe",
            "size": 0
        }]

        if version.parse(platform.version()) >= version.parse("10.0.19041"):
            insort(self.app_name_list,
                   QCoreApplication.translate("AppName", "Cortana"))
            cortana_index = self.app_name_list.index("Cortana")
            self.tooltip_list.insert(
                cortana_index,
                QCoreApplication.translate("ToolTip",
                                           "Personal intelligence assistant."))
            self.app_data_list.insert(
                cortana_index, {
                    "name": "*Microsoft.549981C3F5F10*",
                    "link": "/?PFN=Microsoft.549981C3F5F10_8wekyb3d8bbwe",
                    "size": 0
                })

        self.checkbox_list = []
        for i, _ in enumerate(self.app_name_list):
            self.checkbox_list.append(QCheckBox())
            if i % 3 == 2:
                self.layout_checkboxes_3.addWidget(self.checkbox_list[i])
            elif i % 3 == 1:
                self.layout_checkboxes_2.addWidget(self.checkbox_list[i])
            else:
                self.layout_checkboxes.addWidget(self.checkbox_list[i])

        self.apps_dict = {}
        for i, checkbox in enumerate(self.checkbox_list):
            checkbox.setText(self.app_name_list[i])
            checkbox.setToolTip(self.tooltip_list[i])
            checkbox.setFont(self.font)
            self.apps_dict[checkbox] = self.app_data_list[i]

        self.label_space.setText(
            QCoreApplication.translate("Label", "Total amount of disk space:"))
        self.label_size.setText(QCoreApplication.translate("Label", "0 MB"))

        self.button_select_all.setText(
            QCoreApplication.translate("Button", "Select All"))
        self.button_deselect_all.setText(
            QCoreApplication.translate("Button", "Deselect All"))

        self.button_uninstall.setText(
            QCoreApplication.translate("Button", "Uninstall"))
Beispiel #29
0
    def __init__(self, language):
        QMainWindow.__init__(self, None)
        self.setupUi(self)

        self.currentLanguage = language
        self.current_index = None  # this is used in onOperationContextMenu() to track item for menu

        self.ledger = Ledger()
        self.downloader = QuoteDownloader()
        self.taxes = TaxesRus()
        self.statements = StatementLoader()
        self.backup = JalBackup(self, get_dbfilename(get_app_path()))
        self.estimator = None
        self.price_chart = None

        self.actionImportSlipRU.setEnabled(
            dependency_present(['pyzbar', 'PIL']))

        self.actionAbout = QAction(text=self.tr("About"), parent=self)
        self.MainMenu.addAction(self.actionAbout)

        self.langGroup = QActionGroup(self.menuLanguage)
        self.createLanguageMenu()

        self.statementGroup = QActionGroup(self.menuStatement)
        self.createStatementsImportMenu()

        # Set icons
        self.setWindowIcon(load_icon("jal.png"))
        self.NewOperationBtn.setIcon(load_icon("new.png"))
        self.CopyOperationBtn.setIcon(load_icon("copy.png"))
        self.DeleteOperationBtn.setIcon(load_icon("delete.png"))

        # Operations view context menu
        self.contextMenu = QMenu(self.OperationsTableView)
        self.actionReconcile = QAction(load_icon("reconcile.png"),
                                       self.tr("Reconcile"), self)
        self.actionCopy = QAction(load_icon("copy.png"), self.tr("Copy"), self)
        self.actionDelete = QAction(load_icon("delete.png"), self.tr("Delete"),
                                    self)
        self.contextMenu.addAction(self.actionReconcile)
        self.contextMenu.addSeparator()
        self.contextMenu.addAction(self.actionCopy)
        self.contextMenu.addAction(self.actionDelete)

        # Customize Status bar and logs
        self.ProgressBar = QProgressBar(self)
        self.StatusBar.addWidget(self.ProgressBar)
        self.ProgressBar.setVisible(False)
        self.ledger.setProgressBar(self, self.ProgressBar)
        self.NewLogEventLbl = QLabel(self)
        self.StatusBar.addWidget(self.NewLogEventLbl)
        self.Logs.setNotificationLabel(self.NewLogEventLbl)
        self.Logs.setFormatter(
            logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
        self.logger = logging.getLogger()
        self.logger.addHandler(self.Logs)
        log_level = os.environ.get('LOGLEVEL', 'INFO').upper()
        self.logger.setLevel(log_level)

        # Setup reports tab
        self.reports = Reports(self.ReportTableView, self.ReportTreeView)

        # Customize UI configuration
        self.balances_model = BalancesModel(self.BalancesTableView)
        self.BalancesTableView.setModel(self.balances_model)
        self.balances_model.configureView()

        self.holdings_model = HoldingsModel(self.HoldingsTableView)
        self.HoldingsTableView.setModel(self.holdings_model)
        self.holdings_model.configureView()
        self.HoldingsTableView.setContextMenuPolicy(Qt.CustomContextMenu)

        self.operations_model = OperationsModel(self.OperationsTableView)
        self.OperationsTableView.setModel(self.operations_model)
        self.operations_model.configureView()
        self.OperationsTableView.setContextMenuPolicy(Qt.CustomContextMenu)

        self.connect_signals_and_slots()

        self.NewOperationMenu = QMenu()
        for i in range(self.OperationsTabs.count()):
            if hasattr(self.OperationsTabs.widget(i), "isCustom"):
                self.OperationsTabs.widget(i).dbUpdated.connect(
                    self.ledger.rebuild)
                self.OperationsTabs.widget(i).dbUpdated.connect(
                    self.operations_model.refresh)
                self.NewOperationMenu.addAction(
                    self.OperationsTabs.widget(i).name,
                    partial(self.createOperation, i))
        self.NewOperationBtn.setMenu(self.NewOperationMenu)

        # Setup balance and holdings parameters
        current_time = QDateTime.currentDateTime()
        current_time.setTimeSpec(
            Qt.UTC)  # We use UTC everywhere so need to force TZ info
        self.BalanceDate.setDateTime(current_time)
        self.BalancesCurrencyCombo.setIndex(
            JalSettings().getValue('BaseCurrency'))
        self.HoldingsDate.setDateTime(current_time)
        self.HoldingsCurrencyCombo.setIndex(
            JalSettings().getValue('BaseCurrency'))

        self.OperationsTabs.setCurrentIndex(TransactionType.NA)
        self.OperationsTableView.selectRow(0)
        self.OnOperationsRangeChange(0)
Beispiel #30
0
class MainWindow(QMainWindow, Ui_JAL_MainWindow):
    def __init__(self, language):
        QMainWindow.__init__(self, None)
        self.setupUi(self)

        self.currentLanguage = language
        self.current_index = None  # this is used in onOperationContextMenu() to track item for menu

        self.ledger = Ledger()
        self.downloader = QuoteDownloader()
        self.taxes = TaxesRus()
        self.statements = StatementLoader()
        self.backup = JalBackup(self, get_dbfilename(get_app_path()))
        self.estimator = None
        self.price_chart = None

        self.actionImportSlipRU.setEnabled(
            dependency_present(['pyzbar', 'PIL']))

        self.actionAbout = QAction(text=self.tr("About"), parent=self)
        self.MainMenu.addAction(self.actionAbout)

        self.langGroup = QActionGroup(self.menuLanguage)
        self.createLanguageMenu()

        self.statementGroup = QActionGroup(self.menuStatement)
        self.createStatementsImportMenu()

        # Set icons
        self.setWindowIcon(load_icon("jal.png"))
        self.NewOperationBtn.setIcon(load_icon("new.png"))
        self.CopyOperationBtn.setIcon(load_icon("copy.png"))
        self.DeleteOperationBtn.setIcon(load_icon("delete.png"))

        # Operations view context menu
        self.contextMenu = QMenu(self.OperationsTableView)
        self.actionReconcile = QAction(load_icon("reconcile.png"),
                                       self.tr("Reconcile"), self)
        self.actionCopy = QAction(load_icon("copy.png"), self.tr("Copy"), self)
        self.actionDelete = QAction(load_icon("delete.png"), self.tr("Delete"),
                                    self)
        self.contextMenu.addAction(self.actionReconcile)
        self.contextMenu.addSeparator()
        self.contextMenu.addAction(self.actionCopy)
        self.contextMenu.addAction(self.actionDelete)

        # Customize Status bar and logs
        self.ProgressBar = QProgressBar(self)
        self.StatusBar.addWidget(self.ProgressBar)
        self.ProgressBar.setVisible(False)
        self.ledger.setProgressBar(self, self.ProgressBar)
        self.NewLogEventLbl = QLabel(self)
        self.StatusBar.addWidget(self.NewLogEventLbl)
        self.Logs.setNotificationLabel(self.NewLogEventLbl)
        self.Logs.setFormatter(
            logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
        self.logger = logging.getLogger()
        self.logger.addHandler(self.Logs)
        log_level = os.environ.get('LOGLEVEL', 'INFO').upper()
        self.logger.setLevel(log_level)

        # Setup reports tab
        self.reports = Reports(self.ReportTableView, self.ReportTreeView)

        # Customize UI configuration
        self.balances_model = BalancesModel(self.BalancesTableView)
        self.BalancesTableView.setModel(self.balances_model)
        self.balances_model.configureView()

        self.holdings_model = HoldingsModel(self.HoldingsTableView)
        self.HoldingsTableView.setModel(self.holdings_model)
        self.holdings_model.configureView()
        self.HoldingsTableView.setContextMenuPolicy(Qt.CustomContextMenu)

        self.operations_model = OperationsModel(self.OperationsTableView)
        self.OperationsTableView.setModel(self.operations_model)
        self.operations_model.configureView()
        self.OperationsTableView.setContextMenuPolicy(Qt.CustomContextMenu)

        self.connect_signals_and_slots()

        self.NewOperationMenu = QMenu()
        for i in range(self.OperationsTabs.count()):
            if hasattr(self.OperationsTabs.widget(i), "isCustom"):
                self.OperationsTabs.widget(i).dbUpdated.connect(
                    self.ledger.rebuild)
                self.OperationsTabs.widget(i).dbUpdated.connect(
                    self.operations_model.refresh)
                self.NewOperationMenu.addAction(
                    self.OperationsTabs.widget(i).name,
                    partial(self.createOperation, i))
        self.NewOperationBtn.setMenu(self.NewOperationMenu)

        # Setup balance and holdings parameters
        current_time = QDateTime.currentDateTime()
        current_time.setTimeSpec(
            Qt.UTC)  # We use UTC everywhere so need to force TZ info
        self.BalanceDate.setDateTime(current_time)
        self.BalancesCurrencyCombo.setIndex(
            JalSettings().getValue('BaseCurrency'))
        self.HoldingsDate.setDateTime(current_time)
        self.HoldingsCurrencyCombo.setIndex(
            JalSettings().getValue('BaseCurrency'))

        self.OperationsTabs.setCurrentIndex(TransactionType.NA)
        self.OperationsTableView.selectRow(0)
        self.OnOperationsRangeChange(0)

    def connect_signals_and_slots(self):
        self.actionExit.triggered.connect(QApplication.instance().quit)
        self.actionAbout.triggered.connect(self.showAboutWindow)
        self.langGroup.triggered.connect(self.onLanguageChanged)
        self.statementGroup.triggered.connect(self.statements.load)
        self.actionReconcile.triggered.connect(
            self.reconcileAtCurrentOperation)
        self.action_Load_quotes.triggered.connect(
            partial(self.downloader.showQuoteDownloadDialog, self))
        self.actionImportSlipRU.triggered.connect(self.importSlip)
        self.actionBackup.triggered.connect(self.backup.create)
        self.actionRestore.triggered.connect(self.backup.restore)
        self.action_Re_build_Ledger.triggered.connect(
            partial(self.ledger.showRebuildDialog, self))
        self.actionAccountTypes.triggered.connect(
            partial(self.onDataDialog, "account_types"))
        self.actionAccounts.triggered.connect(
            partial(self.onDataDialog, "accounts"))
        self.actionAssets.triggered.connect(
            partial(self.onDataDialog, "assets"))
        self.actionPeers.triggered.connect(partial(self.onDataDialog,
                                                   "agents"))
        self.actionCategories.triggered.connect(
            partial(self.onDataDialog, "categories"))
        self.actionTags.triggered.connect(partial(self.onDataDialog, "tags"))
        self.actionCountries.triggered.connect(
            partial(self.onDataDialog, "countries"))
        self.actionQuotes.triggered.connect(
            partial(self.onDataDialog, "quotes"))
        self.PrepareTaxForms.triggered.connect(
            partial(self.taxes.showTaxesDialog, self))
        self.BalanceDate.dateChanged.connect(
            self.BalancesTableView.model().setDate)
        self.HoldingsDate.dateChanged.connect(
            self.HoldingsTableView.model().setDate)
        self.BalancesCurrencyCombo.changed.connect(
            self.BalancesTableView.model().setCurrency)
        self.BalancesTableView.doubleClicked.connect(self.OnBalanceDoubleClick)
        self.HoldingsCurrencyCombo.changed.connect(
            self.HoldingsTableView.model().setCurrency)
        self.ReportRangeCombo.currentIndexChanged.connect(
            self.onReportRangeChange)
        self.RunReportBtn.clicked.connect(self.onRunReport)
        self.SaveReportBtn.clicked.connect(self.reports.saveReport)
        self.ShowInactiveCheckBox.stateChanged.connect(
            self.BalancesTableView.model().toggleActive)
        self.DateRangeCombo.currentIndexChanged.connect(
            self.OnOperationsRangeChange)
        self.ChooseAccountBtn.changed.connect(
            self.OperationsTableView.model().setAccount)
        self.SearchString.editingFinished.connect(self.updateOperationsFilter)
        self.HoldingsTableView.customContextMenuRequested.connect(
            self.onHoldingsContextMenu)
        self.OperationsTableView.selectionModel().selectionChanged.connect(
            self.OnOperationChange)
        self.OperationsTableView.customContextMenuRequested.connect(
            self.onOperationContextMenu)
        self.DeleteOperationBtn.clicked.connect(self.deleteOperation)
        self.actionDelete.triggered.connect(self.deleteOperation)
        self.CopyOperationBtn.clicked.connect(self.copyOperation)
        self.actionCopy.triggered.connect(self.copyOperation)
        self.downloader.download_completed.connect(self.balances_model.update)
        self.downloader.download_completed.connect(self.holdings_model.update)
        self.statements.load_completed.connect(self.onStatementImport)
        self.ledger.updated.connect(self.balances_model.update)
        self.ledger.updated.connect(self.holdings_model.update)

    @Slot()
    def closeEvent(self, event):
        self.logger.removeHandler(
            self.Logs
        )  # Removing handler (but it doesn't prevent exception at exit)
        logging.raiseExceptions = False  # Silencing logging module exceptions

    def createLanguageMenu(self):
        langPath = get_app_path() + Setup.LANG_PATH + os.sep

        langDirectory = QDir(langPath)
        for language_file in langDirectory.entryList(['*.qm']):
            language_code = language_file.split('.')[0]
            language = QLocale.languageToString(
                QLocale(language_code).language())
            language_icon = QIcon(langPath + language_code + '.png')
            action = QAction(language_icon, language, self)
            action.setCheckable(True)
            action.setData(language_code)
            self.menuLanguage.addAction(action)
            self.langGroup.addAction(action)

    @Slot()
    def onLanguageChanged(self, action):
        language_code = action.data()
        if language_code != self.currentLanguage:
            JalSettings().setValue('Language',
                                   JalDB().get_language_id(language_code))
            QMessageBox().information(
                self, self.tr("Restart required"),
                self.tr("Language was changed to ") +
                QLocale.languageToString(QLocale(language_code).language()) +
                "\n" +
                self.tr("You should restart application to apply changes\n"
                        "Application will be terminated now"), QMessageBox.Ok)
            self.close()

    # Create import menu for all known statements based on self.statements.sources values
    def createStatementsImportMenu(self):
        for i, source in enumerate(self.statements.sources):
            if 'icon' in source:
                source_icon = load_icon(source['icon'])
                action = QAction(source_icon, source['name'], self)
            else:
                action = QAction(source['name'], self)
            action.setData(i)
            self.menuStatement.addAction(action)
            self.statementGroup.addAction(action)

    @Slot()
    def showAboutWindow(self):
        about_box = QMessageBox(self)
        about_box.setAttribute(Qt.WA_DeleteOnClose)
        about_box.setWindowTitle(self.tr("About"))
        title = self.tr(
            "<h3>JAL</h3><p>Just Another Ledger, version {version}</p>".format(
                version=__version__))
        about_box.setText(title)
        about = self.tr(
            "<p>More information, manuals and problem reports are at "
            "<a href=https://github.com/titov-vv/jal>github home page</a></p>"
            "<p>Questions, comments, help or donations:</p>"
            "<p><a href=mailto:[email protected]>[email protected]</a></p>"
            "<p><a href=https://t.me/jal_support>Telegram</a></p>")
        about_box.setInformativeText(about)
        about_box.show()

    def showProgressBar(self, visible=False):
        self.ProgressBar.setVisible(visible)
        self.centralwidget.setEnabled(not visible)
        self.MainMenu.setEnabled(not visible)

    @Slot()
    def OnBalanceDoubleClick(self, index):
        self.ChooseAccountBtn.account_id = index.model().getAccountId(
            index.row())

    @Slot()
    def onReportRangeChange(self, range_index):
        report_ranges = {
            0: lambda: (0, 0),
            1: ManipulateDate.Last3Months,
            2: ManipulateDate.RangeYTD,
            3: ManipulateDate.RangeThisYear,
            4: ManipulateDate.RangePreviousYear
        }
        begin, end = report_ranges[range_index]()
        self.ReportFromDate.setDateTime(
            QDateTime.fromSecsSinceEpoch(begin, spec=Qt.UTC))
        self.ReportToDate.setDateTime(
            QDateTime.fromSecsSinceEpoch(end, spec=Qt.UTC))

    @Slot()
    def onRunReport(self):
        types = {
            0: ReportType.IncomeSpending,
            1: ReportType.ProfitLoss,
            2: ReportType.Deals,
            3: ReportType.ByCategory
        }
        report_type = types[self.ReportTypeCombo.currentIndex()]
        begin = self.ReportFromDate.dateTime().toSecsSinceEpoch()
        end = self.ReportToDate.dateTime().toSecsSinceEpoch()
        group_dates = 1 if self.ReportGroupCheck.isChecked() else 0
        if report_type == ReportType.ByCategory:
            self.reports.runReport(report_type, begin, end,
                                   self.ReportCategoryEdit.selected_id,
                                   group_dates)
        else:
            self.reports.runReport(report_type, begin, end,
                                   self.ReportAccountBtn.account_id,
                                   group_dates)

    @Slot()
    def OnOperationsRangeChange(self, range_index):
        view_ranges = {
            0: ManipulateDate.startOfPreviousWeek,
            1: ManipulateDate.startOfPreviousMonth,
            2: ManipulateDate.startOfPreviousQuarter,
            3: ManipulateDate.startOfPreviousYear,
            4: lambda: 0
        }
        self.OperationsTableView.model().setDateRange(
            view_ranges[range_index]())

    @Slot()
    def importSlip(self):
        dialog = ImportSlipDialog(self)
        dialog.finished.connect(self.onSlipImportFinished)
        dialog.open()

    @Slot()
    def onSlipImportFinished(self):
        self.ledger.rebuild()

    @Slot()
    def onHoldingsContextMenu(self, pos):
        index = self.HoldingsTableView.indexAt(pos)
        contextMenu = QMenu(self.HoldingsTableView)
        actionShowChart = QAction(text=self.tr("Show Price Chart"),
                                  parent=self.HoldingsTableView)
        actionShowChart.triggered.connect(
            partial(self.showPriceChart,
                    self.HoldingsTableView.viewport().mapToGlobal(pos), index))
        contextMenu.addAction(actionShowChart)
        actionEstimateTax = QAction(text=self.tr("Estimate Russian Tax"),
                                    parent=self.HoldingsTableView)
        actionEstimateTax.triggered.connect(
            partial(self.estimateRussianTax,
                    self.HoldingsTableView.viewport().mapToGlobal(pos), index))
        contextMenu.addAction(actionEstimateTax)
        contextMenu.popup(self.HoldingsTableView.viewport().mapToGlobal(pos))

    @Slot()
    def showPriceChart(self, position, index):
        model = index.model()
        account, asset, asset_qty = model.get_data_for_tax(index)
        self.price_chart = ChartWindow(account, asset, asset_qty, position)
        if self.price_chart.ready:
            self.price_chart.open()

    @Slot()
    def estimateRussianTax(self, position, index):
        model = index.model()
        account, asset, asset_qty = model.get_data_for_tax(index)
        self.estimator = TaxEstimator(account, asset, asset_qty, position)
        if self.estimator.ready:
            self.estimator.open()

    @Slot()
    def OnOperationChange(self, selected, _deselected):
        self.checkForUncommittedChanges()

        if len(self.OperationsTableView.selectionModel().selectedRows()) != 1:
            self.OperationsTabs.setCurrentIndex(TransactionType.NA)
        else:
            idx = selected.indexes()
            if idx:
                selected_row = idx[0].row()
                operation_type, operation_id = self.OperationsTableView.model(
                ).get_operation(selected_row)
                self.OperationsTabs.setCurrentIndex(operation_type)
                self.OperationsTabs.widget(operation_type).setId(operation_id)

    @Slot()
    def checkForUncommittedChanges(self):
        for i in range(self.OperationsTabs.count()):
            if hasattr(self.OperationsTabs.widget(i),
                       "isCustom") and self.OperationsTabs.widget(i).modified:
                reply = QMessageBox().warning(
                    None, self.tr("You have unsaved changes"),
                    self.OperationsTabs.widget(i).name + self.tr(
                        " has uncommitted changes,\ndo you want to save it?"),
                    QMessageBox.Yes, QMessageBox.No)
                if reply == QMessageBox.Yes:
                    self.OperationsTabs.widget(i).saveChanges()
                else:
                    self.OperationsTabs.widget(i).revertChanges()

    @Slot()
    def onOperationContextMenu(self, pos):
        self.current_index = self.OperationsTableView.indexAt(pos)
        if len(self.OperationsTableView.selectionModel().selectedRows()) != 1:
            self.actionReconcile.setEnabled(False)
            self.actionCopy.setEnabled(False)
        else:
            self.actionReconcile.setEnabled(True)
            self.actionCopy.setEnabled(True)
        self.contextMenu.popup(
            self.OperationsTableView.viewport().mapToGlobal(pos))

    @Slot()
    def reconcileAtCurrentOperation(self):
        idx = self.operations_model.index(
            self.current_index.row(),
            0)  # we need only row to address fields by name
        timestamp = self.operations_model.data(idx,
                                               Qt.UserRole,
                                               field="timestamp")
        account_id = self.operations_model.data(idx,
                                                Qt.UserRole,
                                                field="account_id")
        JalDB().reconcile_account(account_id, timestamp)
        self.operations_model.refresh()

    @Slot()
    def deleteOperation(self):
        if QMessageBox().warning(
                None, self.tr("Confirmation"),
                self.tr("Are you sure to delete selected transacion(s)?"),
                QMessageBox.Yes, QMessageBox.No) == QMessageBox.No:
            return
        rows = []
        for index in self.OperationsTableView.selectionModel().selectedRows():
            rows.append(index.row())
        self.operations_model.deleteRows(rows)
        self.ledger.rebuild()

    @Slot()
    def createOperation(self, operation_type):
        self.checkForUncommittedChanges()
        self.OperationsTabs.widget(operation_type).createNew(
            account_id=self.operations_model.getAccount())
        self.OperationsTabs.setCurrentIndex(operation_type)

    @Slot()
    def copyOperation(self):
        operation_type = self.OperationsTabs.currentIndex()
        if operation_type == TransactionType.NA:
            return
        self.checkForUncommittedChanges()
        self.OperationsTabs.widget(operation_type).copyNew()

    @Slot()
    def updateOperationsFilter(self):
        self.OperationsTableView.model().filterText(self.SearchString.text())

    @Slot()
    def onDataDialog(self, dlg_type):
        if dlg_type == "account_types":
            AccountTypeListDialog().exec()
        elif dlg_type == "accounts":
            AccountListDialog().exec()
        elif dlg_type == "assets":
            AssetListDialog().exec()
        elif dlg_type == "agents":
            PeerListDialog().exec()
        elif dlg_type == "categories":
            CategoryListDialog().exec()
        elif dlg_type == "tags":
            TagsListDialog().exec()
        elif dlg_type == "countries":
            CountryListDialog().exec()
        elif dlg_type == "quotes":
            QuotesListDialog().exec()
        else:
            assert False

    @Slot()
    def onStatementImport(self, timestamp, totals):
        self.ledger.rebuild()
        for account_id in totals:
            for asset_id in totals[account_id]:
                amount = JalDB().get_asset_amount(timestamp, account_id,
                                                  asset_id)
                if amount is not None:
                    if abs(totals[account_id][asset_id] -
                           amount) <= Setup.DISP_TOLERANCE:
                        JalDB().reconcile_account(account_id, timestamp)
                        self.balances_model.update(
                        )  # Update required to display reconciled
                    else:
                        account = JalDB().get_account_name(account_id)
                        asset = JalDB().get_asset_name(asset_id)
                        logging.warning(
                            self.tr(
                                "Statement ending balance doesn't match: ") +
                            f"{account} / {asset} / {amount} <> {totals[account_id][asset_id]}"
                        )