コード例 #1
0
class GtoSplasher:
    def __init__(self, info):
        try:
            self.info = info
            self.splasher = None
            self.info.iface.mainWindow().showMinimized()
            qgisAppDataPath = QStandardPaths.standardLocations(
                QStandardPaths.AppDataLocation)[0]
            file = os.path.join(qgisAppDataPath, "splash.png")
            if not os.path.isfile(file):
                file = os.path.join(os.path.dirname(__file__), "splash.png")
            if os.path.isfile(file):
                pixmap = QPixmap(file)
                self.splasher = QSplashScreen(pixmap, Qt.WindowStaysOnTopHint)
                self.splasher.setPixmap(pixmap)
                self.splasher.show()
        except Exception as e:
            self.info.err(e)

    def log(self, msg):
        try:
            if self.splasher is not None:
                self.splasher.show()
                self.splasher.showMessage(msg, Qt.AlignCenter | Qt.AlignBottom)
                QApplication.instance().processEvents()
            self.info.log('Splasher:', msg)
        except Exception as e:
            self.info.err(e)

    def close(self):
        if self.splasher is not None:
            self.splasher.close()
コード例 #2
0
    def setPixmap(self, pixmap):
        self.setAttribute(Qt.WA_TranslucentBackground,
                          pixmap.hasAlpha() and \
                          is_transparency_supported())

        self.__pixmap = pixmap

        QSplashScreen.setPixmap(self, pixmap)
        if pixmap.hasAlpha() and not is_transparency_supported():
            self.setMask(pixmap.createHeuristicMask())
コード例 #3
0
def start_animation():
    splash = QSplashScreen()
    splash.setPixmap(QPixmap('images/zyx1.jpg'))
    splash.show()
    font = QFont("微软雅黑",16)
    splash.setFont(font)
    splash.showMessage('<font color="blue" size="16">Welcome to Use This PyQt5-Made Notebook~ <br> 向为喜爱的创造一切,不想不爱的人解释一句~</font>',
                       Qt.AlignBottom | Qt.AlignCenter, Qt.white)
    #splash.setFont(QFont("microsoft yahei", 20, QFont::Bold))
    time.sleep(2)
コード例 #4
0
class LoadingUI(object):
    def __init__(self, main_window: QMainWindow):
        """
        启动动画
        """
        self.main_window = main_window

        self.splash = QSplashScreen()

    def setup_ui(self) -> None:
        font = QFont()
        font.setPointSize(12)
        self.splash.setFont(font)

        # 因为QSplashScreen类实现的组件本身就是无边框界面所以我们可以省略Qt::FramelessWindowHint
        # self.splash.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint)
        # 正确的写法是只添加Qt::WindowStaysOnTopHint标志
        # setWindowFlags(Qt.WindowStaysOnTopHint)

        # 设置全屏显示
        # self.splash.showFullScreen()

        # 加载图片
        # self.splash.setPixmap(QPixmap(":/images/loading.png"))
        # self.splash.setPixmap(QPixmap(settings.MAIN_UI["background"]))
        self.splash.setPixmap(QPixmap(settings.MAIN_UI["loading"]))

        # 显示信息
        self.splash.showMessage("系统正在启动中...", Qt.AlignHCenter | Qt.AlignBottom,
                                Qt.white)
        # self.splash.showMessage("加载... 0%", Qt.AlignHCenter | Qt.AlignBottom, Qt.white)
        logger.debug("系统正在启动中...")

        self.splash.show()  # 显示启动界面
        # qApp.processEvents()  # 允许主进程处理事件

        # 加载数据
        # self.load_data()

        # self.main_window.show()
        # self.splash.finish(self.main_window)  # 隐藏启动界面

    def load_data(self) -> None:
        """
        模拟加载数据
        :return:
        """
        for i in range(1, 5):  # 模拟主程序加载过程
            # time.sleep(1)  # 加载数据
            msg = "加载... {0}%".format(i * 10)
            self.splash.showMessage(msg, Qt.AlignHCenter | Qt.AlignBottom,
                                    Qt.red)
            logger.debug(msg)
            qApp.processEvents()  # 允许主进程处理事件
コード例 #5
0
    def font_func(self):
        font, ok = QFontDialog.getFont()
        if ok:
            self.text_edit.setFont(font)

    def color_func(self):
        color = QColorDialog.getColor()
        if color.isValid():
            self.text_edit.setTextColor(color)

    def about_func(self):
        QMessageBox.aboutQt(self, 'About Qt')


if __name__ == '__main__':
    app = QApplication(sys.argv)

    splash = QSplashScreen()
    splash.setPixmap(QPixmap('images/splash.jpg'))
    splash.show()
    splash.showMessage('Welcome to Use This PyQt5-Made Notebook~',
                       Qt.AlignBottom | Qt.AlignCenter, Qt.white)
    time.sleep(2)

    demo = Demo()
    demo.show()
    splash.finish(demo)

    sys.exit(app.exec_())
コード例 #6
0
ファイル: main.py プロジェクト: pleuvoir/like-me-learn
import sys
from time import time, sleep

from PyQt5.QtGui import QIcon, QPixmap
from PyQt5.QtWidgets import QApplication, QSplashScreen

from tools.config import Const
from window_creator import MainWindow
import qdarkstyle

if __name__ == '__main__':

    app = QApplication(sys.argv)
    start = time()
    app.setWindowIcon(QIcon(Const.window_icon_path))

    splash = QSplashScreen()
    splash.setPixmap(QPixmap(Const.window_start_path))
    splash.show()
    app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())

    while time() - start < 0.8:
        sleep(0.001)
        app.processEvents()

    gui = MainWindow()
    gui.show()
    splash.finish(gui)
    sys.exit(app.exec_())
コード例 #7
0
ファイル: mainwindow.py プロジェクト: tuxta/myquerytutor
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        if getattr(sys, 'frozen', False):
            self.dir_path = os.path.dirname(sys.executable)
        else:
            # The application is not frozen
            self.dir_path = os.path.dirname(os.path.realpath(__file__))

        self.splash_screen = QSplashScreen()
        self.splash_screen.setPixmap(
            QPixmap(os.path.join(self.dir_path, 'splash.png')))
        self.splash_screen.show()

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.setWindowTitle("My Query Tutor - 2.3")
        self.ui.queryTextArea.setFontPointSize(15)
        self.app_settings = AppSettings()
        self.settings_cancelled = False
        self.erd = None
        self.sync_results = {}
        self.thread_pool = QThreadPool()

        first_run = False
        if not self.app_settings.has_settings():
            first_run = True
            wiz = FirstRunWiz(self.app_settings)
            wiz.setMinimumWidth(650)
            self.splash_screen.hide()
            wiz_result = wiz.exec()
            if wiz_result == 0:
                self.settings_cancelled = True
                sys.exit()

        self.db_ctrl = self.initial_checks()
        self.build_selection_tree()
        self.topic = ''
        self.question = ''
        self.question_id = 0

        # Connect signals to slots #
        self.ui.questionSelectTree.clicked.connect(
            self.on_question_select_tree_clicked)
        self.ui.runQuery_button.clicked.connect(self.run_query_clicked)
        self.ui.expectedResult_button.clicked.connect(
            self.expected_result_clicked)
        self.ui.help_button.clicked.connect(self.help_clicked)
        self.ui.progress_button.clicked.connect(self.show_progress)
        self.ui.syncButton.clicked.connect(self.sync_progress)
        self.ui.erdButton.clicked.connect(self.show_erd)

        # Disable the right click menu in the WebEngineView
        self.ui.questionTextArea.setContextMenuPolicy(Qt.NoContextMenu)
        self.ui.questionTextArea.setContextMenuPolicy(Qt.PreventContextMenu)

        self.ui.questionTextArea.settings().setAttribute(
            QWebEngineSettings.LocalContentCanAccessFileUrls, True)
        self.ui.questionTextArea.settings().setAttribute(
            QWebEngineSettings.LocalContentCanAccessRemoteUrls, True)

        # Set the initial Webview content - Credits
        self.ui.questionTextArea.setHtml('''
                                         <style>

                                         body {
                                           background-color: white;
                                         }

                                         h1 {
                                           text-align:center;
                                           text-decoration:underline;
                                           font-weight:bold;
                                         }
                                         
                                         .syntaxbox {
                                           box-sizing: border-box;
                                           border: 4px solid black;
                                           float: center;
                                           font: italic bold 15px Monospace;
                                           background: wheat;
                                           padding: 20px;
                                           margin-left: 40px;
                                           margin-right: 40px;
                                           text-align: center;
                                         }
                                         
                                         .examplebox {
                                           box-sizing: border-box;
                                           border: 4px solid black;
                                           float: center;
                                           font: bold 16px Arial;
                                           background: PaleTurquoise;
                                           padding: 20px;
                                           margin-left: 40px;
                                           margin-right: 40px;
                                           text-align: center;
                                         }
                                         
                                         </style>
                                         
                                         <body>
                                           <h1>My Query Tutor</h1>
                                           <div class="syntaxbox">
                                             <p>Software Developer</p>
                                             Steven Tucker
                                           </div>
                                           
                                           <div class="examplebox">
                                             <p>Content Developer</p>
                                             Peter Darcy
                                           </div>
                                           
                                           <div class="syntaxbox">
                                             <p>Content Designer</p>
                                             Keshlan Chinia
                                           </div>
                                         
                                         </body>
                                         ''')

        # Part of the horrible hack!!
        self.ui.queryTextArea.textChanged.connect(self.reset_font_query_edit)

        if not first_run:
            self.restoreGeometry(self.app_settings.get_geometry())
            self.ui.splitter.setSizes(
                self.app_settings.get_splitter_1_geometry())
            self.ui.splitter_2.setSizes(
                self.app_settings.get_splitter_2_geometry())
        else:
            self.splash_screen.show()
            self.ui.splitter.setSizes([393, 161])
            self.ui.splitter_2.setSizes([206, 565])

        self.splash_screen.finish(self)
        self.ui.questionTextArea.settings().setAttribute(
            QWebEngineSettings.LocalContentCanAccessFileUrls, True)

    def closeEvent(self, event):
        if not self.settings_cancelled:
            self.app_settings.set_geometry(self.saveGeometry(),
                                           self.ui.splitter.sizes(),
                                           self.ui.splitter_2.sizes())
        event.accept()

    @staticmethod
    def initial_checks():
        db_ctrl = DatabaseController()
        db_ctrl.connect()
        return db_ctrl

    def reset_font_query_edit(self):
        """
        Horrible, Horrible, Horrible Hack!
        Necessary to get around the font resetting if the current text is deleted
        Every time something changes, the font size is set
        """
        self.ui.queryTextArea.setFontPointSize(15)
        self.ui.queryTextArea.setFontWeight(-1)

    def show_erd(self):
        if self.question != '':
            image_dialog = QDialog()
            image_dialog.setModal(False)

            if self.erd is None:
                image_label = QLabel("No Diagram set for Question")
            else:
                image_label = QLabel(self.erd)
                image = QPixmap(os.path.join(self.dir_path, "images",
                                             self.erd))
                image_label.setPixmap(
                    image.scaled(1024, 768, Qt.KeepAspectRatio))
            layout = QBoxLayout(QBoxLayout.LeftToRight)
            layout.addWidget(image_label)
            image_label.setScaledContents(True)
            image_label.setMinimumHeight(100)
            image_label.setMinimumWidth(100)
            image_dialog.setLayout(layout)
            image_dialog.setModal(False)
            image_dialog.exec()

    def run_query_clicked(self):
        query = self.ui.queryTextArea.toPlainText()
        if query != '':

            self.ui.syncButton.setText("Sync with server")
            self.ui.syncButton.setStyleSheet(
                " QPushButton { background-color : lightsalmon; color : black }"
            )

            column_names, row_data = self.db_ctrl.run_query(query)

            expected_result_query = self.db_ctrl.get_question_query(
                self.question_id)
            expected_names, expected_data = self.db_ctrl.run_query(
                expected_result_query)

            if column_names == expected_names and row_data == expected_data:
                result_color = 1
                self.db_ctrl.set_question_query(query, self.topic,
                                                self.question, 1)
            else:
                result_color = 2
                self.db_ctrl.set_question_query(query, self.topic,
                                                self.question, 0)

            # Compare the exemplar query with the user query to identify errors
            query_comparison_html = self.compare_queries(
                expected_result_query, query)

            result_dialog = ExpectedResult(self, self.question, column_names,
                                           row_data, result_color)
            result_dialog.setModal(False)
            result_dialog.ui.textBrowser.setHtml(query_comparison_html)
            result_dialog.show()

    def expected_result_clicked(self):
        if self.question != '':
            query = self.db_ctrl.get_question_query(self.question_id)
            if query != '':
                column_names, row_data = self.db_ctrl.run_query(query)

                answer_dialog = ExpectedResult(
                    self, 'Expected Result for ' + self.question, column_names,
                    row_data)

                answer_dialog.setModal(False)
                answer_dialog.ui.label_correct.setText('')
                answer_dialog.ui.textBrowser.deleteLater()
                answer_dialog.show()

    def help_clicked(self):
        if not self.topic == '':
            lesson = self.db_ctrl.get_lesson(self.topic)
            lesson_dialog = LessonDialog(self, self.topic, lesson)
            lesson_dialog.setModal(False)
            lesson_dialog.show()

    def build_selection_tree(self):
        self.ui.questionSelectTree.setColumnCount(1)
        self.ui.questionSelectTree.header().close()

        questions_map, questions_list = self.db_ctrl.get_questions_list()

        for topic in questions_list:
            topic_item = QTreeWidgetItem(self.ui.questionSelectTree)
            topic_item.setText(0, topic)
            for question in questions_map[topic]:
                QTreeWidgetItem(topic_item).setText(0, question)

    def on_question_select_tree_clicked(self, index: QModelIndex):

        topic_item = index.parent()
        if not topic_item.isValid():
            return

        self.topic = topic_item.data()
        self.question = index.data()

        self.question_id, description, self.erd = self.db_ctrl.get_question(
            self.topic, self.question)

        global installer_building
        # Replace relative path to absolute
        soup = BeautifulSoup(description, "html.parser")
        for img in soup.findAll('img'):
            img['src'] = os.path.join(self.dir_path, "images", img['src'])

        for style in soup.find('style'):
            style_str = str(style)
            finds = re.findall('url\(.+?\)', style_str)
            for find in finds:
                sub_str = find[5:-2]
                file_type = os.path.splitext(sub_str)[1][1:]
                image_path = os.path.join(self.dir_path, 'images', sub_str)
                with open(image_path, "rb") as image_file:
                    encoded_string = base64.b64encode(
                        image_file.read()).decode('utf-8')
                    new_url = 'url("data:image/' + file_type + ' ;base64, ' + encoded_string + '")'
                style_str = style_str.replace(find, new_url)
            style.replaceWith(BeautifulSoup(style_str, features="html.parser"))
        description = str(soup)

        self.ui.questionTextArea.setHtml(description)

        # Load last query attempted for this question if on exists
        last_query = self.db_ctrl.get_last_query(self.topic, self.question)
        self.ui.queryTextArea.setText(last_query)

    def show_progress(self):
        questions_map, questions_list = self.db_ctrl.get_questions_list()

        progress_dialog = ProgressDialog(self, questions_map, questions_list,
                                         self.db_ctrl)

        progress_dialog.setModal(False)
        progress_dialog.ui.label_correct.setText('')
        progress_dialog.ui.textBrowser.deleteLater()
        progress_dialog.show()

    def sync_progress(self):
        server_address, class_key, ssl_set = self.app_settings.get_server_details(
        )
        first_name, surname, email = self.app_settings.get_user_details()

        QApplication.setOverrideCursor(Qt.WaitCursor)

        server_sync = ServerSync(
            self, (server_address, class_key, ssl_set),
            (first_name, surname, email),
            self.db_ctrl.get_sync_up_data(first_name, surname, email,
                                          self.app_settings.get_time_stamp()),
            self.sync_results)
        server_sync.signals.result.connect(self.sync_return)

        QThreadPool.globalInstance().start(server_sync)

    def sync_return(self):
        print("In Sync return")
        if self.sync_results['successful']:
            # Update timestamp from returned json
            self.app_settings.set_time_stamp(
                self.sync_results['synced_down_data']["timestamp"])
            # Mark all entries at synced
            self.db_ctrl.mark_synced()
            # insert new records.
            self.db_ctrl.insert_synced_records(
                self.sync_results['synced_down_data']["results"])
            # Change sync button to green if all completes successfully
            self.ui.syncButton.setText("In Sync")
            self.ui.syncButton.setStyleSheet(
                " QPushButton { background-color : lightgreen; color : black }"
            )
        else:
            # Dialog saying syn failed - with error
            server_address, class_key, ssl_set = self.app_settings.get_server_details(
            )
            self.update_server_settings(server_address, class_key, ssl_set)

        QApplication.setOverrideCursor(Qt.ArrowCursor)

    def update_server_settings(self, server_address, class_key, ssl):
        # Show dialog with server settings, test settings and return true on success, false on fail
        settings_dialog = SettingsDialog(self, self.app_settings,
                                         server_address, class_key, ssl)
        settings_dialog.exec()
        self.ui.syncButton.setText("Sync with server")
        self.ui.syncButton.setStyleSheet(
            " QPushButton { background-color : lightsalmon; color : black }")

    @staticmethod
    def compare_queries(exemplar_query, user_query):

        html_string_list = []

        # Set style rules
        html_header = '''
                    <style>
                      .Correct {
                        color:green;
                      }
                      .Incorrect {
                        color:red;
                      }
                    </style>
                    
                    <html>
                    '''
        # Break both queries into lists
        # Step through the user_query checking if each word
        # is in the exemplar. Set color and add to html string

        exemplar_list = exemplar_query.split()
        query_list = user_query.split()
        html_string_list.append(html_header)

        for word in query_list:
            if word in exemplar_list:
                html_string_list.append('<span class=Correct>' + word +
                                        '</span>')
            else:
                html_string_list.append('<span class=Incorrect>' + word +
                                        '</span>')

        html_string_list.append('''
                                
                                </html>
                                ''')

        html_string = ' '.join(html_string_list)

        return html_string
コード例 #8
0
        exitAct.setShortcut('Ctrl+Q')
        exitAct.triggered.connect(qApp.quit)
        about_menu.addAction(exitAct)

        self.setWindowTitle('你又来学习了')
        self.resize(1200, 650)
        self.center()  # 居中

    def center(self):
        qr = self.frameGeometry()  # 获得主窗口所在的框架
        cp = QDesktopWidget().availableGeometry().center()  # 获取显示器的分辨率,然后得到屏幕中间点的位置
        qr.moveCenter(cp)  # 获取显示器的分辨率,然后得到屏幕中间点的位置
        self.move(qr.topLeft())  # 然后通过move函数把主窗口的左上角移动到其框架的左上角,这样就把窗口居中了


if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setWindowIcon(QIcon('../assets/favicon.png'))

    splash = QSplashScreen()
    splash.setPixmap(QPixmap('../assets/likeme.gif'))
    splash.show()
    splash.showMessage('小伙子,你咋又来学习了?玩游戏它不香吗?',
                       Qt.AlignBottom | Qt.AlignCenter, Qt.white)
    time.sleep(1)


    example = Example()
    example.show()
    sys.exit(app.exec_())
コード例 #9
0
        timer.stop()  # останавливаем таймер
        application.show()  # показываем форму
        splashScreen.finish(application)  # закрываем SplashScreen
    else:
        pass


app = QApplication(sys.argv)

# Поток для SplashScreen
SplashThread = SplashThread()

# Создаем splashScreen
splashScreen = QSplashScreen()
splashPixmap = QPixmap('data/splash/splash_100.png')
splashScreen.setPixmap(splashPixmap)
splashScreen.show()

# Создаем форму приложения
application = MainView()

# Создаем таймер для splashScreen
timer = QTimer()
timer.setInterval(33.33)
timer.setSingleShot(False)
timer.timeout.connect(updateSplashScreen)
timer.start()

# Коннектимся к потоку
SplashThread.mysignal.connect(stopTimer)
# Запускаем поток
コード例 #10
0
class MainWindow(QMainWindow):
    child_count_is_known = False

    def __init__(self, db_worker: DBWorker, parent=None):
        generate_image(get_now())
        QMainWindow.__init__(self, parent)
        self.setWindowTitle("Амбарная книга")
        self.splash_for_time = QSplashScreen(
            QtGui.QPixmap(r'images/spimage.jpg'))
        self.splash_for_time.showMessage(
            "Сохраните своё время с нами!\n\nПодключение к базе данных...\n\r"
            "\n\r\n\r", QtCore.Qt.AlignCenter | QtCore.Qt.AlignBottom,
            QtCore.Qt.black)
        self.splash_for_time.show()
        time.sleep(2)
        self.db_worker: DBWorker = db_worker
        self.con = QSqlDatabase.addDatabase("QSQLITE")
        self.con.setDatabaseName('ambar_book.db')
        self.con.open()
        self.stm: SRTM = SRTM(self)
        self.stm.setEditStrategy(QSqlTableModel.OnManualSubmit)
        generate_image(get_now())
        self.splash_for_time.setPixmap(QtGui.QPixmap(r'images/spimage.jpg'))
        self.splash_for_time.showMessage(
            "Сохраните своё время с нами!\n\nЗагрузка элементов экрана...\n\r"
            "\n\r\n\r", QtCore.Qt.AlignCenter | QtCore.Qt.AlignBottom,
            QtCore.Qt.black)
        time.sleep(2)
        self.central_widget: QWidget = QWidget(self)
        self.main_layout: QLayout = QVBoxLayout()
        self.table_labels_row: QLayout = QHBoxLayout()
        self.control_buttons_row: QLayout = QHBoxLayout()
        self.table_title_layout: QLayout = QVBoxLayout()
        self.pbcwg = QGroupBox("Выберите продукт:")
        self.pbc: QLayout = QVBoxLayout()  # ProductButtonsColumn
        self.pbcwg.setLayout(self.pbc)
        self.pbcw = QScrollArea(self)
        self.pbcw.setWidget(self.pbcwg)
        self.pbcw.setWidgetResizable(True)
        self.labels_increment_decrement_column = QVBoxLayout()
        self.product_buttons: List[ProductButton] = list()
        self.table_title: QLabel = QLabel("", parent=self)
        self.table: QTableView = QTableView(self)
        # self.table = QTableWidget(self)
        self.child_count_label = QLabel("", parent=self)
        self.date_label = QLabel(date.today().strftime("%d.%m.%Y"))
        self.add_increment_widget = AddIncrementWidget(parent=self)
        self.add_increment_widget.button.clicked.connect(self.add_increment)
        self.add_decrement_widget = AddDecrementWidget(parent=self)
        self.add_decrement_widget.button.clicked.connect(self.add_decrement)
        self.add_row_button = QPushButton("Добавить строку", parent=self)
        self.add_row_button.clicked.connect(self.add_row)
        self.delete_row_button = QPushButton("Убрать строку", parent=self)
        self.delete_row_button.clicked.connect(self.delete_row)
        self.setup_menu_bar()
        self.load_ui()
        self.setStyleSheet(css_style)
        self.chosen_product = self.product_buttons[0]
        self.chosen_product.setObjectName("chosenProductButton")
        self.table_title.setText(centralize_text(self.chosen_product.text()))
        self.load_changings()
        self.add_decrement_widget.quantity_checker.setEnabled(
            self.child_count_is_known)

    def edit_remainders(self) -> None:
        return

    def show_remainders(self) -> None:
        return

    def setup_menu_bar(self):
        menu_bar = self.menuBar()
        my_menu_add = menu_bar.addMenu("&Добавить")
        my_menu_add.addAction("&Продукт", self.add_product,
                              QtCore.Qt.CTRL + QtCore.Qt.Key_P)
        my_menu_add.addAction("&Блюдо", self.add_meal,
                              QtCore.Qt.CTRL + QtCore.Qt.Key_M)
        menu_remainders = menu_bar.addMenu("&Остатки")
        menu_remainders.addAction(
            "&Редактировать", self.edit_remainders,
            QtCore.Qt.CTRL + QtCore.Qt.Key_O + QtCore.Qt.Key_R)
        menu_remainders.addAction(
            "&Посмотреть", self.show_remainders,
            QtCore.Qt.CTRL + QtCore.Qt.Key_S + QtCore.Qt.Key_O)

    def add_meal(self):
        dialog: QDialog = QDialog(self)
        dialog.ui = MealInfoUI(dialog, self.db_worker)
        dialog.show()

    def add_product(self):
        dialog: QDialog = QDialog(self)
        dialog.ui = UiProductInfo(dialog, self.db_worker)
        dialog.ui.setup_ui(dialog)
        dialog.show()

    def add_increment(self):
        product_id = self.chosen_product.product_id
        quantity = self.add_increment_widget.quantity_value.value()
        mdate = self.add_increment_widget.otherday_edit.date().toPyDate()
        price = self.add_increment_widget.price_value.value()
        agreement_info = self.add_increment_widget.agreement_info.toPlainText()
        invoice_info = self.add_increment_widget.invoice_info.toPlainText()
        self.db_worker.add_changing(product_id,
                                    quantity,
                                    mdate=mdate,
                                    price=price,
                                    agreement_info=agreement_info,
                                    invoice_info=invoice_info)
        self.stm.select()

    def add_decrement(self):
        product_id = self.chosen_product.product_id
        if self.add_decrement_widget.quantity_checker.isChecked():
            decrement = (self.add_decrement_widget.quantity_value.value() *
                         self.child_count)
        else:
            decrement = self.add_decrement_widget.quantity_value.value()
        mdate = self.add_decrement_widget.otherday_edit.date().toPyDate()
        self.db_worker.add_changing(product_id,
                                    decrement=decrement,
                                    mdate=mdate)
        self.stm.select()

    def add_row(self):
        rec = self.con.record('changings')
        rec.setValue('product_id', self.chosen_product.product_id)
        rec.setValue('unit', self.chosen_product.product_unit)
        rec.setValue('date', date.today().strftime("%d-%m-%Y"))
        rec.setValue('price', 0)
        rec.setValue('increment', 0)
        rec.setValue('decrement', 0)
        self.stm.insertRowIntoTable(rec)
        self.stm.submitAll()
        self.stm.select()

    def delete_row(self):
        self.stm.removeRow(self.table.currentIndex().row())
        self.stm.select()

    def load_changings(self):
        self.stm.setTable('changings')
        self.stm.setSort(1, QtCore.Qt.DescendingOrder)
        self.stm.setFilter(f"product_id = {self.chosen_product.product_id}")
        self.stm.select()
        self.stm.setHeaderData(1, QtCore.Qt.Horizontal, "Дата")
        self.stm.setHeaderData(2, QtCore.Qt.Horizontal, "Доверенность")
        self.stm.setHeaderData(3, QtCore.Qt.Horizontal, "Счёт-фактура")
        self.stm.setHeaderData(4, QtCore.Qt.Horizontal, "Цена")
        self.stm.setHeaderData(5, QtCore.Qt.Horizontal, "Приход")
        self.stm.setHeaderData(6, QtCore.Qt.Horizontal, "Расход")
        self.stm.setHeaderData(7, QtCore.Qt.Horizontal, "Остаток")
        self.stm.setHeaderData(8, QtCore.Qt.Horizontal, "ед. изм")
        self.table.setModel(self.stm)
        self.table.hideColumn(0)
        self.table.hideColumn(9)
        self.table.setItemDelegateForColumn(1, DateDelegate())

    def ask_child_count(self):
        dialog = QDialog(self)
        dialog.ui = ChildCountUi(dialog)
        dialog.ui.setupUi(dialog)
        dialog.show()

    def load_child_count(self):
        try:
            value = self.db_worker.get_child_count()
        except AssertionError:
            today = date.today()
            if today.weekday() < week_lim:
                self.ask_child_count()
            else:
                self.child_count_label.hide()
        else:
            self.child_count_is_known = True
            self.child_count_label.setText(f'Кол-во детей:{value:4}')

    def change_product(self, btn: ProductButton):
        self.chosen_product.setObjectName("")
        self.chosen_product = btn
        btn.setObjectName("chosenProductButton")
        self.table_title.setText(centralize_text(btn.text()))
        self.setStyleSheet(css_style)
        self.load_changings()

    def load_ui(self):
        self.pbc.setObjectName("pbc_layout")
        products = self.db_worker.get_products_by_fields(
            ['id', 'name', 'unit'])
        for product in products:
            self.product_buttons.append(
                ProductButton(parent=self.pbcw,
                              product_id=product[0],
                              product_name=product[1],
                              product_unit=product[2]))
        for pr_button in self.product_buttons:
            pr_button.clicked.connect(self.change_product)
            self.pbc.addWidget(pr_button)
        self.load_child_count()
        spacer_item1 = QSpacerItem(0, 0, QSizePolicy.Expanding,
                                   QSizePolicy.Minimum)
        spacer_item2 = QSpacerItem(0, 0, QSizePolicy.Minimum,
                                   QSizePolicy.Expanding)
        self.pbcw.setMaximumWidth(170)
        self.pbcwg.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.pbc.setObjectName("pbc_layout")
        self.pbc.setContentsMargins(2, 0, 10, 0)
        self.control_buttons_row.addItem(spacer_item1)
        self.control_buttons_row.addWidget(self.add_row_button)
        self.control_buttons_row.addWidget(self.delete_row_button)
        self.table_title_layout.addWidget(self.table_title)
        self.table_title_layout.addWidget(self.table)
        self.labels_increment_decrement_column.addWidget(self.date_label)
        self.labels_increment_decrement_column.addWidget(
            self.child_count_label)
        self.labels_increment_decrement_column.addWidget(
            self.add_increment_widget)
        self.labels_increment_decrement_column.addWidget(
            self.add_decrement_widget)
        self.pbc.addItem(spacer_item2)
        self.labels_increment_decrement_column.addItem(spacer_item2)
        self.table_labels_row.addLayout(self.table_title_layout)
        self.table_labels_row.addWidget(self.pbcw)
        self.table_labels_row.addLayout(self.labels_increment_decrement_column)
        self.main_layout.addLayout(self.table_labels_row)
        # self.main_layout.addLayout(self.control_buttons_row)
        self.central_widget.setLayout(self.main_layout)
        self.setCentralWidget(self.central_widget)
コード例 #11
0
def main():
    """
    This is the main for HABBY. If no argument is given, the PyQt interface
    is called. If argument are given, HABBY is called from the command line.
    In this case, it can call restart (read a list of command from a file) or
    read a command written on the cmd or apply a command to a type of file
    (key word ALL before the command and name of the file with asterisk).
    For more complicated case, one can directly do a python script using
    the function from HABBY.
    """
    # current working directory
    if os.path.basename(sys.argv[0]) == "habby.py":  # from script
        # change current working directory
        os.chdir(os.path.dirname(os.path.abspath(sys.argv[0])))
    else:  # from exe
        try:
            this_file = __file__
        except NameError:
            this_file = sys.argv[0]
        this_file = os.path.abspath(this_file)
        if getattr(sys, 'frozen', False):
            application_path = getattr(sys, '_MEIPASS',
                                       os.path.dirname(sys.executable))
        else:
            application_path = os.path.dirname(this_file)
        os.chdir(application_path)  # change current working directory

    # GUI
    if len(sys.argv) <= 2 and 'LIST_COMMAND' not in sys.argv:
        """
        GUI
        """
        #print("GUI")
        from src_GUI import main_window_GUI
        import numpy as np
        # os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "2"  # try to ajust font size widget for windows
        # create app
        app = QApplication(sys.argv)
        # app.setAttribute(Qt.AA_EnableHighDpiScaling)  # try to ajust font size widget for windows

        # Create and display image splash screen
        time_between_image = 0.02
        delta_opacity = 0.1
        splash = QSplashScreen()
        splash.setPixmap(QPixmap('file_dep/splash_screen.png'))
        # splashscreen progressively displayed (with transparency)
        effect = QGraphicsOpacityEffect()
        splash.setGraphicsEffect(effect)
        effect.setOpacity(0.0)
        app.processEvents()
        splash.show()
        for opacity_value in np.arange(delta_opacity, 1.0 + delta_opacity,
                                       delta_opacity):
            time.sleep(time_between_image)
            effect.setOpacity(opacity_value)
            app.processEvents()

        # create windows
        if len(sys.argv) == 1:
            ex = main_window_GUI.MainWindows()
        if len(sys.argv) == 2:  # open existing project with .exe
            project_path = sys.argv[1]
            if os.path.exists(project_path) and project_path.split(
                    ".")[-1] == "habby":
                ex = main_window_GUI.MainWindows(project_path)
            else:
                return

        app.setActiveWindow(ex)

        # splashscreen progressively disappear (with transparency)
        for opacity_value in np.flip(np.arange(0.0, 1.0, delta_opacity)):
            time.sleep(time_between_image)
            effect.setOpacity(opacity_value)
            app.processEvents()
        splash.finish(ex)  # close splashscreen

        # close
        sys.exit(app.exec_())

    # CLI
    else:
        """
        CLI
        """
        #print("CLI")

        from src import func_for_cmd_mod

        # get path_prj and name_prj
        path_prj = None
        name_prj = None
        path_prj_index = None
        for id, opt in enumerate(sys.argv):
            if len(opt) > 8:
                if opt[:8] == 'path_prj':
                    path_prj = opt[9:]
                    name_prj = os.path.basename(path_prj)
                    path_prj_index = id

        if not path_prj and 'LIST_COMMAND' not in sys.argv:
            print("Error : Project path argument not found.")
            return
        else:
            if path_prj_index:
                # remove path_prj arg
                sys.argv.pop(path_prj_index)

        # check if enough argument
        if len(sys.argv) == 0 or len(sys.argv) == 1:
            print(" Not enough argument was given. \
                    At least one argument should be given")
            return

        # RESTART MODE
        elif sys.argv[1] == 'RESTART':
            if len(sys.argv) != 3:
                print('Error: the RESTART command needs the name of \
                      the restart file as input.')
                return
            func_for_cmd_mod.habby_restart(sys.argv[2], name_prj, path_prj)
        # ALL
        elif sys.argv[1] == 'ALL':
            if len(sys.argv) < 2:
                print('Error: the ALL command needs at least one argument.')
            all_arg = ['habby_cmd.py'] + sys.argv[2:]
            func_for_cmd_mod.habby_on_all(all_arg, name_prj, path_prj)
        else:
            all_arg = sys.argv[1:]
            func_for_cmd_mod.all_command(all_arg, name_prj, path_prj,
                                         HABBY_VERSION_STR)
コード例 #12
0
ファイル: MainLauncher.py プロジェクト: Esttelle/CuteImage
import sys
from PyQt5.QtWidgets import QApplication, QSplashScreen
from PyQt5.QtGui import QPixmap
import time
import json
# import qdarkgraystyle

from MainWindow import MainWindow

if __name__ == "__main__":
    settings = open("./default/userDefault.json")
    settings_text = ''
    for line in settings:
        settings_text += line
    settings.close()
    settings_dict = json.loads(settings_text)
    app = QApplication([])
    # if settings_dict['dark-mode'] == 'true':
    #     app.setStyleSheet(qdarkgraystyle.load_stylesheet())
    sleep_time = len(settings_dict["open-windows"]) * 0.1
    if settings_dict['show-splash'] == 'true':
        for i in range(5):
            splash = QSplashScreen()
            splash.setPixmap(QPixmap('./Icons/loading_' + str(i) + '.png'))
            splash.show()
            time.sleep(sleep_time)
            splash.hide()
    window = MainWindow()
    window.show()
    app.exec_()