Ejemplo n.º 1
0
 def load_ui_widget(self, ui_filename, parent=None):
     loader = uic()
     file = QFile(ui_filename)
     file.open(QFile.ReadOnly)
     self.ui = loader.load(file, parent)
     file.close()
     return self.ui
Ejemplo n.º 2
0
class TestQFileSignalBlocking(unittest.TestCase):
    '''Test case for blocking the signal QIODevice.aboutToClose()'''

    def setUp(self):
        #Set up the needed resources - A temp file and a QFile
        self.called = False
        handle, self.filename = mkstemp()
        os.close(handle)

        self.qfile = QFile(self.filename)

    def tearDown(self):
        #Release acquired resources
        os.remove(self.filename)
        del self.qfile

    def callback(self):
        #Default callback
        self.called = True

    def testAboutToCloseBlocking(self):
        #QIODevice.aboutToClose() blocking

        QObject.connect(self.qfile, SIGNAL('aboutToClose()'), self.callback)

        self.assert_(self.qfile.open(QFile.ReadOnly))
        self.qfile.close()
        self.assert_(self.called)

        self.called = False
        self.qfile.blockSignals(True)

        self.assert_(self.qfile.open(QFile.ReadOnly))
        self.qfile.close()
        self.assert_(not self.called)
Ejemplo n.º 3
0
 def testBasic(self):
     '''QFile.getChar'''
     obj = QFile(self.filename)
     obj.open(QIODevice.ReadOnly)
     self.assertEqual(obj.getChar(), (True, 'a'))
     self.assertFalse(obj.getChar()[0])
     obj.close()
Ejemplo n.º 4
0
 def load_ui_widget(self, ui_filename, parent=None):
     loader = uic()
     file = QFile(ui_filename)
     file.open(QFile.ReadOnly)
     loader.registerCustomWidget(MouthView)
     loader.registerCustomWidget(WaveformView)
     self.ui = loader.load(file, parent)
     file.close()
     return self.ui
Ejemplo n.º 5
0
    def testBug909(self):
        fileName = QFile(adjust_filename('bug_909.ui', __file__))
        loader = QUiLoader()
        main_win = loader.load(fileName)
        self.assertEqual(sys.getrefcount(main_win), 2)
        fileName.close()

        tw = QTabWidget(main_win)
        main_win.setCentralWidget(tw)
        main_win.show()
Ejemplo n.º 6
0
    def testImage(self):
        #Test loading of sample.png resource
        f = open(adjust_filename('sample.png', __file__), "rb")
        orig = f.read()
        f.close()

        f = QFile(':/sample.png')
        f.open(QIODevice.ReadOnly)
        copy = f.readAll()
        f.close()
        self.assertEqual(len(orig), len(copy))
        self.assertEqual(orig, copy)
Ejemplo n.º 7
0
    def testPhrase(self):
        #Test loading of quote.txt resource
        f = open(adjust_filename('quoteEnUS.txt', __file__), "r")
        orig = f.read()
        f.close()

        f = QFile(':/quote.txt')
        f.open(QIODevice.ReadOnly) #|QIODevice.Text)
        print("Error:", f.errorString())
        copy = f.readAll()
        f.close()
        self.assertEqual(orig, copy)
Ejemplo n.º 8
0
    sys.exit(0)


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

    os.chdir(os.path.dirname(os.path.abspath(__file__)))

    ui_file_name = "mainwindow.ui"
    ui_file = QFile(ui_file_name)
    if not ui_file.open(QIODevice.ReadOnly):
        print("Cannot open {}: {}".format(ui_file_name, ui_file.errorString()))
        sys.exit(-1)
    loader = QUiLoader()
    window = loader.load(ui_file)
    ui_file.close()
    if not window:
        print(loader.errorString())
        sys.exit(-1)

    res = None

    if platform.system() == 'Darwin':
        dev_dir = os.listdir('/dev')
        res = None
        for d in dev_dir:
            res = re.search(r'cu.usbmodem[0-9]', d), d
            if (res[0] is not None):
                res = "/dev/{}".format(d)
                break
Ejemplo n.º 9
0
class MainWindow(QObject):
    """ Appliaction GUI """
    current_port_signal = Signal(str)
    current_table = Signal(str)

    def __init__(self, ui_fil, parent=None):
        super(MainWindow, self).__init__(parent)
        self.ui_file = QFile(ui_fil)
        self.ui_file.open(QFile.ReadOnly)
        self.loader = QUiLoader()
        self.loader.setLanguageChangeEnabled(True)
        self.window = self.loader.load(self.ui_file)
        self.window.setGeometry(50, 50, 860, 640)
        self.window.setWindowIcon(QIcon('icons/icons8-wi-fi-64.png'))
        self.ui_file.close()

        self.trans = QTranslator()
        self.trans.load('lang/pl_PL.qm')
        self.conn_baudrates = [
            "9600", "115200", "300", "1200", "2400", "4800", "14400", "19200",
            "31250", "38400", "57600"
        ]
        self.conn_boards = ["ESP32", "ESP8266"]

        self.widget_tab = self.window.findChild(QTabWidget, 'tabWidget')
        self.widget_tab.setIconSize(QSize(36, 36))
        self.widget_tab.setTabIcon(0, QIcon('icons/icons8-automatic-64.png'))
        self.widget_tab.setTabIcon(1, QIcon('icons/icons8-bar-chart-50.png'))
        self.widget_tab.setTabIcon(2, QIcon('icons/icons8-menu-64.png'))
        self.widget_tab.setTabIcon(3, QIcon('icons/icons8-timeline-64.png'))
        self.widget_tab.setTabIcon(4, QIcon('icons/icons8-bluetooth-50.png'))
        self.widget_tab.setTabIcon(5, QIcon('icons/icons8-console-64.png'))

        self.lang_combo_box = self.window.findChild(QComboBox,
                                                    'lang_combo_box')
        self.lang_combo_box.addItem("English")
        self.lang_combo_box.addItem("Polski")
        self.lang_combo_box.currentTextChanged.connect(self.change_language)
        self.serial_port_box = self.window.findChild(QComboBox,
                                                     'serial_port_box')
        self.baud_rate_box = self.window.findChild(QComboBox, 'baud_rate_box')
        self.select_board_box = self.window.findChild(QComboBox,
                                                      'select_board_box')
        self.scan_time_edit = self.window.findChild(QTimeEdit,
                                                    'scan_time_edit')
        self.wifi_scan_box = self.window.findChild(QCheckBox, 'wifi_scan_box')
        self.blue_scan_box = self.window.findChild(QCheckBox, 'blue_scan_box')
        self.save_data_check = self.window.findChild(QCheckBox,
                                                     'save_data_check')
        self.connection_status_edit = self.window.findChild(
            QLineEdit, 'connection_status_edit')
        self.start_button = self.window.findChild(QPushButton, 'start_button')
        self.stop_button = self.window.findChild(QPushButton, 'stop_button')
        self.stop_button.setEnabled(False)
        self.vertical_wifi_layout = self.window.findChild(
            QVBoxLayout, 'verticalLayout_5')
        self.wifi_list_view = self.window.findChild(QListWidget,
                                                    'wifi_list_view')
        self.wifi_list_view.setIconSize(QSize(64, 64))
        self.vertical_timeline_layout = self.window.findChild(
            QVBoxLayout, 'verticalLayout_7')
        self.blue_list_view = self.window.findChild(QListWidget,
                                                    'blue_list_view')
        self.blue_list_view.setIconSize(QSize(64, 64))
        self.console_logging_check = self.window.findChild(
            QCheckBox, 'console_logging_check')
        self.console_autoscroll_check = self.window.findChild(
            QCheckBox, 'console_autoscroll_check')
        self.console_text_edit = self.window.findChild(QTextEdit,
                                                       'console_text_edit')

        self.select_board_box.activated[str].connect(self.change_board)

        #Settings tab
        for i in self.conn_baudrates:
            self.baud_rate_box.addItem(i)
        for i in self.conn_boards:
            self.select_board_box.addItem(i)
        self.connection_status_edit.setText('Not connected')
        self.connection_status_edit.setStyleSheet(
            "background: red; color: white; font-size: 14px; border-width: 1px; \
            border-style: solid; border-radius: 2px; border-color: red;")

        thread1 = ReadSerialPortsThread.ReadSerialPortsThread(self)
        thread1.add_serial_port.connect(
            lambda p: self.serial_port_box.addItem(p))
        thread1.remove_serial_port.connect(
            lambda p: self.serial_port_box.removeItem(
                self.serial_port_box.findText(p)))
        thread1.start()
        thread2 = MakeSerialConnection.MakeSerialConnection(self)
        thread4 = WriteToDatabase.WriteToDatabase(self)

        self.serial_port_box.currentTextChanged.connect(thread2.get_curr_port)
        self.baud_rate_box.activated[str].connect(thread2.get_curr_baud)
        self.select_board_box.activated[str].connect(thread2.get_curr_board)
        self.scan_time_edit.timeChanged.connect(thread2.get_curr_time)
        self.start_button.clicked.connect(thread2.start)
        self.stop_button.clicked.connect(thread2.stop_serial_communication)
        self.wifi_scan_box.clicked.connect(thread2.get_wifi_check)
        self.blue_scan_box.clicked.connect(thread2.get_blue_check)
        self.save_data_check.clicked.connect(thread2.enable_saving_to_db)
        self.save_data_check.clicked.connect(thread4.enable_saving_data_func)
        self.lang_combo_box.currentTextChanged.connect(
            lambda s: thread2.get_current_lang(s))

        thread2.baud_box_state.connect(
            lambda b: self.baud_rate_box.setEnabled(b))
        thread2.port_box_state.connect(
            lambda b: self.serial_port_box.setEnabled(b))
        thread2.board_box_state.connect(
            lambda b: self.select_board_box.setEnabled(b))
        thread2.time_edit_state.connect(
            lambda b: self.scan_time_edit.setEnabled(b))
        thread2.wifi_check_state.connect(
            lambda b: self.wifi_scan_box.setEnabled(b))
        thread2.blue_check_state.connect(
            lambda b: self.blue_scan_box.setEnabled(b))
        thread2.serial_port_placeholder.connect(
            lambda t: self.serial_port_box.addItem(t))
        thread2.serial_port_clear.connect(self.serial_port_box.clear)
        thread2.send_text_signal.connect(
            lambda t: self.console_text_edit.append(t))
        thread2.start_btn_state.connect(
            lambda b: self.start_button.setEnabled(b))
        thread2.stop_btn_state.connect(
            lambda b: self.stop_button.setEnabled(b))
        thread2.conn_stat_text.connect(
            lambda t: self.connection_status_edit.setText(t))
        thread2.conn_stat_style.connect(
            lambda s: self.connection_status_edit.setStyleSheet(s))

        #Wi-Fi Chart tab
        self.chart = QtCharts.QChart()
        self.axis_x = QtCharts.QValueAxis()
        self.axis_y = QtCharts.QValueAxis()

        self.line_series = QtCharts.QLineSeries()
        self.line_series.append(QPoint(0, 0))
        self.chart.setAxisX(self.axis_x, self.line_series)
        self.axis_x.setRange(2400, 2483)
        self.axis_x.setTickCount(10)
        self.axis_x.setMinorTickCount(4)
        self.axis_x.applyNiceNumbers()
        self.axis_x.setTitleText("Frequency [MHz]")
        self.chart.setAxisY(self.axis_y, self.line_series)
        self.axis_y.setRange(-100, -30)
        self.axis_y.applyNiceNumbers()
        self.axis_y.setTickCount(9)
        self.axis_y.setMinorTickCount(4)
        self.axis_y.setTitleText("RSSI [dBm]")
        self.chart.legend().setVisible(True)
        self.chart.legend().setAlignment(Qt.AlignRight)
        self.chart.setBackgroundRoundness(0)
        self.chart_view = QtCharts.QChartView(self.chart)
        self.chart_view.setRenderHint(QPainter.Antialiasing)
        self.vertical_wifi_layout.addWidget(self.chart_view)

        #WiFi List tab
        thread2.clear_wifi_list.connect(self.wifi_list_view.clear)
        thread2.append_wifi_list_item.connect(
            lambda i: self.wifi_list_view.addItem(i))
        thread2.append_wifi_timeline_data.connect(
            lambda d: self.append_data(d))
        thread2.save_wifi_timeline_data.connect(
            lambda t: thread4.update_db_file(t))
        thread2.clear_wifi_series.connect(self.chart.removeAllSeries)
        thread2.add_wifi_series.connect(lambda s: self.chart.addSeries(s))
        thread2.set_axis_x_series.connect(
            lambda s: self.chart.setAxisX(self.axis_x, s))
        thread2.set_axis_y_series.connect(
            lambda s: self.chart.setAxisY(self.axis_y, s))
        thread2.wifi_data_to_func.connect(
            lambda d: thread2.append_wifi_data(d))
        thread2.wifi_data_to_func.connect(
            lambda d: thread2.append_data_to_wifi_graph(d))
        thread2.wifi_data_to_func.connect(
            lambda d: thread2.append_data_to_wifi_timeline(d))
        thread2.blue_data_to_func.connect(
            lambda d: thread2.append_blue_data(d))

        #Wi-Fi Timeline tab
        self.wifi_channels_occupancy_array = []
        self.wifi_channels_timestamps = []
        self.deleted_empty_vals = False
        self.freeze_graph_bool_val = False
        self.last_item = 0
        self.graph_item_color = QColor(255, 195, 0)

        self.bars = QtDataVisualization.Q3DBars()
        self.column_axis = QtDataVisualization.QCategory3DAxis()
        self.column_axis.setTitle('Channels')
        self.column_axis.setTitleVisible(True)
        self.column_axis.setLabels([
            'Channel 1', 'Channel 2', 'Channel 3', 'Channel 4', 'Channel 5',
            'Channel 6', 'Channel 7', 'Channel 8', 'Channel 9', 'Channel 10',
            'Channel 11', 'Channel 12', 'Channel 13'
        ])
        self.column_axis.setLabelAutoRotation(45)
        self.column_axis.setAutoAdjustRange(True)
        self.row_axis = QtDataVisualization.QCategory3DAxis()
        self.row_axis.setTitle('Timeline')
        self.row_axis.setTitleVisible(True)
        self.value_axis = QtDataVisualization.QValue3DAxis()
        self.value_axis.setTitle('RSSI [dBm]')
        self.value_axis.setTitleVisible(True)
        self.value_axis.setRange(-100, -10)

        self.bars.setRowAxis(self.row_axis)
        self.bars.setColumnAxis(self.column_axis)
        self.bars.setValueAxis(self.value_axis)
        self.bars.setBarSpacingRelative(False)
        self.bars.setFloorLevel(-100)

        self.series = QtDataVisualization.QBar3DSeries()
        self.array_data = [[]]
        self.series.dataProxy().addRows(
            self.data_to_bar_data_array(self.array_data))
        self.series.setBaseColor(self.graph_item_color)

        self.bars.setPrimarySeries(self.series)
        self.container = QWidget.createWindowContainer(self.bars)

        if not self.bars.hasContext():
            print("Couldn't initialize the OpenGL context")
            sys.exit(-1)

        camera = self.bars.scene().activeCamera()
        camera.setXRotation(-45.0)
        camera.setYRotation(22.5)

        geometry = QGuiApplication.primaryScreen().geometry()
        size = geometry.height() * 3 / 4
        self.container.setMinimumSize(size, size)
        self.container.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        self.container.setFocusPolicy(Qt.StrongFocus)
        self.append_data([
            -100, -80, -100, -80, -100, -80, -100, -80, -100, -80, -100, -80,
            -100
        ])
        self.nav_layout_h = QHBoxLayout()
        self.freeze_check = QCheckBox()
        self.freeze_check.setText("Freeze")
        self.freeze_check.clicked.connect(self.enable_scrolling_data)
        self.freeze_check.stateChanged.connect(self.freeze_graph)
        self.prev_button = QPushButton()
        self.prev_button.setText("Previous")
        self.prev_button.setEnabled(False)
        self.prev_button.clicked.connect(self.previous_data)
        self.next_button = QPushButton()
        self.next_button.setText("Next")
        self.next_button.setEnabled(False)
        self.next_button.clicked.connect(self.next_data)
        self.nav_layout_h.addWidget(self.freeze_check)
        self.nav_layout_h.addWidget(self.prev_button)
        self.nav_layout_h.addWidget(self.next_button)

        self.load_data_check = QCheckBox()
        self.load_data_check.setText("Load archival data")
        self.load_data_check.clicked.connect(self.enable_load_data)
        self.load_data_combo = QComboBox()
        self.load_data_combo.addItem("No data found")
        self.load_data_combo.setEnabled(False)
        self.load_data_btn = QPushButton()
        self.load_data_btn.setText("Load")
        self.load_data_btn.setEnabled(False)
        self.nav_layout_h2 = QHBoxLayout()
        self.nav_layout_h2.addWidget(self.load_data_check)
        self.nav_layout_h2.addWidget(self.load_data_combo)
        self.nav_layout_h2.addWidget(self.load_data_btn)
        thread4.start()
        thread4.remove_defualt_item.connect(
            lambda: self.load_data_combo.clear())
        thread4.append_available_day.connect(
            lambda s: self.load_data_combo.addItem(s))
        thread4.send_data_from_database.connect(
            lambda t: self.append_data_from_database(t))
        self.load_data_combo.currentTextChanged.connect(
            lambda t: thread4.get_curr_table(t))
        self.load_data_btn.clicked.connect(thread4.load_data_button)

        self.vertical_timeline_layout.addWidget(self.container)
        self.vertical_timeline_layout.addLayout(self.nav_layout_h)
        self.vertical_timeline_layout.addLayout(self.nav_layout_h2)

        #Bluetooth tab
        thread2.clear_blue_list.connect(self.blue_list_view.clear)
        thread2.append_blue_list_item.connect(
            lambda i: self.blue_list_view.addItem(i))

        #Console tab
        self.console_autoscroll_check.stateChanged.connect(
            self.enable_auto_scroll)
        thread3 = WriteToFile.WriteToFile(self)
        self.console_logging_check.stateChanged.connect(thread3.enable_logging)
        thread2.send_text_signal.connect(lambda t: thread3.write_to_file(t))

        self.window.show()

    def change_board(self):
        """ Disable Bluetooth scan option if ESP8266 board is selected """
        print(self.select_board_box.currentText())
        if self.select_board_box.currentText() == "ESP8266":
            self.blue_scan_box.setEnabled(False)
        elif self.select_board_box.currentText() == "ESP32":
            self.blue_scan_box.setEnabled(True)

    def enable_auto_scroll(self):
        """ Enable scrolling in text console """
        if self.console_autoscroll_check.checkState() == Qt.Checked:
            self.console_text_edit.moveCursor(QTextCursor.End)
        else:
            self.console_text_edit.moveCursor(QTextCursor.Start)

    def freeze_graph(self, state):
        """ Stop showing live data in 3d Wi-Fi graph """
        if state == 2:
            self.freeze_graph_bool_val = True
        else:
            self.freeze_graph_bool_val = False

    def data_to_bar_data_row(self, data):
        """ DOCSTRING """
        return list(QtDataVisualization.QBarDataItem(d) for d in data)

    def data_to_bar_data_array(self, data):
        """ DOCSTRING """
        return list(self.data_to_bar_data_row(row) for row in data)

    def append_data(self, data):
        """ DOCSTRING """
        self.wifi_channels_occupancy_array.append(data)
        self.wifi_channels_timestamps.append(str(datetime.datetime.now()))
        self.update_graph()

    def update_graph(self):
        """ DOCSTRING """
        if len(self.wifi_channels_occupancy_array) < 10:
            missing_vals = 10 - len(self.wifi_channels_occupancy_array)
            for z in range(missing_vals):
                self.wifi_channels_occupancy_array.append([
                    -100, -100, -100, -100, -100, -100, -100, -100, -100, -100,
                    -100, -100, -100
                ])
                self.wifi_channels_timestamps.append("")
            self.print_freshes_ten()

        elif len(self.wifi_channels_occupancy_array
                 ) > 20 and self.deleted_empty_vals is False:
            for y in range(
                    self.wifi_channels_occupancy_array.count([
                        -100, -100, -100, -100, -100, -100, -100, -100, -100,
                        -100, -100, -100, -100
                    ])):
                self.wifi_channels_occupancy_array.remove([
                    -100, -100, -100, -100, -100, -100, -100, -100, -100, -100,
                    -100, -100, -100
                ])
                self.wifi_channels_timestamps.remove("")
                self.deleted_empty_vals = True
                self.print_freshes_ten()
        else:
            self.print_freshes_ten()

    def previous_data(self):
        """ DOCSTRING """
        if self.last_item < 9 and len(self.wifi_channels_occupancy_array) < 9:
            QMessageBox.warning(self.window, 'ISM 2.4GHz Scanner - Warning',
                                "To few information to rewind!",
                                QMessageBox.Ok)
        elif self.last_item < 9:
            print('out of range')
            QMessageBox.warning(self.window, 'ISM 2.4GHz Scanner - Warning',
                                "No more data to rewind!", QMessageBox.Ok)
        else:
            temp_array = []
            temp_timestamp_array = []
            if self.last_item - 9 < 0:
                print('out of range')
                QMessageBox.warning(self.window,
                                    'ISM 2.4GHz Scanner - Warning',
                                    "No more data to rewind!", QMessageBox.Ok)
            else:
                for x in range(self.last_item - 10, self.last_item - 1):
                    temp_array.append(self.wifi_channels_occupancy_array[x])
                    temp_timestamp_array.append(
                        self.wifi_channels_timestamps[x])
                self.last_item = self.last_item - 9
                self.row_axis.setLabels(temp_timestamp_array)
                self.series.dataProxy().resetArray()
                self.series.dataProxy().addRows(
                    self.data_to_bar_data_array(temp_array))

    def next_data(self):
        """ DOCSTRING """
        if self.last_item < 9 and len(self.wifi_channels_occupancy_array) < 9:
            QMessageBox.warning(self.window, 'ISM 2.4GHz Scanner - Warning',
                                "To few information to rewind!",
                                QMessageBox.Ok)
        elif self.last_item > len(self.wifi_channels_occupancy_array):
            print('out of range')
            QMessageBox.warning(self.window, 'ISM 2.4GHz Scanner - Warning',
                                "No more data to rewind!", QMessageBox.Ok)
        else:
            temp_array = []
            temp_timestamp_array = []
            if self.last_item + 9 > len(self.wifi_channels_occupancy_array):
                print('out of range')
                QMessageBox.warning(self.window,
                                    'ISM 2.4GHz Scanner - Warning',
                                    "No more data to rewind!", QMessageBox.Ok)
            else:
                for x in range(self.last_item + 1, self.last_item + 10):
                    temp_array.append(self.wifi_channels_occupancy_array[x])
                    temp_timestamp_array.append(
                        self.wifi_channels_timestamps[x])

                self.last_item = self.last_item + 9
                self.row_axis.setLabels(temp_timestamp_array)
                self.series.dataProxy().resetArray()
                self.series.dataProxy().addRows(
                    self.data_to_bar_data_array(temp_array))

    def print_freshes_ten(self):
        """ DOCSTRING """
        if self.freeze_graph_bool_val is False:
            i = 0
            temp_array = []
            temp_timestamp_array = []
            self.last_item = 0
            for x in range(len(self.wifi_channels_occupancy_array) - 1):
                if i < 10:
                    temp_array.append(self.wifi_channels_occupancy_array[
                        len(self.wifi_channels_occupancy_array) - x - 1])
                    temp_timestamp_array.append(self.wifi_channels_timestamps[
                        len(self.wifi_channels_timestamps) - x - 1])
                    i += 1
                elif i == 10:
                    self.last_item = len(
                        self.wifi_channels_occupancy_array) - 10
                    i += 1

            self.row_axis.setLabels(temp_timestamp_array)
            self.series.dataProxy().resetArray()
            self.series.dataProxy().addRows(
                self.data_to_bar_data_array(temp_array))

    def enable_scrolling_data(self, state):
        """ DOCSTRING """
        if state is True:
            self.prev_button.setEnabled(True)
            self.next_button.setEnabled(True)
        else:
            self.prev_button.setEnabled(False)
            self.next_button.setEnabled(False)

    def enable_load_data(self, state):
        """ DOCSTRING """
        if state is True:
            self.load_data_combo.setEnabled(True)
            if (self.load_data_combo.findText("No data found") == -1
                    or self.load_data_combo.findText("Nie znaleziono danych")):
                self.load_data_btn.setEnabled(True)
        else:
            self.load_data_combo.setEnabled(False)
            self.load_data_btn.setEnabled(False)
            self.wifi_channels_occupancy_array = []
            self.wifi_channels_timestamps = []
            self.print_freshes_ten()

    def change_language(self, lang):
        """ DOCSTRING """
        if lang == "Polski":
            QCoreApplication.installTranslator(self.trans)
            self.axis_x.setTitleText("Częstotliwość [MHz]")
            self.freeze_check.setText("Zamróź")
            self.load_data_check.setText("Otwórz dane archiwalne")
            self.load_data_combo.removeItem(
                self.load_data_combo.findText("No data found"))
            self.load_data_combo.addItem("Nie znaleziono danych")
            self.load_data_btn.setText("Otwórz")
            self.next_button.setText("Następny")
            self.prev_button.setText("Poprzedni")
            self.column_axis.setTitle('Kanały')
            self.column_axis.setLabels([
                'Kanał 1', 'Kanał 2', 'Kanał 3', 'Kanał 4', 'Kanał 5',
                'Kanał 6', 'Kanał 7', 'Kanał 8', 'Kanał 9', 'Kanał 10',
                'Kanał 11', 'Kanał 12', 'Kanał 13'
            ])
            self.row_axis.setTitle('Oś czasu')
            self.bars.setColumnAxis(self.column_axis)
            self.bars.setRowAxis(self.row_axis)
        else:
            QCoreApplication.removeTranslator(self.trans)
            self.axis_x.setTitleText("Frequency [MHz]")
            self.freeze_check.setText("Freeze")
            self.load_data_check.setText("Load archival data")
            self.load_data_combo.removeItem(
                self.load_data_combo.findText("Nie znaleziono danych"))
            self.load_data_combo.addItem("No data found")
            self.load_data_btn.setText("Load")
            self.next_button.setText("Next")
            self.prev_button.setText("Previous")
            self.column_axis.setTitle('Channels')
            self.column_axis.setLabels([
                'Channel 1', 'Channel 2', 'Channel 3', 'Channel 4',
                'Channel 5', 'Channel 6', 'Channel 7', 'Channel 8',
                'Channel 9', 'Channel 10', 'Channel 11', 'Channel 12',
                'Channel 13'
            ])
            self.row_axis.setTitle('Timeline')
            self.bars.setColumnAxis(self.column_axis)
            self.bars.setRowAxis(self.row_axis)

    def append_data_from_database(self, data):
        """ DOCSTRING !!! """
        self.wifi_channels_occupancy_array = []
        self.wifi_channels_timestamps = []
        self.print_freshes_ten()

        for row in data:
            itm_nmbr = 0
            self.temp_db_array = []
            for item in row:
                if itm_nmbr == 1:
                    self.wifi_channels_timestamps.append(
                        "" + str(self.load_data_combo.currentText()) + " " +
                        item + "")
                elif itm_nmbr > 1:
                    self.temp_db_array.append(item)
                itm_nmbr += 1
            self.wifi_channels_occupancy_array.append(self.temp_db_array)
        self.print_freshes_ten()
Ejemplo n.º 10
0
class StockWindow:

    def __init__(self, excel_manager):
        self.excel_manager = excel_manager
        self.ui_file = QFile("product_select.ui")
        self.ui_file.open(QFile.ReadOnly)
        self.loader = QUiLoader()
        self.main_window = self.loader.load(self.ui_file)
        self.ui_file.close()
        self.main_window.show()

        # 콤보박스 객체 저장
        self.combobox_manufacturer = None
        self.combobox_product = None
        self.combobox_weight = None
        self.combobox_color = None
        self.combobox_size = None

        # 콤보박스 선택된 item Text
        self.combobox_manufacturer_text = None
        self.combobox_product_text = None
        self.combobox_weight_text = None
        self.combobox_color_text = None
        self.combobox_size_text = None

        # 제조사 콤보박스 객체 찾기
        cb = self.main_window.findChild(QtWidgets.QComboBox, "comboBox")
        self.combobox_manufacturer = cb
        # 제조사 콤보박스에 시그널 별로 슬랏 연결
        cb.activated.connect(self.activated_manufacturer)

        # 제품 콤보박스 객체 찾기
        cb2 = self.main_window.findChild(QtWidgets.QComboBox, "comboBox_2")
        self.combobox_product = cb2
        # 제품 콤보박스에 시그널 슬랏 연결
        cb2.activated.connect(self.activated_product)

        # 무게 콤보박스 객체 찾기
        cb3 = self.main_window.findChild(QtWidgets.QComboBox, "comboBox_3")
        self.combobox_weight = cb3
        # 제품 콤보박스에 시그널 슬랏 연결
        cb3.activated.connect(self.activated_weight)

        # 컬러 콤보박스 객체 찾기
        cb4 = self.main_window.findChild(QtWidgets.QComboBox, "comboBox_4")
        self.combobox_color = cb4
        # 제품 콤보박스에 시그널 슬랏 연결
        cb3.activated.connect(self.activated_color)

        self.combobox_add_manufacturer()



    def combobox_add_manufacturer(self):
        cb = self.combobox_manufacturer
        # 엑셀 메니저에서 제조사 리스트 가져오기
        mf_list = self.excel_manager.get_manufacturer()
        # 제조사 리스트 콤보박스에 아이템 추가
        cb.addItems(mf_list)



    def activated_manufacturer(self):
        print("activated")
        # 현재 선택된 아이템 저장
        text = self.combobox_manufacturer.currentText()
        self.combobox_manufacturer_text = text
        print(text)

        # 선택된 제조사를 보고 그 제조사 제품을 추가
        self.combobox_add_product()

    def combobox_add_product(self):
        # 제조사에 해당하는 제품 리스트 가져오기
        name = self.combobox_manufacturer_text
        p_list = self.excel_manager.get_products(name)
        print(p_list)

        # 제품 콤보박스에 제품리스트 추가
        cb2 = self.combobox_product
        cb2.addItems(p_list)

    def activated_product(self):
        print("activated")
        # 현재 선택된 아이템 저장
        text = self.combobox_product.currentText()
        self.combobox_product_text = text
        print(text)

        # 선택된 제조사를 보고 그 제조사 제품을 추가
        self.combobox_add_weight()

    def combobox_add_weight(self):
        name = self.combobox_product_text
        w_list = self.excel_manager.get_weight(name)
        print(w_list)

        cb3 = self.combobox_weight
        cb3.addItems(w_list)


    def activated_weight(self):
        print("activated")
        # 현재 선택된 아이템 저장
        text = self.combobox_weight.currentText()
        self.combobox_weight_text = text
        print(text)

        # 선택된 제조사를 보고 그 제조사 제품을 추가
        self.combobox_add_color()

    def combobox_add_color(self):
        name = self.combobox_weight_text
        c_list = self.excel_manager.get_color(name)
        print(c_list)

        cb4 = self.combobox_color
        cb4.addItems(c_list)

    def activated_color(self):
        print("activated")
        # 현재 선택된 아이템 저장
        text = self.combobox_color.currentText()
        self.combobox_color_text = text
        print(text)

        # 선택된 제조사를 보고 그 제조사 제품을 추가
        # self.combobox_add_size()

    def highlighted(self):
        print("highlighted")

    def idxchanged(self):
        print("idx changed")
Ejemplo n.º 11
0
# directly_loading_QML
import sys
from PySide2.QtUiTools import QUiLoader
from PySide2.QtWidgets import QApplication
from PySide2.QtCore import QFile

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

	ui_file=QFile('./mainwindow.ui')
	ui_file.open(QFile.ReadOnly)
	loader = QUiLoader()
	window = loader.load(ui_file)
	ui_file.close()

	window.show()

	sys.exit(app.exec_())
Ejemplo n.º 12
0
 def save_current_parameters(self):
     current_parameters = {
         'printer_setup': self.printer_setup,
         'projector_setup': self.projector_setup,
         'motor_setup': self.motor_setup,
         # Support Parameters
         'support_thickness (mm)': self.support_thickness,  # mm
         'support_exposure (ms)': self.support_exposure,  # ms
         'support_amplitude': self.support_amplitude,
         'support_burn_layers': self.support_burn_layers,
         'support_burn_exposure (ms)': self.support_burn_exposure,  # ms
         'support_burn_amplitude': self.support_burn_amplitude,
         # Features Parameters
         'features_thickness (mm)': self.features_thickness,  # mm
         'features_exposure (ms)': self.features_exposure,  # ms
         'features_amplitude': self.features_amplitude,
         'features_burn_layers': self.features_burn_layers,
         'features_burn_exposure (ms)': self.features_burn_exposure,  # ms
         'features_burn_amplitude': self.features_burn_amplitude,
         # Advanced Parameters
         'incremental_thickness': self.incremental_thickness,
         'incremental_exposure': self.incremental_exposure,
         'incremental_amplitude': self.incremental_amplitude,
         'starting_incremental_thickness (mm)':
         self.starting_incremental_thickness,  # mm
         'incremental_step_thickness (mm)':
         self.incremental_step_thickness,  # mm
         'starting_incremental_exposure (ms)':
         self.starting_incremental_exposure,  # ms
         'incremental_step_exposure (ms)':
         self.incremental_step_exposure,  # ms
         'starting_incremental_amplitude':
         self.starting_incremental_amplitude,
         'incremental_step_amplitude': self.incremental_step_amplitude,
         'fixed_layer': self.fixed_layer,
         'grayscale_correction': self.grayscale_correction,
         'grayscale_alpha': self.grayscale_alpha,
         'grayscale_beta': self.grayscale_beta,
         'grayscale_gamma': self.grayscale_gamma,
         # Others
         'projector_amplitude': self.projector_amplitude,
         'feed_rate (mm/min)': self.__motor_controller.feed_rate,  # mm/min
         'spindle_pitch_microns': self.spindle_pitch_microns,
         'motor_steps_per_revolution': self.motor_steps_per_revolution,
         'projector_feed_rate (mm/min)':
         self.__motor_controller.projector_feed_rate,
         'repositioning_delay (ms)':
         self.__motor_controller.repositioning_delay,  # ms
         'repositioning_offset (mm)':
         self.__motor_controller.repositioning_offset,  # mm
         'projector_pixel_size (mm)': self.projector_pixel_size,  # mm
         'projector_width': self.projector_width,
         'projector_height': self.projector_height,
         'horizontal_mirror': self.__projector_controller.horizontal_mirror,
         'vertical_mirror': self.__projector_controller.vertical_mirror,
         'samples_per_pixel': self.samples_per_pixel
     }
     base_path = Path(__file__).parent
     log_path = str((base_path / '../resources/PRINT_LOG.json').resolve())
     log_file = QFile(log_path)
     file_data = {}
     # if log_file.open(QIODevice.ReadOnly | QIODevice.Text):
     #     file_data = QJsonDocument.fromJson(log_file.readAll()).object()
     #     log_file.close()
     if log_file.open(QIODevice.ReadWrite | QIODevice.Append):
         # Print Job Parameters
         file_data['date (yyyy.MM.dd)'] = self.printing_date
         file_data['time (hh.mm.ss)'] = self.printing_time
         file_data['username'] = self.username
         file_data['print_job_name'] = self.print_job_name
         file_data['print_job_status'] = self.print_status
         file_data['total_layers'] = self.number_of_layers
         file_data['support_layers'] = len(self.support_file_names)
         file_data['features_layers'] = len(self.features_file_names)
         file_data['printed_layers'] = self.current_layer
         file_data["printer_type"] = "DLP"
         if self.print_status == "FAILED":
             file_data["error_message"] = self.error_message
         file_data["dlp_settings"] = current_parameters
         log_file.write(QJsonDocument(file_data).toJson())
         log_file.close()
Ejemplo n.º 13
0
 def __load_default_parameters__(self):
     self.__default_parameters = {
         'printer_setup': self.printer_setup,
         'projector_setup': self.projector_setup,
         'motor_setup': self.motor_setup,
         'support_thickness (mm)': 0.018,  # mm
         'support_exposure (ms)': 3000,  # ms
         'support_amplitude': 230,
         'support_burn_layers': 5,
         'support_burn_exposure (ms)': 15000,  # ms
         'support_burn_amplitude': 500,
         # Features Parameters
         'features_thickness (mm)': 0.018,  # mm
         'features_exposure (ms)': 3000,  # ms
         'features_amplitude': 230,
         'features_burn_layers': 0,
         'features_burn_exposure (ms)': 15000,  # ms
         'features_burn_amplitude': 500,
         # Advanced Parameters
         'incremental_thickness': False,
         'incremental_exposure': False,
         'incremental_amplitude': False,
         'starting_incremental_thickness (mm)': 0.001,  # mm
         'incremental_step_thickness (mm)': 0.001,  # mm
         'starting_incremental_exposure (ms)': 1000,  # ms
         'incremental_step_exposure (ms)': 100,  # ms
         'starting_incremental_amplitude': 10,
         'incremental_step_amplitude': 10,
         'fixed_layer': False,
         'grayscale_correction': False,
         'grayscale_alpha': 0,
         'grayscale_beta': 0,
         'grayscale_gamma': 0,
         # Others
         'projector_amplitude': 0,
         'horizontal_mirror': True,
         'vertical_mirror': False,
         'repositioning_delay (ms)': 500,  # ms
         'feed_rate (mm/min)': 300,  # mm/min
         'spindle_pitch_microns': 4000,
         'motor_steps_per_revolution': 6400,
         'projector_feed_rate (mm/min)': 300,
         'repositioning_offset (mm)': 5,  # mm
         'projector_pixel_size (mm)': 0.00754,  # mm
         'projector_width': 2560,
         'projector_height': 1600,
         'samples_per_pixel': 1
     }
     base_path = Path(__file__).parent
     settings_path = str(
         (base_path / '../resources/PRINTER_SETTINGS.json').resolve())
     settings_file = QFile(settings_path)
     if settings_file.open(QIODevice.ReadOnly | QIODevice.Text):
         file_data = QJsonDocument.fromJson(
             settings_file.readAll()).object()
         if "dlp_settings" in file_data:
             for key, value in self.__default_parameters.items():
                 if key in file_data["dlp_settings"]:
                     new_value = file_data["dlp_settings"][key]
                     self.__default_parameters[key] = new_value
         settings_file.close()
Ejemplo n.º 14
0
class Sender(QRunnable):
    class Signals(QObject):
        update_status = Signal(int)

    def __init__(self,
                 portname: str,
                 filepath: str,
                 baudrate: int,
                 databits: str,
                 parity: str,
                 stopbits_: str,
                 flowcontrol_: str,
                 parent: QObject = None):
        super(Sender, self).__init__(parent)
        self.file = QFile(filepath)
        self.errorString = 'Unknown error'
        self.signals = self.Signals()
        self.portname = portname
        self.baudrate = baudrate
        self.bytesize = bytesize.get(databits)
        self.parity = parities.get(parity)
        self.stopbits = stopbits.get(stopbits_)
        self.flowcontrol = flowcontrol_
        self.xonoff = (self.flowcontrol == 'SoftwareControl')
        self.rtscts = (self.flowcontrol == 'HardwareControl')
        self.port = Serial(
            port=self.portname,
            baudrate=self.baudrate,
            parity=self.parity,
            stopbits=self.stopbits,
            bytesize=self.bytesize,
            xonxoff=self.xonoff,
            rtscts=self.rtscts,
            dsrdtr=False,
            timeout=None,
            write_timeout=10.0  # 10s
        )
        self.cancelled = False

    def run(self):
        if not self.port.isOpen():
            self.errorString = ("Could not open port %s" % self.portname)
            return
        self.file.open(QFile.ReadOnly)
        line = self.file.readLine()
        while not self.cancelled:
            if self.port.write(bytes(line.data())) > 0:
                print(str(line))
                self.signals.update_status.emit(self.file.pos())
                if not self.file.atEnd():
                    line = self.file.readLine()
                else:
                    break
        if self.cancelled:
            self.port.reset_output_buffer()
            self.port.flushOutput()
            self.port.flush()
        else:
            self.port.flush()
        self.file.close()
        self.port.close()

    @Slot()
    def cancel(self):
        self.cancelled = True
Ejemplo n.º 15
0
    def __init__(self, ui_file, application, parent=None):
        super(Form, self).__init__(parent)
        self.application = application

        # ================================
        #    Load Window
        # ================================
        ui_file = QFile(ui_file)
        ui_file.open(QFile.ReadOnly)
        loader = QUiLoader()
        self.window = loader.load(ui_file)
        ui_file.close()

        # ===================================
        # Instantiate some window properties
        # ===================================
        # Collection
        self.collection_path = None
        self.collection_working_path = getcwd()
        self.cobj = None
        self.document = None
        self.matches = None
        self.shelf_path = None
        self.shelf_working_path = getcwd()
        self.query_list = []  # visual list for the GUI
        self.queries = []  # shelve object list
        self.formatted_queries = []
        self.selected_query = None

        # Single Document
        self.file_path = None
        self.working_path = getcwd()

        # Mutual
        self.results = None
        self.num_sentences = 5
        self.num_keywords = 10

        # ================================
        # Locate and bind window children
        # ================================
        # menuBar -> menuTools
        action_load = self.window.findChild(QAction, 'actionLoadQL')
        action_load.triggered.connect(self.browse_and_load)
        action_refresh = self.window.findChild(QAction, 'actionRefresh')
        action_refresh.triggered.connect(self.refresh)

        # centralWidget -> tabWidget
        self.tab_widget = self.window.findChild(QTabWidget, 'tabWidget')

        # -----------------------------
        # tabWidget -> Collection Panel
        # -----------------------------

        # centralWidget -> collection
        self.line_collection_path = self.window.findChild(
            QPlainTextEdit, 'collectionPathInput')
        self.line_collection_path.textChanged.connect(
            self.check_collection_path)
        butt_browse_collection_path = self.window.findChild(
            QPushButton, 'collectionBrowseButton')
        butt_browse_collection_path.clicked.connect(
            self.browse_collection_path)

        # centralWidget -> Process Collection
        self.butt_process_collection_processing = self.window.findChild(
            QPushButton, 'processButton')
        self.butt_process_collection_processing.clicked.connect(
            self.process_configuration)
        self.prog_bar = self.window.findChild(QProgressBar, 'progressBar')
        self.prog_label = self.window.findChild(QLabel, 'progressLabel')

        # centralWidget -> queryFiles
        self.line_query_path = self.window.findChild(QPlainTextEdit,
                                                     'queryPathInput')
        self.line_query_path.textChanged.connect(self.check_query_path)
        butt_browse_query_path = self.window.findChild(QPushButton,
                                                       'queryBrowseButton')
        butt_browse_query_path.clicked.connect(self.browse_shelf_path)
        self.butt_load_query_path = self.window.findChild(
            QPushButton, 'queryLoadButton')
        self.butt_load_query_path.clicked.connect(self.load_shelf_file)
        butt_open_query_builder = self.window.findChild(
            QPushButton, 'openQueryBuilderButton')
        butt_open_query_builder.clicked.connect(open_query_builder)

        # centralWidget -> querySelection
        self.combo_query = self.window.findChild(QComboBox, 'queriesCombo')
        self.combo_query.currentIndexChanged.connect(self.set_query_combo)
        self.clear_query = self.window.findChild(QPushButton,
                                                 'clearQueryButton')
        self.clear_query.clicked.connect(self.clear_query_box)

        # centralWidget -> Query Options
        self.spin_sentence_buffer = self.window.findChild(
            QSpinBox, 'spinSentenceBuffer')

        # centralWidget -> Summary Options
        self.radio_full = self.window.findChild(QRadioButton, 'radioFull')
        self.radio_reduced = self.window.findChild(QRadioButton,
                                                   'radioReduced')
        self.radio_reduced.setChecked(True)  # reduced by default
        self.spin_num_sentences_collection = self.window.findChild(
            QSpinBox, 'spinSentencesCollection')
        self.spin_num_sentences_collection.valueChanged.connect(
            self.set_sentences_collection)
        self.spin_num_words_collection = self.window.findChild(
            QSpinBox, 'spinWordsCollection')
        self.spin_num_words_collection.valueChanged.connect(
            self.set_words_collection)

        # centralWidget -> Apply Query
        self.butt_apply_query = self.window.findChild(QPushButton,
                                                      'applyQueryButton')
        self.butt_apply_query.clicked.connect(self.apply_query)

        # -----------------------------------
        # tabWidget -> Single Document Panel
        # -----------------------------------

        # centralWidget -> file
        self.line_file_path = self.window.findChild(QPlainTextEdit,
                                                    'filePathInput')
        self.line_file_path.textChanged.connect(self.enable_summary_button)
        butt_browse_file_path = self.window.findChild(QPushButton,
                                                      'fileBrowseButton')
        butt_browse_file_path.clicked.connect(self.browse_file_path)

        # centralWidget -> Customization
        self.spin_num_sentences = self.window.findChild(
            QSpinBox, 'spinSentences')
        self.spin_num_sentences.valueChanged.connect(self.set_sentences)
        self.spin_num_words = self.window.findChild(QSpinBox, 'spinWords')
        self.spin_num_words.valueChanged.connect(self.set_words)

        # centralWidget -> Apply Query
        self.butt_summarize = self.window.findChild(QPushButton,
                                                    'summarizeButton')
        self.butt_summarize.clicked.connect(self.apply_summary)

        # -----------------------------
        # tabWidget -> Results Panel
        # -----------------------------

        # centralWidget -> view results
        self.results_text = self.window.findChild(QPlainTextEdit, 'outputText')
        self.results_text.textChanged.connect(self.enable_save_results_button)
        self.butt_save_results = self.window.findChild(QPushButton,
                                                       'saveOutputButton')
        self.butt_save_results.clicked.connect(self.write_results)

        # -----------------------------
        # tabWidget -> Results Panel
        # -----------------------------

        # centralWidget -> view matches
        self.matches_text = self.window.findChild(QPlainTextEdit,
                                                  'outputMatches')

        # ========
        #   Show
        # ========
        self.window.show()
Ejemplo n.º 16
0
    def __init__(self, parent=None):
        try:
            super().__init__(parent)
            loader = QUiLoader()
            file = QFile(os.path.abspath("forms/MainWindow.ui"))
            file.open(QFile.ReadOnly)
            ui = loader.load(file, self)
            file.close()
            self.setLayout(ui.layout())

            # Components
            self.clipboard = QGuiApplication.clipboard()
            self.desktop = QDesktopWidget()
            self.trans_label = self.findChild(QLabel, "transLabel")
            self.transparent_slider = self.findChild(QSlider,
                                                     "transparentSlider")
            self.interface_frame = self.findChild(QFrame, "interfaceFrame")
            self.hide_button = self.findChild(QPushButton, "hideButton")
            self.enable_box = self.findChild(QCheckBox, "enableBox")
            self.on_top_box = self.findChild(QCheckBox, "onTopBox")
            self.clear_button = self.findChild(QPushButton, "clearButton")

            self.system_tray = SystemTray(self)

            self.currentScreen = 0
            self.currentPosition = 0

            self.is_on_top = True
            self.is_enable = True
            self.is_show_panel = True
            self.is_not_fixed = True
            self.is_grab = False
            self.is_follow_cursor = False

            # Instances
            self.config = config_parser.Configuration()
            self.trans_request = web_api.YouDaoRequest(self.config)
            self.translate_thread = threads.TranslatorThread(
                self.config, self.trans_request, self.get_clip_text, self)

            # initialize
            self._initialize()
            # self.trans_label.setAttribute(QtCore.Qt.WA_TransparentForMouseEvents, True);

            # register
            QObject.connect(self.enable_box, SIGNAL("stateChanged(int)"), self,
                            SLOT("_set_enabled(int)"))
            QObject.connect(self.on_top_box, SIGNAL("stateChanged(int)"), self,
                            SLOT("_set_on_top(int)"))
            QObject.connect(self.translate_thread, SIGNAL("finished()"), self,
                            SLOT("_translate()"))
            QObject.connect(self.transparent_slider,
                            SIGNAL("valueChanged(int)"), self,
                            SLOT("_set_transparent(int)"))
            QObject.connect(self.clipboard, SIGNAL("dataChanged()"), self,
                            SLOT("translate()"))
            QObject.connect(self.desktop, SIGNAL("resized(int)"), self,
                            SLOT("_set_geometry()"))
            QObject.connect(self.hide_button, SIGNAL("clicked()"), self,
                            SLOT("hide_interface()"))

        except TranslatorException as e:
            err_box = QMessageBox(self.parent())
            err_box.setText(str(e))
            err_box.exec_()
            sys.exit(-1)
Ejemplo n.º 17
0
    def __init__(self, ui_file, parent=None):

        #call parent QObject constructor
        super(MainWindow, self).__init__(parent)

        #load the UI file into Python
        ui_file = QFile(ui_file)
        ui_file.open(QFile.ReadOnly)
        loader = QUiLoader()
        self.window = loader.load(ui_file)

        #always remember to close files
        ui_file.close()

        #add event listener to the 7 button
        sevenButton = self.window.findChild(QPushButton, 'sevenButton')
        sevenButton.clicked.connect(self.seven_button_clicked)

        eightButton = self.window.findChild(QPushButton, 'eightButton')
        eightButton.clicked.connect(self.eight_button_clicked)

        nineButton = self.window.findChild(QPushButton, 'nineButton')
        nineButton.clicked.connect(self.nine_button_clicked)

        fourButton = self.window.findChild(QPushButton, 'fourButton')
        fourButton.clicked.connect(self.four_button_clicked)

        fiveButton = self.window.findChild(QPushButton, 'fiveButton')
        fiveButton.clicked.connect(self.five_button_clicked)

        sixButton = self.window.findChild(QPushButton, 'sixButton')
        sixButton.clicked.connect(self.six_button_clicked)

        oneButton = self.window.findChild(QPushButton, 'oneButton')
        oneButton.clicked.connect(self.one_button_clicked)

        twoButton = self.window.findChild(QPushButton, 'twoButton')
        twoButton.clicked.connect(self.two_button_clicked)

        threeButton = self.window.findChild(QPushButton, 'threeButton')
        threeButton.clicked.connect(self.three_button_clicked)

        zeroButton = self.window.findChild(QPushButton, 'zeroButton')
        zeroButton.clicked.connect(self.zero_button_clicked)

        divideButton = self.window.findChild(QPushButton, 'divideButton')
        divideButton.clicked.connect(self.divide)

        multiplyButton = self.window.findChild(QPushButton, 'multiplyButton')
        multiplyButton.clicked.connect(self.multiply)

        addButton = self.window.findChild(QPushButton, 'addButton')
        addButton.clicked.connect(self.add)

        subtractButton = self.window.findChild(QPushButton, 'subtractButton')
        subtractButton.clicked.connect(self.subtract)

        equalsButton = self.window.findChild(QPushButton, 'equalsButton')
        equalsButton.clicked.connect(self.equals)

        #show window to user
        self.window.show()
Ejemplo n.º 18
0
    def __init__(self):
        QObject.__init__(self)

        self.module_path = os.path.dirname(__file__)

        self.mouse_pressed = False
        self.draw_ellipse = False
        self.write_text = False
        self.mouse_pressed_x = 0
        self.mouse_pressed_y = 0
        self.tables = []
        self.ellipses = []
        self.texts = []

        self.text_event_filter = TextEventFilter(self)

        # loading widgets from designer file

        loader = QUiLoader()

        loader.registerCustomWidget(QtCharts.QChartView)

        self.window = loader.load(self.module_path +
                                  "/ui/application_window.ui")

        self.tab_widget = self.window.findChild(QTabWidget, "tab_widget")
        chart_frame = self.window.findChild(QFrame, "chart_frame")
        chart_cfg_frame = self.window.findChild(QFrame, "chart_cfg_frame")
        self.chart_view = self.window.findChild(QtCharts.QChartView,
                                                "chart_view")
        button_add_tab = self.window.findChild(QPushButton, "button_add_tab")
        button_reset_zoom = self.window.findChild(QPushButton,
                                                  "button_reset_zoom")
        button_save_image = self.window.findChild(QPushButton,
                                                  "button_save_image")
        self.label_mouse_coords = self.window.findChild(
            QLabel, "label_mouse_coords")
        self.radio_zoom = self.window.findChild(QRadioButton, "radio_zoom")
        self.radio_ellipse = self.window.findChild(QRadioButton,
                                                   "radio_ellipse")
        self.radio_text = self.window.findChild(QRadioButton, "radio_text")

        # Creating QChart
        self.chart = QtCharts.QChart()
        self.chart.setAnimationOptions(QtCharts.QChart.AllAnimations)
        self.chart.setTheme(QtCharts.QChart.ChartThemeLight)
        self.chart.setAcceptHoverEvents(True)

        self.axis_x = QtCharts.QValueAxis()
        self.axis_x.setTitleText("PC1")
        self.axis_x.setRange(-10, 10)
        self.axis_x.setLabelFormat("%.1f")

        self.axis_y = QtCharts.QValueAxis()
        self.axis_y.setTitleText("PC2")
        self.axis_y.setRange(-10, 10)
        self.axis_y.setLabelFormat("%.1f")

        self.chart.addAxis(self.axis_x, Qt.AlignBottom)
        self.chart.addAxis(self.axis_y, Qt.AlignLeft)

        self.chart_view.setChart(self.chart)
        self.chart_view.setRenderHint(QPainter.Antialiasing)
        self.chart_view.setRubberBand(QtCharts.QChartView.RectangleRubberBand)

        # 1 tab by default

        self.add_tab()

        # custom stylesheet

        style_file = QFile(self.module_path + "/ui/custom.css")
        style_file.open(QFile.ReadOnly)

        self.window.setStyleSheet(style_file.readAll().data().decode("utf-8"))

        style_file.close()

        # effects

        self.tab_widget.setGraphicsEffect(self.card_shadow())
        chart_frame.setGraphicsEffect(self.card_shadow())
        chart_cfg_frame.setGraphicsEffect(self.card_shadow())
        button_add_tab.setGraphicsEffect(self.button_shadow())
        button_reset_zoom.setGraphicsEffect(self.button_shadow())
        button_save_image.setGraphicsEffect(self.button_shadow())

        # signal connection

        self.tab_widget.tabCloseRequested.connect(self.remove_tab)
        button_add_tab.clicked.connect(self.add_tab)
        button_reset_zoom.clicked.connect(self.reset_zoom)
        button_save_image.clicked.connect(self.save_image)
        self.radio_zoom.toggled.connect(self.on_mouse_function_changed)
        self.radio_ellipse.toggled.connect(self.on_mouse_function_changed)
        self.radio_text.toggled.connect(self.on_mouse_function_changed)

        # event filter

        self.chart.installEventFilter(self)

        # show window

        self.window.show()
Ejemplo n.º 19
0
class EditIncomingActs(QWidget):
    def __init__(self, action, parent=None):
        super(EditIncomingActs, self).__init__(parent)
        self.path = os.path.join('faces', 'edit_invoicing.ui')
        self.ui_file = QFile(self.path)
        self.ui_file.open(QFile.ReadOnly)
        self.loader = QUiLoader()
        self.dialog = self.loader.load(self.ui_file, self)
        self.ui_file.close()

        self.action = action

        # определим элементы управления
        self.date_edit = self.dialog.findChild(QDateEdit, 'date_edit')
        self.table_service = self.dialog.findChild(QTableWidget,
                                                   'table_service')
        self.comment_edit = self.dialog.findChild(QLineEdit, 'comment_edit')
        self.table_total = self.dialog.findChild(QTableWidget, 'table_total')
        self.cmbox_company = self.dialog.findChild(QComboBox, 'cmbox_company')
        self.btn_save = self.dialog.findChild(QPushButton, 'btn_save')
        self.btn_add = self.dialog.findChild(QPushButton, 'btn_add')
        self.btn_changed = self.dialog.findChild(QPushButton, 'btn_changed')
        self.btn_delete = self.dialog.findChild(QPushButton, 'btn_delete')

        # назначим подсказки для элементов
        self.btn_save.setToolTip('Сохранить акт')
        self.btn_add.setToolTip('Добавить услугу, товар')
        self.btn_changed.setToolTip('Изменить услугу, товар')
        self.btn_delete.setToolTip('Удалить услугу, товар')

        # задаём специальные размеров колонок основной таблицы
        self.table_service.setColumnWidth(0, 329)  # наименование услуг
        self.table_service.setColumnWidth(1, 100)  # количество
        self.table_service.setColumnWidth(2, 100)  # цена
        self.table_service.setColumnWidth(3, 100)  # сумма

        # задаём специальные размеров колонок итоговой таблицы
        self.table_total.setColumnWidth(0, 549)  # наименование услуг
        self.table_total.setColumnWidth(1, 80)  # количество

        # замена имени колонки в форме
        self.table_total.horizontalHeaderItem(0).setText('Итого по актам')

        # добавляем значения по умолчанию: текущую дату
        self.date_edit.setDate(QDate.currentDate())
        # список контроагентов
        result = conn.query(Counterparties).all()
        if result:
            for elem in result:
                self.cmbox_company.addItem(str(elem.name_c))

        # назначим подсказки для элементов
        self.btn_add.setToolTip('Добавить')
        self.btn_delete.setToolTip('Удалить')

        # назначим действия для объектов
        self.btn_save.clicked.connect(self.save_service)
        self.btn_add.clicked.connect(self.insert_service)
        self.btn_changed.clicked.connect(self.edit_service)
        self.btn_delete.clicked.connect(self.dell_service)

    # метод добавление данных в новую строку
    def set_data_in_new_row(self, data: list):
        rows = self.table_service.rowCount()
        self.table_service.setRowCount(int(rows + 1))
        columns = self.table_service.columnCount()
        for i in range(0, columns):
            item = QtWidgets.QTableWidgetItem(str(data[i]))
            self.table_service.setItem(rows, i, item)

    # метод добавление данных в текущую строку
    def set_data_in_current_row(self, data: list):
        selected_row = self.table_service.currentItem()
        id_row = self.table_service.row(selected_row)
        columns = self.table_service.columnCount()
        for i in range(0, columns):
            item = QtWidgets.QTableWidgetItem(str(data[i]))
            self.table_service.setItem(id_row, i, item)

    # Возвращает список значений строки таблицы
    def get_value_row(self, current_row):
        value_cells = []
        if self.table_service.isItemSelected(current_row):
            index_row = self.table_service.row(current_row)
            columns = self.table_service.columnCount()
            for column in range(0, columns):
                value_cells.append(
                    self.table_service.item(index_row, column).text())
        return value_cells

    # метод суммирования стоимости услуг
    def total_summ(self):
        # собираем значения последних ячеек по строкам
        value_cells = []
        columns = self.table_service.columnCount()
        rows = self.table_service.rowCount()
        for row in range(0, rows):
            value = self.table_service.item(row, columns - 1).text()
            value_cells.append(float(value))
        summ = sum(value_cells)
        # вставляем сумму
        self.table_total.horizontalHeaderItem(1).setText(str(summ))

    # метод заполнения таблицы
    def filling_table(self, row):
        self.table_service.setRowCount(int(0))  # удаляем строки
        self.set_data_in_new_row(row)

    # метод отображения окна
    def work_with_service(self, selector):
        self.win = ServiceForInvoice(selector)
        self.id_selected_row = ''  # ID выделенной строки
        if selector == 'add':
            self.win.setWindowTitle('Добавить услугу')
            self.start_win()
        else:
            # получаем выделенную строку
            selected_row = self.table_service.currentItem()
            if selector == 'dell':
                id_row = self.table_service.row(selected_row)
                self.table_service.removeRow(id_row)
            elif selector == 'edit':
                # получаем значения ячеек выделенной строки
                value_cells = self.get_value_row(selected_row)
                # вставляем исходные значения: название услуги
                for i in range(self.win.cmbox_service.count()):
                    if self.win.cmbox_service.itemText(i) == value_cells[0]:
                        self.win.cmbox_service.setCurrentIndex(i)
                self.win.amount_service.setText(value_cells[1])  # количество
                self.win.price_service.setText(value_cells[2])  # стоимость
                self.start_win()
        self.total_summ()

    # запуск окна
    def start_win(self):
        self.win.setWindowModality(Qt.ApplicationModal)
        self.win.setWindowFlags(Qt.Window)
        self.win.btn_action.clicked.connect(self.add_upt_dell)
        self.win.btn_exit.clicked.connect(self.win.close)
        self.win.show()

    # метод модального окна "Дорбавления услуг"
    def add_upt_dell(self):
        if self.win.action == 'add' or self.win.action == 'edit':
            # получаем данные из дочернего окна:
            new_service = [
                self.win.cmbox_service.currentText(),
                self.win.amount_service.text(),
                self.win.price_service.text(),
                self.win.summ_service.text()
            ]
            # вставляем данные а таблицу
            if self.win.action == 'edit':
                # вставляем данные в туже строку
                self.set_data_in_current_row(new_service)
            else:
                self.set_data_in_new_row(new_service)
            self.win.close()
            self.total_summ()

    # сохранение услуг
    def save_service(self):
        if not self.action == 'edit':
            self.action = 'save'

    # метод добавления услуг
    def insert_service(self):
        self.work_with_service('add')

    # метод редактирования услуг
    def edit_service(self):
        if self.table_service.isItemSelected(self.table_service.currentItem()):
            self.work_with_service('edit')

    # метод удаления виделеной строки
    def dell_service(self):
        if self.table_service.isItemSelected(self.table_service.currentItem()):
            self.work_with_service('dell')
Ejemplo n.º 20
0
class ShowBankDocs(QWidget):
    def __init__(self, parent=None):
        super(ShowBankDocs, self).__init__(parent)
        self.path = os.path.join('faces', 'show_bank_docs.ui')

        self.ui_file = QFile(self.path)
        self.ui_file.open(QFile.ReadOnly)
        self.loader = QUiLoader()
        self.dialog = self.loader.load(self.ui_file, self)
        self.ui_file.close()



        # определим элементы управления
        self.label = self.dialog.findChild(QLabel, 'label')
        self.date_start = self.dialog.findChild(QDateEdit, 'date_start')
        self.date_end = self.dialog.findChild(QDateEdit, 'date_end')
        self.cmbox_company = self.dialog.findChild(QComboBox, 'cmbox_company')
        self.cmbox_action = self.dialog.findChild(QComboBox, 'cmbox_action')
        self.btn_create = self.dialog.findChild(QPushButton, 'btn_create')

        # назначим подсказки для элементов
        self.btn_create.setToolTip('Сформировать отчёт')

        # добавляем значения по умолчанию: текущую дату
        self.date_start.setDate(QDate.currentDate())
        self.date_end.setDate(QDate.currentDate())
        # список контроагентов
        result = conn.query(Counterparties).all()
        if result:
            for elem in result:
                self.cmbox_company.addItem(str(elem.name_c))

        # назначим действия для объектов
        self.btn_create.clicked.connect(self.create_report)

        self.setMaximumHeight(225)
        self.setMaximumWidth(473)

    def create_report(self):
        # собираем условия с формы
        # name_company = self.cmbox_company.currentText()
        # id_company = conn.query(Counterparties).filter(Counterparties.name_c == name_company).first().id

        # data_start = self.date_start.text()
        # data_end = self.date_end.text()
        # action = self.cmbox_action.currentText()  # приход / расход
        # формируем запрос в базу
        bank_query = conn.query(BankDocsRev).filter(BankDocsRev.date_docs >= self.date_start.date().toPython()).filter(BankDocsRev.date_docs <= self.date_end.date().toPython()).filter(BankDocsRev.action_docs == self.cmbox_action.currentText()).all()
        for item in bank_query:
            print(f'Контрагент: {item.p_counterparties.name_c}, сумма: {item.summ_docs:.2f}, статус документа: {item.action_docs}')
        # определяем пути к файлам
        path_empty = os.path.join('templates', 'report_bank.ods')
        path_full = os.path.join('temp', 'report_bank.ods')
        t = Template(path_empty, path_full)

        items = list()
        total_summ = 0

        # перебираем значения из запроса
        for bank in bank_query:
            item = Item()
            item.date = bank.date_docs.strftime('%d.%m.%Y')
            # item.summ = str(round(bank.summ_docs, 2)).replace('.', ',')
            item.summ = round(bank.summ_docs, 2)
            item.counterp = bank.p_counterparties.name_c
            item.coment = bank.comment_docs
            items.append(item)
            total_summ += bank.summ_docs
        
        # формируем даты
        start_date = Item()
        start_date.date = datetime.strftime(self.date_start.date().toPython(), '%d.%m.%Y')

        end_date = Item()
        end_date.date = datetime.strftime(self.date_end.date().toPython(), '%d.%m.%Y')

        total = Item()
        # total.summ = str(round(total_summ, 2)).replace('.', ',')
        total.summ = round(total_summ, 2)
        
        # группируем данные для передачи в отчёт
        date = dict(items = items, start_date = start_date, end_date = end_date, total = total)

        # передаём данные в отчёт
        t.render(date)

        # открываем созданный отчёт
        if sys.platform == "win32":
                os.startfile(path_full)
        else:
            opener ="open" if sys.platform == "darwin" else "xdg-open"
            subprocess.call([opener, path_full])
Ejemplo n.º 21
0
class ShowInvoice(QWidget):
    def __init__(self, action, parent=None):
        super(ShowInvoice, self).__init__(parent)
        self.path = os.path.join('faces', 'invoicing.ui')

        self.ui_file = QFile(self.path)
        self.ui_file.open(QFile.ReadOnly)
        self.loader = QUiLoader()
        self.dialog = self.loader.load(self.ui_file, self)
        self.ui_file.close()

        self.action = action

        # определим элементы управления
        self.label = self.dialog.findChild(QLabel, 'label')
        self.table_bill = self.dialog.findChild(QTableWidget, 'table_bill')
        self.btn_add = self.dialog.findChild(QPushButton, 'btn_add')
        self.btn_changed = self.dialog.findChild(QPushButton, 'btn_changed')
        self.btn_delete = self.dialog.findChild(QPushButton, 'btn_delete')

        # назначим подсказки для элементов
        self.btn_changed.setToolTip('Выбрать счёт для создание акта')

        # задаём специальные размеров колонок
        self.table_bill.setColumnWidth(0, 80)  # дата
        self.table_bill.setColumnWidth(1, 80)  # сумма
        self.table_bill.setColumnWidth(2, 160)  # контрагент
        # колонка "комментарий" использует остаток пространства

        # смена названия кнопок
        self.btn_changed.setText('Выбрать')

        # убираем лишние кнопки
        self.btn_add.hide()
        self.btn_delete.hide()

        self.period = []
        self.id_invoices = []  # ID данных загружаемых из таблицы Invoice
        self.filling_table()

    # метод формирование надписи
    def change_period(self):
        query_list = conn.query(Invoice).filter(Invoice.date_invoice).all()
        data_list = []
        for elem in query_list:
            data_list.append(elem.date_invoice.strftime("%d.%m.%Y"))
        data_list.sort(key=lambda d: datetime.strptime(d, '%d.%m.%Y'))
        if data_list:
            first = data_list[0]
            last = data_list[-1]
            self.label.setText(f'C {first} по {last}')

    # метод добавление данных в новую строку
    def set_data_in_new_row(self, data: list):
        rows = self.table_bill.rowCount()
        self.table_bill.setRowCount(int(rows + 1))
        columns = self.table_bill.columnCount()
        for i in range(0, columns):
            item = QtWidgets.QTableWidgetItem(str(data[i]))
            self.table_bill.setItem(rows, i, item)

    # метод заполнения таблицы
    def filling_table(self):
        self.table_bill.setRowCount(int(0))  # удаляем строки
        items = conn.query(Invoice).all()
        self.id_invoices = []
        for item in items:
            # пересохраняем объект таблицы в строчку
            row = []
            self.id_invoices.append(item.id)

            row.append(item.date_invoice.strftime("%d.%m.%Y"))
            row.append(item.summ_invoice)
            name_company = conn.query(Counterparties).filter(
                Counterparties.id == item.id_company).first().name_c
            row.append(name_company)
            row.append(item.comment_invoice)
            # вставляем строчку в таблицу
            self.set_data_in_new_row(row)
        self.change_period()

    # метод возвращвет ID выбранного счёта
    def selected_invoice(self):
        selected_row = self.table_bill.currentItem()
        index_row = self.table_bill.row(selected_row)
        result = self.id_invoices[index_row]
        return result
Ejemplo n.º 22
0
    def __init__(self):
        QObject.__init__(self)

        self.module_path = os.path.dirname(__file__)

        self.tables = []
        self.series_dict = dict()

        n_cpu_cores = cpu_count()

        print("number of cpu cores: ", n_cpu_cores)

        self.pool = Pool(processes=n_cpu_cores)
        self.coins = Coins(self.pool)
        self.model = Model()
        self.chart = QtCharts.QChart()
        self.callout = Callout(self.chart)

        self.callout.hide()

        # loading widgets from designer file

        loader = QUiLoader()

        loader.registerCustomWidget(QtCharts.QChartView)

        self.window = loader.load(self.module_path +
                                  "/ui/application_window.ui")

        main_frame = self.window.findChild(QFrame, "main_frame")
        chart_frame = self.window.findChild(QFrame, "chart_frame")
        chart_cfg_frame = self.window.findChild(QFrame, "chart_cfg_frame")
        button_read_tags = self.window.findChild(QPushButton,
                                                 "button_read_tags")
        button_save_matrix = self.window.findChild(QPushButton,
                                                   "button_save_matrix")
        button_save_image = self.window.findChild(QPushButton,
                                                  "button_save_image")
        button_reset_zoom = self.window.findChild(QPushButton,
                                                  "button_reset_zoom")
        self.table_view = self.window.findChild(QTableView, "table_view")
        self.chart_view = self.window.findChild(QtCharts.QChartView,
                                                "chart_view")
        self.label_mouse_coords = self.window.findChild(
            QLabel, "label_mouse_coords")

        self.table_view.horizontalHeader().setSectionResizeMode(
            QHeaderView.ResizeToContents)
        self.table_view.verticalHeader().setSectionResizeMode(
            QHeaderView.ResizeToContents)
        self.table_view.setModel(self.model)

        # signal connection

        button_read_tags.clicked.connect(self.read_tags)
        button_save_matrix.clicked.connect(self.save_matrix)
        button_save_image.clicked.connect(self.save_image)
        button_reset_zoom.clicked.connect(self.reset_zoom)
        self.table_view.selectionModel().selectionChanged.connect(
            self.selection_changed)
        self.coins.new_spectrum.connect(self.on_new_spectrum)
        self.model.dataChanged.connect(self.data_changed)

        # Creating QChart
        self.chart.setAnimationOptions(QtCharts.QChart.AllAnimations)
        self.chart.setTheme(QtCharts.QChart.ChartThemeLight)
        self.chart.setAcceptHoverEvents(True)

        self.axis_x = QtCharts.QValueAxis()
        self.axis_x.setTitleText("Energy [keV]")
        self.axis_x.setRange(0, 100)
        self.axis_x.setLabelFormat("%.0f")

        self.axis_y = QtCharts.QValueAxis()
        self.axis_y.setTitleText("Intensity [a.u.]")
        self.axis_y.setRange(0, 100)
        self.axis_y.setLabelFormat("%d")

        self.chart.addAxis(self.axis_x, Qt.AlignBottom)
        self.chart.addAxis(self.axis_y, Qt.AlignLeft)

        self.chart_view.setChart(self.chart)
        self.chart_view.setRenderHint(QPainter.Antialiasing)
        self.chart_view.setRubberBand(QtCharts.QChartView.RectangleRubberBand)

        # custom stylesheet

        style_file = QFile(self.module_path + "/ui/custom.css")
        style_file.open(QFile.ReadOnly)

        self.window.setStyleSheet(style_file.readAll().data().decode("utf-8"))

        style_file.close()

        # effects

        main_frame.setGraphicsEffect(self.card_shadow())
        chart_frame.setGraphicsEffect(self.card_shadow())
        chart_cfg_frame.setGraphicsEffect(self.card_shadow())
        button_read_tags.setGraphicsEffect(self.button_shadow())
        button_save_matrix.setGraphicsEffect(self.button_shadow())
        button_save_image.setGraphicsEffect(self.button_shadow())
        button_reset_zoom.setGraphicsEffect(self.button_shadow())

        self.window.show()