Exemplo n.º 1
0
    def on_connectButton_clicked(self):

        if not self.connect_status:

            portl = self.comboBoxL.currentText()
            portr = self.comboBoxR.currentText()

            if portl == "":
                portl = 'loop://'

            if portr == "":
                portr = 'loop://'

            try:
                self.serL = serial.serial_for_url(
                    portl,
                    baudrate=int(self.comboBoxLBaudrate.currentText()),
                    bytesize=int(self.comboBoxLBytesizes.currentText()),
                    parity=self.comboBoxLParity.currentText(),
                    stopbits=float(self.comboBoxLStopbits.currentText()),
                    timeout=TIMEOUT_READLINE)
            except serial.serialutil.SerialException as e:
                QMessageBox.warning(
                    None, "", "Unable to open serial port " + portl + ".")
                return

            try:
                self.serR = serial.serial_for_url(
                    portr,
                    baudrate=int(self.comboBoxRBaudrate.currentText()),
                    bytesize=int(self.comboBoxLBytesizes.currentText()),
                    parity=self.comboBoxLParity.currentText(),
                    stopbits=float(self.comboBoxLStopbits.currentText()),
                    timeout=TIMEOUT_READLINE)
            except serial.serialutil.SerialException as e:
                QMessageBox.warning(
                    None, "", "Unable to open serial port " + portr + ".")
                return

            self.sioL = io.TextIOWrapper(
                io.BufferedRWPair(self.serL, self.serL))
            self.sioR = io.TextIOWrapper(
                io.BufferedRWPair(self.serR, self.serR))

            # test code
            # self.sioL.write(u"hello l")
            # self.sioL.flush()
            # self.sioR.write(u"hello r")
            # self.sioR.flush()

            self.connectButton.setText(DISCONNECT_LABEL)
            self.connect_status = True
            self.textL.append(CONNECT_LABEL + " " + str(self.serL))
            self.textR.append(CONNECT_LABEL + " " + str(self.serR))

            self.timer = QTimer(self)
            self.timer.timeout.connect(self.timeout)
            self.timer.start(TIMEOUT_TIMER)
        else:

            self.timer.stop()

            self.serL.close()
            self.serR.close()

            self.serL = None
            self.serR = None

            self.sioL = None
            self.sioR = None

            self.connectButton.setText(CONNECT_LABEL)
            self.connect_status = False
            self.textL.append(DISCONNECT_LABEL)
            self.textR.append(DISCONNECT_LABEL)
Exemplo n.º 2
0
    def initUI(self, path_to_options):
        """ initialize the view-scene graphic environment """
        self.scene = QGraphicsScene()
        #self.scene.setSceneRect(0, 0, 640, 480)
        self.view = QGraphicsViewExtend(self.scene)
        self.view.setSceneRect(QRectF(self.view.viewport().rect()))
        self.view.setSceneRect(QRectF(0, 0, 850, 900))
        self.view.setRenderHint(QPainter.Antialiasing)
        layout = QGridLayout()
        layout.addWidget(self.view)
        self.setLayout(layout)
        self.setBackgroundColor(QColor('green'))

        # special properties
        self.svgCardsPath = "../cards"
        self.cardsGraphItems = []  #holds all the cards items
        self.defInsertionPos = QPointF(0, 0)
        self.defAngle = 0
        self.defScale = 0.5
        self.deckBackSVG = 'back_1'
        self.numOfPlayers = 4
        self.playersHandsPos = [(75, 50, 0), (210, 50, 180), (680, 50, 0),
                                (210, 385, 0)]  #(x,y,angle)
        self.defHandSpacing = 24
        self.midCards = []
        self.options_file_path = path_to_options

        # Card fields
        pen = QPen()
        brush = QBrush()
        self.scene.addRect(QRectF(200, 230, 100, 80), pen, brush)
        self.scene.addRect(QRectF(200 + 120, 230, 100, 80), pen, brush)
        self.scene.addRect(QRectF(200 + 120 * 2, 230, 100, 80), pen, brush)
        self.scene.addRect(QRectF(200 + 120 * 3, 230, 100, 80), pen, brush)

        # Player Names
        self.player1_label = self.addPlayerLabel(425, 350, "Player 1")
        self.player2_label = self.addPlayerLabel(0, 240, "Player 2")
        self.player3_label = self.addPlayerLabel(425, 20, "Player 3")
        self.player4_label = self.addPlayerLabel(782, 240, "Player 4")

        self.card1_label = self.addPlayerLabel(200, 210, "")
        self.card2_label = self.addPlayerLabel(200 + 120, 210, "")
        self.card3_label = self.addPlayerLabel(200 + 120 * 2, 210, "")
        self.card4_label = self.addPlayerLabel(200 + 120 * 3, 210, "")

        self.card_label_l = [
            self.card1_label, self.card2_label, self.card3_label,
            self.card4_label
        ]
        self.card_label_pla = [
            self.player1_label, self.player2_label, self.player3_label,
            self.player4_label
        ]

        self.play_1_state = self.addPlayerLabel(200, 250, "")
        self.play_2_state = self.addPlayerLabel(200 + 120, 250, "")
        self.play_3_state = self.addPlayerLabel(200 + 120 * 2, 250, "")
        self.play_4_state = self.addPlayerLabel(200 + 120 * 3, 250, "")
        self.game_indicator = self.addPlayerLabel(650, 5, "Game: ")
        self.mode_label = self.addPlayerLabel(150, 5, "Mode: ")

        playbtn = QPushButton('Start', self)
        playbtn.resize(50, 32)
        playbtn.move(10, 10)
        playbtn.clicked.connect(self.start_clicked)

        options = QPushButton('Options', self)
        options.resize(80, 32)
        options.move(65, 10)
        options.clicked.connect(self.options_clicked)

        nextRound = QPushButton('nextRound', self)
        nextRound.resize(80, 32)
        nextRound.move(150, 10)
        nextRound.setVisible(False)
        nextRound.clicked.connect(self.nextRound_clicked)

        self.scene.addWidget(playbtn)
        self.scene.addWidget(nextRound)
        self.scene.addWidget(options)

        self.my_game = None

        # Testing tree:
        self.my_tree = None

        # Storing game_play
        self.game_play = {}

        self.corrString = ""
        # emit signal:
        self.server_receivedSig.connect(self.parseClient)

        ### Client stuff:
        self.clientTimer = QTimer(self)
        self.tcpSocket = None
        self.games_played = 0
        self.reset_client()

        self.server_thread = None
                humidity FLOAT,
                timestamp CHAR(30),
                PRIMARY KEY(id))"""
    try:
        cur.execute(sql_command)
        db.commit()
        print ("Database Initialized")
    except:
        db.rollback()

    """PyQt5 initialization"""
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    mygui = gui_functionality(MainWindow)
    MainWindow.show()
    
    
    """Timer Iniitalization for 15 seconds"""
    timer = QTimer()
    timer.timeout.connect(mygui.get_sensor_data)
    timer.start(15000)
    
    """Multithreading"""
    thread1 = threading.Thread(target = tornado_thread)
    thread1.start()
    
    sys.exit(app.exec_())
    thread1.join()


Exemplo n.º 4
0
    def __init__(self, qapp, bbackups, check_interval, environments,
                 graphical_editor, log_path, terminal_command):
        # Reference to main PyQt.QApplication
        self.qapp = qapp

        # Config-defined editor to use when showing borg command output
        self.graphical_editor = graphical_editor

        # Store path to log file
        self.log_path = log_path

        # Save prepared function for terminal command generation
        self.terminal_command = terminal_command

        # Load all tray icon files
        self.icon = QIcon("icons/icon.png")
        self.icon_running = [
            QIcon("icons/icon_running0.png"),
            QIcon("icons/icon_running1.png"),
            QIcon("icons/icon_running2.png"),
            QIcon("icons/icon_running3.png"),
            QIcon("icons/icon_running4.png"),
            QIcon("icons/icon_running5.png"),
            QIcon("icons/icon_running6.png"),
            QIcon("icons/icon_running7.png")
        ]
        self.icon_running_idx = 0
        self.icon_error = QIcon("icons/icon_error.png")
        self.icon_ok = QIcon("icons/icon_ok.png")
        self.icon_attention = QIcon("icons/icon_attention.png")

        # Load icons for menu
        self.micon_exit = QIcon("icons/micon_exit.png")
        self.micon_info = QIcon("icons/micon_info.png")
        self.micon_run = QIcon("icons/micon_run.png")
        self.micon_log = QIcon("icons/micon_log.png")
        self.micon_console = QIcon("icons/micon_console.png")

        # Keep track of borg backups
        self.bbackups = deque(bbackups)
        self.bbackups_ = deque()

        # Keep track of stati of borg backups and other commands
        # This dict determines which icon is displayed in tray
        self.status = {}

        # Get all environments (BEnv objects)
        self.environments = environments

        # Setup tray icon
        self.qapp.setQuitOnLastWindowClosed(False)
        self.tray = QSystemTrayIcon()
        self.tray.setIcon(self.icon)

        # Create right-click menu for tray
        self.menu = QMenu()

        self.exit_action = QAction("Exit", self.qapp)
        self.exit_action.triggered.connect(self.click_exit)
        self.exit_action.setIcon(self.micon_exit)
        self.menu.addAction(self.exit_action)

        self.borg_list_actions = {}
        self.borg_create_actions = {}
        self.borg_console_actions = {}
        for bbackup in self.bbackups:
            self.menu.addSeparator()
            self.borg_list_actions[bbackup.name] = QAction(
                'List "%s"' % bbackup.name, self.qapp)
            self.borg_list_actions[bbackup.name].triggered.connect(
                partial(self.click_borg_list, bbackup))
            self.borg_list_actions[bbackup.name].setIcon(self.micon_info)
            self.menu.addAction(self.borg_list_actions[bbackup.name])

            self.borg_create_actions[bbackup.name] = QAction(
                'Run "%s" now' % bbackup.name, self.qapp)
            self.borg_create_actions[bbackup.name].triggered.connect(
                partial(self.click_borg_create, bbackup))
            self.borg_create_actions[bbackup.name].setIcon(self.micon_run)
            self.menu.addAction(self.borg_create_actions[bbackup.name])

            if self.terminal_command is not None:
                self.borg_console_actions[bbackup.name] = QAction(
                    'Open console for "%s"' % bbackup.name, self.qapp)
                self.borg_console_actions[bbackup.name].triggered.connect(
                    partial(self.click_borg_console, bbackup))
                self.borg_console_actions[bbackup.name].setIcon(
                    self.micon_console)
                self.menu.addAction(self.borg_console_actions[bbackup.name])

        self.menu.addSeparator()
        self.log_action = QAction('Show log')
        self.log_action.triggered.connect(self.click_log)
        self.log_action.setIcon(self.micon_log)
        self.menu.addAction(self.log_action)

        self.tray.setContextMenu(self.menu)

        # Setup main timer and set interval to config-defined value
        self.main_timer = QTimer()
        self.main_timer.setInterval(check_interval * 1000)
        self.main_timer.timeout.connect(self.timed)

        # Setup icon update timer with interval of 200ms
        self.status_timer = QTimer()
        self.status_timer.setInterval(200)
        self.status_timer.timeout.connect(self.update_status)

        # Instantiate a thread pool for long running operations later
        self.thread_pool = QThreadPool()

        # Display tray icon
        self.tray.setVisible(True)

        # Create status variables
        self.cur = None
        self.busy = False
        self.valid_envs = []
        self.user_mode = False

        # Trigger normally timer-triggered function first
        self.timed()
        # Then start timers
        self.main_timer.start()
        self.status_timer.start()

        logging.debug(
            'Setup main qt app, main_timer started with interval of %d seconds.'
            % (check_interval, ))
Exemplo n.º 5
0
    def __init__(self, LOGIN, parent=None):
        self.LOGIN = LOGIN
        self.db = dataBase(self.LOGIN, "Brewing")
        super().__init__(parent)
        self.setWindowTitle('Fermentation tanks')
        self.batchInTank = {}

        self.tabs = QTabWidget()
        self.tabSg = FermentSgTab(database=self.db, parent=parent)
        self.tabTemp = FermentTempTab(database=self.db, parent=parent)
        self.tabs.resize(100, 1000)

        self.tabs.addTab(self.tabSg, "Gravity")
        self.tabs.addTab(self.tabTemp, "Temperature")

        self.dropDownBox = QComboBox()
        self.updateTankDropdown()
        self.dropDownGraphBox = QComboBox()
        self.dropDownGraphBox.addItem("Specific Gravity")
        self.dropDownGraphBox.addItem("Temperature")
        # self.dropDownGraphBox.addItem("Volume")

        self.dropDownBox.currentIndexChanged.connect(self.indexChanged)

        quitButton = QPushButton(self.tr('&Close'))
        quitButton.clicked.connect(self.closeWindow)
        quitLayout = QHBoxLayout()
        quitLayout.addStretch(10)
        quitLayout.addWidget(quitButton)

        currentValuetimer = QTimer(self)
        currentValuetimer.timeout.connect(self.updateCurrentValues)
        currentValuetimer.start(1000)

        self.recipelayout = QGridLayout()

        nameLabel = QLabel("Recipe:")
        self.nameValue = QLabel()

        dateLabel = QLabel("Date:")
        self.dateValue = QLabel()

        brewIDLabel = QLabel("Brew ID:")
        self.brewIDValue = QLabel()

        setTempLabel = QLabel("Set temperature:")
        self.setTempValue = QLabel()

        currentTempLabel = QLabel("Current temperature:")
        self.currentTempValue = QLabel()

        currentSgLabel = QLabel("Current specific gravity:")
        self.currentSgValue = QLabel()

        self.recipelayout.addWidget(nameLabel, 0, 0)
        self.recipelayout.addWidget(self.nameValue, 0, 1)
        self.recipelayout.addWidget(dateLabel, 1, 0)
        self.recipelayout.addWidget(self.dateValue, 1, 1)
        self.recipelayout.addWidget(brewIDLabel, 2, 0)
        self.recipelayout.addWidget(self.brewIDValue, 2, 1)
        self.recipelayout.addWidget(setTempLabel, 3, 0)
        self.recipelayout.addWidget(self.setTempValue, 3, 1)
        self.recipelayout.addWidget(currentTempLabel, 4, 0)
        self.recipelayout.addWidget(self.currentTempValue, 4, 1)
        self.recipelayout.addWidget(currentSgLabel, 5, 0)
        self.recipelayout.addWidget(self.currentSgValue, 5, 1)

        buttonlayout = QVBoxLayout()
        buttonlayout.addWidget(self.dropDownBox)
        buttonlayout.addLayout(self.recipelayout)
        buttonlayout.addStretch(10)

        tablayout = QHBoxLayout()
        tablayout.addLayout(buttonlayout)
        tablayout.addWidget(self.tabs)

        mainlayout = QVBoxLayout()
        mainlayout.addLayout(tablayout)
        mainlayout.addLayout(quitLayout)

        self.setLayout(mainlayout)

        self.recipeUpdate(self.batchInTank["1"])
        self.tabSg.changeTank(1)
        self.tabTemp.changeTank(1)
Exemplo n.º 6
0
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.t = None

        self.setWindowTitle('RF1201 Card Reader Tool - ' + getProgVer())

        for port in serial.tools.list_ports.comports():
            self.ui.cob_Com.addItem(port[0])
        self.ui.cob_Com.setCurrentText(self.myConfig.getComPort())
        self.reader = Reader(self.ui.cob_Com.currentText())
        # self.ui.pb_OpenOrClose.setAttribute(Qt.WA_NativeWindow)
        self.ui.pb_OpenOrClose.setText(getTxt('openPort'))
        # self.ui.lbl_Com.setPixmap(QtGui.QPixmap("ico/off.png"))
        self.ui.lbl_Com.setPixmap(QtGui.QPixmap(":/ico/off.png"))
        self.ui.te_Recv.setReadOnly(True)
        self.ui.lbl_Status.setText('')
        self.ui.lbl_Tip.setText('')

        for x in range(0, 64):
            self.ui.cob_BlockNo.addItem('%02d' % x)

        self.ui.cob_Channel.addItem('Contactless Card')
        self.ui.cob_Channel.addItem('CPU Card')
        self.ui.cob_Channel.addItem('SAM Card')

        for x in range(3):
            self.ui.cob_SamSlot.addItem('Slot %d' % x)

        self.ui.cob_SamBaudrate.addItem('9600')
        self.ui.cob_SamBaudrate.addItem('38400')
        self.ui.cob_SamBaudrate.addItem('19200')
        self.ui.cob_SamBaudrate.addItem('56000')
        self.ui.cob_SamBaudrate.addItem('115200')

        self.ui.le_KeyA.setText('A0A1A2A3A4A5')
        self.ui.le_KeyB.setText('FFFFFFFFFFFF')

        self.ui.le_RfResetMs.setText('1')

        self.ui.le_WriteBlock.setMaxLength(32)
        self.ui.le_KeyA.setMaxLength(12)
        self.ui.le_KeyB.setMaxLength(12)

        self.timerTip = QTimer(self)
        self.timerTip.timeout.connect(self.timerTipProc)

        self.ui.pb_OpenOrClose.clicked.connect(self.on_pb_OpenOrClose_Clicked)
        self.ui.cob_Com.currentIndexChanged.connect(
            self.on_cob_Com_CurrentIndexChanged)
        self.ui.pb_ClearRecv.clicked.connect(self.on_pb_ClearRecv_Clicked)
        self.ui.pb_Beep.clicked.connect(self.on_pb_Beep)
        self.ui.pb_Request.clicked.connect(self.on_pb_Request)
        self.ui.pb_RequestAll.clicked.connect(self.on_pb_RequestAll)
        self.ui.pb_Anticol.clicked.connect(self.on_pb_Anticol)
        self.ui.pb_SelectCard.clicked.connect(self.on_pb_SelectCard)
        self.ui.pb_FoundCard.clicked.connect(self.on_pb_FoundCard)
        self.ui.pb_HaltCard.clicked.connect(self.on_pb_HaltCard)
        self.ui.pb_ReadBlock.clicked.connect(self.on_pb_ReadBlock)
        self.ui.pb_WriteBlock.clicked.connect(self.on_pb_WriteBlock)
        self.ui.pb_LoadKeyA.clicked.connect(self.on_pb_LoadKeyA)
        self.ui.pb_AuthKeyA.clicked.connect(self.on_pb_AuthKeyA)
        self.ui.pb_LoadKeyB.clicked.connect(self.on_pb_LoadKeyB)
        self.ui.pb_AuthKeyB.clicked.connect(self.on_pb_AuthKeyB)
        self.ui.pb_ReadValue.clicked.connect(self.on_pb_ReadValue)
        self.ui.pb_WriteValue.clicked.connect(self.on_pb_WriteValue)
        self.ui.pb_IncValue.clicked.connect(self.on_pb_IncValue)
        self.ui.pb_DecValue.clicked.connect(self.on_pb_DecValue)
        self.ui.pb_Restore.clicked.connect(self.on_pb_Restore)
        self.ui.pb_Transfer.clicked.connect(self.on_pb_Transfer)
        self.ui.pb_SelectChannel.clicked.connect(self.on_pb_SelectChannel)
        self.ui.pb_SelectSamSlot.clicked.connect(self.on_pb_SelectSamSlot)
        self.ui.pb_SelectSamBaudrate.clicked.connect(
            self.on_pb_SelectSamBaudrate)
        self.ui.pb_CpuReset.clicked.connect(self.on_pb_CpuReset)
        self.ui.pb_CpuDeselect.clicked.connect(self.on_pb_CpuDeselect)
        self.ui.pb_CosCmd.clicked.connect(self.on_pb_CosCmd)
        self.ui.pb_ReadSid.clicked.connect(self.on_pb_ReadSid)
        self.ui.pb_ReadLkt4210Info.clicked.connect(self.on_pb_ReadLkt4210Info)
        self.ui.pb_RfReset.clicked.connect(self.on_pb_RfReset)
        self.ui.pb_CpuPps.clicked.connect(self.on_pb_CpuPps)
        self.ui.pb_CalcKeyBs.clicked.connect(self.on_pb_CalcKeyBs)
        self.ui.pb_ReadAllBlocks.clicked.connect(self.on_pb_ReadAllBlocks)
        self.ui.pb_ClearCard.clicked.connect(self.on_pb_ClearCard)
        self.ui.pb_CPU_Consume.clicked.connect(self.on_pb_CPU_Consume)

        # QtWidgets.QWidget.setTabOrder(self.ui.cob_Com, self.ui.pb_OpenOrClose)
        # QtWidgets.QWidget.setTabOrder(
        #     self.ui.pb_OpenOrClose, self.ui.chk_HexRecv)
        # QtWidgets.QWidget.setTabOrder(
        #     self.ui.chk_HexRecv, self.ui.pb_ClearRecv)
        # QtWidgets.QWidget.setTabOrder(
        #     self.ui.pb_ClearRecv, self.ui.chk_HexSend)
        # QtWidgets.QWidget.setTabOrder(self.ui.chk_HexSend, self.ui.pb_Send)
        # QtWidgets.QWidget.setTabOrder(self.ui.pb_Send, self.ui.cob_Com)

        self.show()
Exemplo n.º 7
0
 def export(self):
     timer = QTimer(self.view)
     timer.setSingleShot(True)
     timer.timeout.connect(self.run)
     timer.start()
Exemplo n.º 8
0
    def __init__(self,
                 title,
                 message,
                 item,
                 *args,
                 ntype=0,
                 callback=None,
                 **kwargs):
        super(NotificationItem, self).__init__(*args, **kwargs)
        self.item = item
        self.callback = callback
        layout = QHBoxLayout(self, spacing=0)
        layout.setContentsMargins(0, 0, 0, 0)
        self.bgWidget = QWidget(self)  # 背景控件, 用于支持动画效果
        layout.addWidget(self.bgWidget)

        layout = QGridLayout(self.bgWidget)
        layout.setHorizontalSpacing(15)
        layout.setVerticalSpacing(10)

        # 标题左边图标
        layout.addWidget(QLabel(self, pixmap=NotificationIcon.icon(ntype)), 0,
                         0)

        # 标题
        self.labelTitle = QLabel(title, self)
        font = self.labelTitle.font()
        font.setBold(True)
        font.setPixelSize(22)
        self.labelTitle.setFont(font)

        # 关闭按钮
        self.labelClose = QLabel(self,
                                 cursor=Qt.PointingHandCursor,
                                 pixmap=NotificationIcon.icon(
                                     NotificationIcon.Close))

        # 消息内容
        self.labelMessage = QLabel(message,
                                   self,
                                   cursor=Qt.PointingHandCursor,
                                   wordWrap=True,
                                   alignment=Qt.AlignLeft | Qt.AlignTop)
        font = self.labelMessage.font()
        font.setPixelSize(20)
        self.labelMessage.setFont(font)
        self.labelMessage.adjustSize()

        # 添加到布局
        layout.addWidget(self.labelTitle, 0, 1)
        layout.addItem(
            QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum), 0,
            2)
        layout.addWidget(self.labelClose, 0, 3)
        layout.addWidget(self.labelMessage, 1, 1, 1, 2)

        # 边框阴影
        effect = QGraphicsDropShadowEffect(self)
        effect.setBlurRadius(12)
        effect.setColor(QColor(0, 0, 0, 25))
        effect.setOffset(0, 2)
        self.setGraphicsEffect(effect)

        self.adjustSize()

        # 5秒自动关闭
        self._timer = QTimer(self, timeout=self.doClose)
        self._timer.setSingleShot(True)  # 只触发一次
        self._timer.start(5000)
Exemplo n.º 9
0
 def setupGL(self):
     scene = self.scene()
     # win = self.scene_root_item.window()
     self.is_GL = True
     self.is_GL_switch_allowed = True
     self.qTimer = QTimer()
Exemplo n.º 10
0
 def refreshCycle(self):
     self.timer = QTimer(self)
     self.timer.timeout.connect(self.refreshTable)
     self.timer.setInterval(1500)
     self.timer.start()
Exemplo n.º 11
0
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        # Find out where the engine is located, and how it is called.
        # This depends on how Cura is packaged and which OS we are running on.
        executable_name = "CuraEngine"
        if Platform.isWindows():
            executable_name += ".exe"
        default_engine_location = executable_name
        if os.path.exists(
                os.path.join(Application.getInstallPrefix(), "bin",
                             executable_name)):
            default_engine_location = os.path.join(
                Application.getInstallPrefix(), "bin", executable_name)
        if hasattr(sys, "frozen"):
            default_engine_location = os.path.join(
                os.path.dirname(os.path.abspath(sys.executable)),
                executable_name)
        if Platform.isLinux() and not default_engine_location:
            if not os.getenv("PATH"):
                raise OSError(
                    "There is something wrong with your Linux installation.")
            for pathdir in os.getenv("PATH").split(os.pathsep):
                execpath = os.path.join(pathdir, executable_name)
                if os.path.exists(execpath):
                    default_engine_location = execpath
                    break

        if not default_engine_location:
            raise EnvironmentError("Could not find CuraEngine")

        Logger.log("i", "Found CuraEngine at: %s" % (default_engine_location))

        default_engine_location = os.path.abspath(default_engine_location)
        Preferences.getInstance().addPreference("backend/location",
                                                default_engine_location)

        # Workaround to disable layer view processing if layer view is not active.
        self._layer_view_active = False
        Application.getInstance().getController().activeViewChanged.connect(
            self._onActiveViewChanged)
        self._onActiveViewChanged()
        self._stored_layer_data = []
        self._stored_optimized_layer_data = []

        self._scene = Application.getInstance().getController().getScene()
        self._scene.sceneChanged.connect(self._onSceneChanged)

        # Triggers for when to (re)start slicing:
        self._global_container_stack = None
        Application.getInstance().globalContainerStackChanged.connect(
            self._onGlobalStackChanged)
        self._onGlobalStackChanged()

        self._active_extruder_stack = None
        ExtruderManager.getInstance().activeExtruderChanged.connect(
            self._onActiveExtruderChanged)
        self._onActiveExtruderChanged()

        # Listeners for receiving messages from the back-end.
        self._message_handlers["cura.proto.Layer"] = self._onLayerMessage
        self._message_handlers[
            "cura.proto.LayerOptimized"] = self._onOptimizedLayerMessage
        self._message_handlers["cura.proto.Progress"] = self._onProgressMessage
        self._message_handlers[
            "cura.proto.GCodeLayer"] = self._onGCodeLayerMessage
        self._message_handlers[
            "cura.proto.GCodePrefix"] = self._onGCodePrefixMessage
        self._message_handlers[
            "cura.proto.PrintTimeMaterialEstimates"] = self._onPrintTimeMaterialEstimates
        self._message_handlers[
            "cura.proto.SlicingFinished"] = self._onSlicingFinishedMessage

        self._start_slice_job = None
        self._slicing = False  # Are we currently slicing?
        self._restart = False  # Back-end is currently restarting?
        self._tool_active = False  # If a tool is active, some tasks do not have to do anything
        self._always_restart = True  # Always restart the engine when starting a new slice. Don't keep the process running. TODO: Fix engine statelessness.
        self._process_layers_job = None  # The currently active job to process layers, or None if it is not processing layers.
        self._need_slicing = False
        self._engine_is_fresh = True  # Is the newly started engine used before or not?

        self._backend_log_max_lines = 20000  # Maximum number of lines to buffer
        self._error_message = None  # Pop-up message that shows errors.
        self._last_num_objects = 0  # Count number of objects to see if there is something changed
        self._postponed_scene_change_sources = [
        ]  # scene change is postponed (by a tool)

        self.backendQuit.connect(self._onBackendQuit)
        self.backendConnected.connect(self._onBackendConnected)

        # When a tool operation is in progress, don't slice. So we need to listen for tool operations.
        Application.getInstance().getController().toolOperationStarted.connect(
            self._onToolOperationStarted)
        Application.getInstance().getController().toolOperationStopped.connect(
            self._onToolOperationStopped)

        self._slice_start_time = None

        Preferences.getInstance().addPreference("general/auto_slice", True)

        self._use_timer = False
        # When you update a setting and other settings get changed through inheritance, many propertyChanged signals are fired.
        # This timer will group them up, and only slice for the last setting changed signal.
        # TODO: Properly group propertyChanged signals by whether they are triggered by the same user interaction.
        self._change_timer = QTimer()
        self._change_timer.setSingleShot(True)
        self._change_timer.setInterval(500)
        self.determineAutoSlicing()
        Preferences.getInstance().preferenceChanged.connect(
            self._onPreferencesChanged)
Exemplo n.º 12
0
 def init_pygame(self, game):
     # https://stackoverflow.com/questions/46656634/pyqt5-qtimer-count-until-specific-seconds
     self.game = game
     self.timer = QTimer()
     self.timer.timeout.connect(self.pygame_loop)
     self.timer.start(0)
Exemplo n.º 13
0
    def __init__(self, proto_analyzer: ProtocolAnalyzer, undo_stack: QUndoStack,
                 project_manager, proto_bits=None, parent=None):
        super().__init__(parent)

        self.undo_stack = undo_stack

        self.ui = Ui_SignalFrame()
        self.ui.setupUi(self)

        self.__set_spectrogram_adjust_widgets_visibility()
        self.ui.gvSignal.init_undo_stack(self.undo_stack)

        fixed_font = QFontDatabase.systemFont(QFontDatabase.FixedFont)
        fixed_font.setPointSize(QApplication.instance().font().pointSize())
        self.ui.txtEdProto.setFont(fixed_font)
        self.ui.txtEdProto.participants = project_manager.participants
        self.ui.txtEdProto.messages = proto_analyzer.messages

        self.ui.gvSignal.participants = project_manager.participants

        self.setAttribute(Qt.WA_DeleteOnClose)
        self.project_manager = project_manager

        self.proto_analyzer = proto_analyzer
        self.signal = proto_analyzer.signal if self.proto_analyzer is not None else None  # type: Signal
        self.ui.gvSignal.protocol = self.proto_analyzer
        self.ui.gvSignal.set_signal(self.signal)
        self.ui.sliderFFTWindowSize.setValue(int(math.log2(Spectrogram.DEFAULT_FFT_WINDOW_SIZE)))
        self.ui.sliderSpectrogramMin.setValue(self.ui.gvSpectrogram.scene_manager.spectrogram.data_min)
        self.ui.sliderSpectrogramMax.setValue(self.ui.gvSpectrogram.scene_manager.spectrogram.data_max)

        self.dsp_filter = Filter([0.1] * 10, FilterType.moving_average)
        self.set_filter_button_caption()
        self.filter_dialog = FilterDialogController(self.dsp_filter, parent=self)

        self.proto_selection_timer = QTimer()  # For Update Proto Selection from ROI
        self.proto_selection_timer.setSingleShot(True)
        self.proto_selection_timer.setInterval(1)

        self.spectrogram_update_timer = QTimer()
        self.spectrogram_update_timer.setSingleShot(True)
        self.spectrogram_update_timer.setInterval(500)

        # Disabled because never used (see also set_protocol_visibilty())
        self.ui.chkBoxSyncSelection.hide()

        if self.signal is not None:
            self.filter_menu = QMenu()
            self.apply_filter_to_selection_only = self.filter_menu.addAction(self.tr("Apply only to selection"))
            self.apply_filter_to_selection_only.setCheckable(True)
            self.apply_filter_to_selection_only.setChecked(False)
            self.configure_filter_action = self.filter_menu.addAction("Configure filter...")
            self.configure_filter_action.setIcon(QIcon.fromTheme("configure"))
            self.configure_filter_action.triggered.connect(self.on_configure_filter_action_triggered)
            self.ui.btnFilter.setMenu(self.filter_menu)

            if self.signal.qad_demod_file_loaded:
                self.ui.lSignalTyp.setText("Quad-Demod Signal (*.wav)")
            elif self.signal.wav_mode:
                self.ui.lSignalTyp.setText("Realpart Signal (*.wav)")
            else:
                self.ui.lSignalTyp.setText("Complex Signal")

            self.ui.gvLegend.hide()
            self.ui.lineEditSignalName.setText(self.signal.name)
            self.ui.lSamplesInView.setText("{0:,}".format(self.signal.num_samples))
            self.ui.lSamplesTotal.setText("{0:,}".format(self.signal.num_samples))
            self.sync_protocol = self.ui.chkBoxSyncSelection.isChecked()
            self.ui.chkBoxSyncSelection.hide()

            self.ui.splitter.setSizes([self.ui.splitter.height(), 0])

            self.protocol_selection_is_updateable = True

            self.scene_manager = SignalSceneManager(self.signal, self)
            self.ui.gvSignal.scene_manager = self.scene_manager
            self.ui.gvSignal.setScene(self.scene_manager.scene)

            self.jump_sync = True
            self.on_btn_show_hide_start_end_clicked()

            self.refresh_signal_information(block=True)
            self.create_connects()
            self.set_protocol_visibility()

            self.ui.chkBoxShowProtocol.setChecked(True)
            self.set_qad_tooltip(self.signal.noise_threshold)
            self.ui.btnSaveSignal.hide()

            self.show_protocol(refresh=False)

        else:
            self.ui.btnFilter.setDisabled(True)
            self.ui.lSignalTyp.setText("Protocol")

            scene, nsamples = SignalSceneManager.create_rectangle(proto_bits)

            self.ui.lSamplesInView.setText("{0:n}".format(int(nsamples)))
            self.ui.lSamplesTotal.setText("{0:n}".format(int(nsamples)))
            self.ui.gvSignal.setScene(scene)
            self.ui.btnReplay.hide()

            self.create_connects()
            self.ui.btnSaveSignal.hide()
Exemplo n.º 14
0
    def initUI(self):

        #Layout'ların tanımlanması
        self.mainVerticalLayout = QVBoxLayout()
        self.headerLayout = QHBoxLayout()
        self.upLayout = QHBoxLayout()
        self.middleLayout = QHBoxLayout()
        self.downLayout = QHBoxLayout()
        self.notificationLayout = QHBoxLayout()

        # Widgetlerin tanımlanması,tasarımının yapılması ve Layout'lara yüklenmesi.

        self.header = QLabel()
        self.header.setText("Kullanıcı Girişi")
        self.header.setStyleSheet("""
        font-family:Courier;
        font-size:32px;
        color:#003366;
        border-left: 4px solid #221354;

        padding:3px;
        background-color: lightgrey;
        """)
        self.headerLayout.addStretch()
        self.headerLayout.addWidget(self.header)
        self.headerLayout.addStretch()

        self.userNameLabel = QLabel()
        self.userNameLabel.setText("Kullanıcı Adı : ")
        self.userNameLabel.setStyleSheet("""
        border-right:4px solid #221354;          
        font-family:Verdana;
        font-size:14px;
        color:#201A1E;
        """)
        self.userNameLineEdit = QLineEdit()
        self.userNameLineEdit.setMaximumWidth(150)

        self.upLayout.addStretch()
        self.upLayout.addWidget(self.userNameLabel)
        self.upLayout.addWidget(self.userNameLineEdit)
        self.upLayout.addStretch()

        self.passwordLabel = QLabel()
        self.passwordLabel.setText("                 Şifre : ")
        self.passwordLabel.setStyleSheet("""
        font-family:Verdana;
        font-size:14px;
        color:#201A1E;
        """)
        self.passwordLineEdit = QLineEdit()
        self.passwordLineEdit.setMaximumWidth(150)
        self.readablePassword = QRadioButton()

        self.timer = QTimer()
        self.timer.timeout.connect(self._update)
        self.timer.start(1000)

        self.middleLayout.addStretch()
        self.middleLayout.addWidget(self.passwordLabel)
        self.middleLayout.addWidget(self.passwordLineEdit)
        self.middleLayout.addWidget(self.readablePassword)
        self.middleLayout.addStretch()

        self.registerbutton = QPushButton("Kayıt")
        self.registerbutton.setStyleSheet("""
        color:  #80004d;
        background-color:#aaaaaa;
        font-weight: 650 ;
        font-style:Verdana;       
        """)
        shadow = QGraphicsDropShadowEffect(blurRadius=5, xOffset=3, yOffset=3)
        self.registerbutton.setGraphicsEffect(shadow)
        self.registerbutton.clicked.connect(
            self.register
        )  #Kayıt sayfasına yönlendirecek fonksiyonun çağrılması

        self.loginbutton = QPushButton("Giriş")
        self.loginbutton.setStyleSheet("""
        color: #008080;
        background-color:#aaaaaa;
        font-weight: 650 ;
        font-style:Verdana;       
        """)
        shadow = QGraphicsDropShadowEffect(blurRadius=5, xOffset=3, yOffset=3)
        self.loginbutton.setGraphicsEffect(shadow)
        self.loginbutton.clicked.connect(
            self.login
        )  #Veritabanında bilgi kontrolünü yapacak fonksiyonun çağrılması

        self.downLayout.addStretch()
        self.downLayout.addWidget(self.loginbutton)
        self.downLayout.addWidget(self.registerbutton)

        self.registeredNotificationLabel = QLabel()
        self.registeredNotificationImage = QLabel()

        self.notificationLayout.addStretch()
        self.notificationLayout.addWidget(self.registeredNotificationImage)
        self.notificationLayout.addWidget(self.registeredNotificationLabel)
        self.notificationLayout.addStretch()

        #İşlenen Layout'ların ana Layout'a eklenmesi
        self.mainVerticalLayout.addStretch()
        self.mainVerticalLayout.addLayout(self.headerLayout)
        self.mainVerticalLayout.addLayout(self.upLayout)
        self.mainVerticalLayout.addLayout(self.middleLayout)
        self.mainVerticalLayout.addLayout(self.downLayout)
        self.mainVerticalLayout.addLayout(self.notificationLayout)
        self.mainVerticalLayout.addStretch()

        self.setAutoFillBackground(True)
        p = self.palette()
        p.setColor(self.backgroundRole(), QColor(240, 250, 253))
        self.setPalette(p)

        self.setLayout(self.mainVerticalLayout)
Exemplo n.º 15
0
    def __init__(self) -> None:
        super().__init__()
        # Find out where the engine is located, and how it is called.
        # This depends on how Cura is packaged and which OS we are running on.
        executable_name = "CuraEngine"
        if Platform.isWindows():
            executable_name += ".exe"
        default_engine_location = executable_name
        if os.path.exists(
                os.path.join(CuraApplication.getInstallPrefix(), "bin",
                             executable_name)):
            default_engine_location = os.path.join(
                CuraApplication.getInstallPrefix(), "bin", executable_name)
        if hasattr(sys, "frozen"):
            default_engine_location = os.path.join(
                os.path.dirname(os.path.abspath(sys.executable)),
                executable_name)
        if Platform.isLinux() and not default_engine_location:
            if not os.getenv("PATH"):
                raise OSError(
                    "There is something wrong with your Linux installation.")
            for pathdir in cast(str, os.getenv("PATH")).split(os.pathsep):
                execpath = os.path.join(pathdir, executable_name)
                if os.path.exists(execpath):
                    default_engine_location = execpath
                    break

        self._application = CuraApplication.getInstance(
        )  #type: CuraApplication
        self._multi_build_plate_model = None  #type: Optional[MultiBuildPlateModel]
        self._machine_error_checker = None  #type: Optional[MachineErrorChecker]

        if not default_engine_location:
            raise EnvironmentError("Could not find CuraEngine")

        Logger.log("i", "Found CuraEngine at: %s", default_engine_location)

        default_engine_location = os.path.abspath(default_engine_location)
        self._application.getPreferences().addPreference(
            "backend/location", default_engine_location)

        # Workaround to disable layer view processing if layer view is not active.
        self._layer_view_active = False  #type: bool
        self._onActiveViewChanged()

        self._stored_layer_data = []  # type: List[Arcus.PythonMessage]
        self._stored_optimized_layer_data = {
        }  # type: Dict[int, List[Arcus.PythonMessage]] # key is build plate number, then arrays are stored until they go to the ProcessSlicesLayersJob

        self._scene = self._application.getController().getScene(
        )  #type: Scene
        self._scene.sceneChanged.connect(self._onSceneChanged)

        # Triggers for auto-slicing. Auto-slicing is triggered as follows:
        #  - auto-slicing is started with a timer
        #  - whenever there is a value change, we start the timer
        #  - sometimes an error check can get scheduled for a value change, in that case, we ONLY want to start the
        #    auto-slicing timer when that error check is finished
        # If there is an error check, stop the auto-slicing timer, and only wait for the error check to be finished
        # to start the auto-slicing timer again.
        #
        self._global_container_stack = None  #type: Optional[ContainerStack]

        # Listeners for receiving messages from the back-end.
        self._message_handlers["cura.proto.Layer"] = self._onLayerMessage
        self._message_handlers[
            "cura.proto.LayerOptimized"] = self._onOptimizedLayerMessage
        self._message_handlers["cura.proto.Progress"] = self._onProgressMessage
        self._message_handlers[
            "cura.proto.GCodeLayer"] = self._onGCodeLayerMessage
        self._message_handlers[
            "cura.proto.GCodePrefix"] = self._onGCodePrefixMessage
        self._message_handlers[
            "cura.proto.PrintTimeMaterialEstimates"] = self._onPrintTimeMaterialEstimates
        self._message_handlers[
            "cura.proto.SlicingFinished"] = self._onSlicingFinishedMessage

        self._start_slice_job = None  #type: Optional[StartSliceJob]
        self._start_slice_job_build_plate = None  #type: Optional[int]
        self._slicing = False  #type: bool # Are we currently slicing?
        self._restart = False  #type: bool # Back-end is currently restarting?
        self._tool_active = False  #type: bool # If a tool is active, some tasks do not have to do anything
        self._always_restart = True  #type: bool # Always restart the engine when starting a new slice. Don't keep the process running. TODO: Fix engine statelessness.
        self._process_layers_job = None  #type: Optional[ProcessSlicedLayersJob] # The currently active job to process layers, or None if it is not processing layers.
        self._build_plates_to_be_sliced = [
        ]  #type: List[int] # what needs slicing?
        self._engine_is_fresh = True  #type: bool # Is the newly started engine used before or not?

        self._backend_log_max_lines = 20000  #type: int # Maximum number of lines to buffer
        self._error_message = None  #type: Optional[Message] # Pop-up message that shows errors.
        self._last_num_objects = defaultdict(
            int
        )  #type: Dict[int, int] # Count number of objects to see if there is something changed
        self._postponed_scene_change_sources = [
        ]  #type: List[SceneNode] # scene change is postponed (by a tool)

        self._slice_start_time = None  #type: Optional[float]
        self._is_disabled = False  #type: bool

        self._application.getPreferences().addPreference(
            "general/auto_slice", False)

        self._use_timer = False  #type: bool
        # When you update a setting and other settings get changed through inheritance, many propertyChanged signals are fired.
        # This timer will group them up, and only slice for the last setting changed signal.
        # TODO: Properly group propertyChanged signals by whether they are triggered by the same user interaction.
        self._change_timer = QTimer()  #type: QTimer
        self._change_timer.setSingleShot(True)
        self._change_timer.setInterval(500)
        self.determineAutoSlicing()
        self._application.getPreferences().preferenceChanged.connect(
            self._onPreferencesChanged)

        self._application.initializationFinished.connect(self.initialize)
Exemplo n.º 16
0
    def SetupActions(self):
        #Buttons and etc
        self.paxRadio.clicked.connect(self.ChangeCam)
        self.ingaasRadio.clicked.connect(self.ChangeCam)
        self.ingaasHGRadio.clicked.connect(self.ChangeCam)
        self.startBut.clicked.connect(self.OnStartButClicked)
        self.stopBut.clicked.connect(self.OnStopButClicked)
        self.saveFrameBut.clicked.connect(self.SaveFrame)
        self.savefullimgBut.clicked.connect(self.SaveFullImg)
        self.exposureSlider.valueChanged.connect(self.OnExpSliderChanged)
        self.gainSlider.valueChanged.connect(self.OnGainSliderChanged)
        self.multiDial.valueChanged.connect(self.UpdateMultiSpin)
        self.multiSpin.valueChanged.connect(self.UpdateMultiDial)
        self.emergBut.clicked.connect(self.StopAllMov)
        self.upBut.clicked.connect(self.MoveUp)
        self.downBut.clicked.connect(self.MoveDown)
        self.leftBut.clicked.connect(self.MoveLeft)
        self.rightBut.clicked.connect(self.MoveRight)
        self.zdownBut.clicked.connect(self.MoveZDown)
        self.zupBut.clicked.connect(self.MoveZUp)
        self.xPosSpin.valueChanged.connect(self.OnXPosChanged)
        self.yPosSpin.valueChanged.connect(self.OnYPosChanged)
        self.zPosSpin.valueChanged.connect(self.OnZPosChanged)
        self.zSlider.sliderMoved.connect(self.OnZSliderChanged)
        self.zSlider.sliderPressed.connect(self.OnZSliderClick)
        self.zSlider.sliderReleased.connect(self.OnZSliderRelease)
        #self.saveposBut.clicked.connect(self.SavePosition)
        self.savedposCombo.lineEdit().returnPressed.connect(self.SavePosition)
        self.gotoposBut.clicked.connect(self.GoToPos)
        self.delposBut.clicked.connect(self.DelPos)
        self.npixelsSpin.valueChanged.connect(self.CalcMicrons)
        self.microcalSpin.valueChanged.connect(self.CalcMicrons)
        self.lensmagSpin.valueChanged.connect(self.CalcCalibrationScale)
        self.zoomSpin.valueChanged.connect(self.CalcCalibrationScale)
        self.drawcolorBut.clicked.connect(self.SetDrawColor)
        self.drawlinemeasBut.clicked.connect(self.DrawLineMeasurement)
        self.clearmeasBut.clicked.connect(self.ClearLineMeasurement)
        self.meassaveBut.clicked.connect(self.SaveMeas)
        self.measloadBut.clicked.connect(self.LoadMeas)
        self.placemarkerBut.clicked.connect(self.PlaceMarker)
        self.clearmarkerBut.clicked.connect(self.ClearMarker)
        self.markersaveBut.clicked.connect(self.SaveMarker)
        self.markerloadBut.clicked.connect(self.LoadMarker)
        self.fixedscaleCheck.stateChanged.connect(self.DrawFixedScale)

        #Video
        self.capTimer = QTimer()
        self.capTimer.timeout.connect(self.CaptureVideo)
        self.capTimer.setInterval(10)

        #Motors
        self.getposTimer = QTimer()
        self.getposTimer.timeout.connect(self.UpdateMotorsPos)
        self.getposTimer.setInterval(100)
        self.getcontposTimer = QTimer()
        self.getcontposTimer.timeout.connect(self.UpdateMotorsContPos)
        self.getcontposTimer.setInterval(100)
        self.movXTimer = QTimer()
        self.movXTimer.timeout.connect(self.MoveXCont)
        self.movXTimer.setInterval(500)
        self.movYTimer = QTimer()
        self.movYTimer.timeout.connect(self.MoveYCont)
        self.movYTimer.setInterval(500)
        self.movZTimer = QTimer()
        self.movZTimer.timeout.connect(self.MoveZCont)
        self.movZTimer.setInterval(500)

        #Menu bar
        self.action_Reserved.triggered.connect(self.ShowReserved)
        self.actionGuide.triggered.connect(self.ShowGuide)
        self.actionAbout_Qt.triggered.connect(self.AboutQt)
        self.actionAbout_Python.triggered.connect(self.AboutPython)
        self.actionAbout.triggered.connect(self.About)
        self.actionExit.triggered.connect(self.Exit)
Exemplo n.º 17
0
	def __init__(self, parent=None):
		QMainWindow.__init__(self, parent)
		self.resize(950, 700)
		screenRect = QDesktopWidget().screenGeometry()
		if globalSettings.windowGeometry:
			self.restoreGeometry(globalSettings.windowGeometry)
		else:
			self.move((screenRect.width()-self.width())/2, (screenRect.height()-self.height())/2)
			if not screenRect.contains(self.geometry()):
				self.showMaximized()
		if sys.platform.startswith('darwin'):
			# https://github.com/retext-project/retext/issues/198
			searchPaths = QIcon.themeSearchPaths()
			searchPaths.append('/opt/local/share/icons')
			searchPaths.append('/usr/local/share/icons')
			QIcon.setThemeSearchPaths(searchPaths)
		if globalSettings.iconTheme:
			QIcon.setThemeName(globalSettings.iconTheme)
		if QIcon.themeName() in ('hicolor', ''):
			if not QFile.exists(getBundledIcon('document-new')):
				QIcon.setThemeName(get_icon_theme())
		if QFile.exists(getBundledIcon('retext')):
			self.setWindowIcon(QIcon(getBundledIcon('retext')))
		elif QFile.exists('/usr/share/pixmaps/retext.png'):
			self.setWindowIcon(QIcon('/usr/share/pixmaps/retext.png'))
		else:
			self.setWindowIcon(QIcon.fromTheme('retext',
				QIcon.fromTheme('accessories-text-editor')))
		self.tabWidget = QTabWidget(self)
		self.initTabWidget()
		self.setCentralWidget(self.tabWidget)
		self.tabWidget.currentChanged.connect(self.changeIndex)
		self.tabWidget.tabCloseRequested.connect(self.closeTab)
		toolBar = QToolBar(self.tr('File toolbar'), self)
		self.addToolBar(Qt.TopToolBarArea, toolBar)
		self.editBar = QToolBar(self.tr('Edit toolbar'), self)
		self.addToolBar(Qt.TopToolBarArea, self.editBar)
		self.searchBar = QToolBar(self.tr('Search toolbar'), self)
		self.addToolBar(Qt.BottomToolBarArea, self.searchBar)
		toolBar.setVisible(not globalSettings.hideToolBar)
		self.editBar.setVisible(not globalSettings.hideToolBar)
		self.actionNew = self.act(self.tr('New'), 'document-new',
			self.createNew, shct=QKeySequence.New)
		self.actionNew.setPriority(QAction.LowPriority)
		self.actionOpen = self.act(self.tr('Open'), 'document-open',
			self.openFile, shct=QKeySequence.Open)
		self.actionOpen.setPriority(QAction.LowPriority)
		self.actionSetEncoding = self.act(self.tr('Set encoding'),
			trig=self.showEncodingDialog)
		self.actionSetEncoding.setEnabled(False)
		self.actionReload = self.act(self.tr('Reload'), 'view-refresh',
			lambda: self.currentTab.readTextFromFile())
		self.actionReload.setEnabled(False)
		self.actionSave = self.act(self.tr('Save'), 'document-save',
			self.saveFile, shct=QKeySequence.Save)
		self.actionSave.setEnabled(False)
		self.actionSave.setPriority(QAction.LowPriority)
		self.actionSaveAs = self.act(self.tr('Save as'), 'document-save-as',
			self.saveFileAs, shct=QKeySequence.SaveAs)
		self.actionNextTab = self.act(self.tr('Next tab'), 'go-next',
			lambda: self.switchTab(1), shct=Qt.CTRL+Qt.Key_PageDown)
		self.actionPrevTab = self.act(self.tr('Previous tab'), 'go-previous',
			lambda: self.switchTab(-1), shct=Qt.CTRL+Qt.Key_PageUp)
		self.actionCloseCurrentTab = self.act(self.tr('Close tab'), 'window-close',
			lambda: self.closeTab(self.ind), shct=QKeySequence.Close)
		self.actionPrint = self.act(self.tr('Print'), 'document-print',
			self.printFile, shct=QKeySequence.Print)
		self.actionPrint.setPriority(QAction.LowPriority)
		self.actionPrintPreview = self.act(self.tr('Print preview'), 'document-print-preview',
			self.printPreview)
		self.actionViewHtml = self.act(self.tr('View HTML code'), 'text-html', self.viewHtml)
		self.actionChangeEditorFont = self.act(self.tr('Change editor font'),
			trig=self.changeEditorFont)
		self.actionChangePreviewFont = self.act(self.tr('Change preview font'),
			trig=self.changePreviewFont)
		self.actionSearch = self.act(self.tr('Find text'), 'edit-find',
			self.search, shct=QKeySequence.Find)
		self.actionGoToLine = self.act(self.tr('Go to line'),
			trig=self.goToLine, shct=Qt.CTRL+Qt.Key_G)
		self.searchBar.visibilityChanged.connect(self.searchBarVisibilityChanged)
		self.actionPreview = self.act(self.tr('Preview'), shct=Qt.CTRL+Qt.Key_E,
			trigbool=self.preview)
		if QIcon.hasThemeIcon('document-preview'):
			self.actionPreview.setIcon(QIcon.fromTheme('document-preview'))
		elif QIcon.hasThemeIcon('preview-file'):
			self.actionPreview.setIcon(QIcon.fromTheme('preview-file'))
		elif QIcon.hasThemeIcon('x-office-document'):
			self.actionPreview.setIcon(QIcon.fromTheme('x-office-document'))
		else:
			self.actionPreview.setIcon(QIcon(getBundledIcon('document-preview')))
		self.actionLivePreview = self.act(self.tr('Live preview'), shct=Qt.CTRL+Qt.Key_L,
		trigbool=self.enableLivePreview)
		menuPreview = QMenu()
		menuPreview.addAction(self.actionLivePreview)
		self.actionPreview.setMenu(menuPreview)
		self.actionTableMode = self.act(self.tr('Table editing mode'),
			shct=Qt.CTRL+Qt.Key_T,
			trigbool=lambda x: self.currentTab.editBox.enableTableMode(x))
		if ReTextFakeVimHandler:
			self.actionFakeVimMode = self.act(self.tr('FakeVim mode'),
				shct=Qt.CTRL+Qt.ALT+Qt.Key_V, trigbool=self.enableFakeVimMode)
			if globalSettings.useFakeVim:
				self.actionFakeVimMode.setChecked(True)
				self.enableFakeVimMode(True)
		self.actionFullScreen = self.act(self.tr('Fullscreen mode'), 'view-fullscreen',
			shct=Qt.Key_F11, trigbool=self.enableFullScreen)
		self.actionFullScreen.setChecked(self.isFullScreen())
		self.actionFullScreen.setPriority(QAction.LowPriority)
		self.actionConfig = self.act(self.tr('Preferences'), icon='preferences-system',
			trig=self.openConfigDialog)
		self.actionConfig.setMenuRole(QAction.PreferencesRole)
		self.actionSaveHtml = self.act('HTML', 'text-html', self.saveFileHtml)
		self.actionPdf = self.act('PDF', 'application-pdf', self.savePdf)
		self.actionOdf = self.act('ODT', 'x-office-document', self.saveOdf)
		self.getExportExtensionsList()
		self.actionQuit = self.act(self.tr('Quit'), 'application-exit', shct=QKeySequence.Quit)
		self.actionQuit.setMenuRole(QAction.QuitRole)
		self.actionQuit.triggered.connect(self.close)
		self.actionUndo = self.act(self.tr('Undo'), 'edit-undo',
			lambda: self.currentTab.editBox.undo(), shct=QKeySequence.Undo)
		self.actionRedo = self.act(self.tr('Redo'), 'edit-redo',
			lambda: self.currentTab.editBox.redo(), shct=QKeySequence.Redo)
		self.actionCopy = self.act(self.tr('Copy'), 'edit-copy',
			lambda: self.currentTab.editBox.copy(), shct=QKeySequence.Copy)
		self.actionCut = self.act(self.tr('Cut'), 'edit-cut',
			lambda: self.currentTab.editBox.cut(), shct=QKeySequence.Cut)
		self.actionPaste = self.act(self.tr('Paste'), 'edit-paste',
			lambda: self.currentTab.editBox.paste(), shct=QKeySequence.Paste)
		self.actionMoveUp = self.act(self.tr('Move line up'), 'go-up',
			lambda: self.currentTab.editBox.moveLineUp(), shct=Qt.ALT+Qt.Key_Up)
		self.actionMoveDown = self.act(self.tr('Move line down'), 'go-down',
			lambda: self.currentTab.editBox.moveLineDown(), shct=Qt.ALT+Qt.Key_Down)
		self.actionUndo.setEnabled(False)
		self.actionRedo.setEnabled(False)
		self.actionCopy.setEnabled(False)
		self.actionCut.setEnabled(False)
		qApp = QApplication.instance()
		qApp.clipboard().dataChanged.connect(self.clipboardDataChanged)
		self.clipboardDataChanged()
		if enchant is not None:
			self.actionEnableSC = self.act(self.tr('Enable'), trigbool=self.enableSpellCheck)
			self.actionSetLocale = self.act(self.tr('Set locale'), trig=self.changeLocale)
		self.actionWebKit = self.act(self.tr('Use WebKit renderer'), trigbool=self.enableWebKit)
		if ReTextWebKitPreview is None:
			globalSettings.useWebKit = False
			self.actionWebKit.setEnabled(False)
		self.actionWebKit.setChecked(globalSettings.useWebKit)
		self.actionWebEngine = self.act(self.tr('Use WebEngine (Chromium) renderer'),
			trigbool=self.enableWebEngine)
		if ReTextWebEnginePreview is None:
			globalSettings.useWebEngine = False
		self.actionWebEngine.setChecked(globalSettings.useWebEngine)
		self.actionShow = self.act(self.tr('Show directory'), 'system-file-manager', self.showInDir)
		self.actionFind = self.act(self.tr('Next'), 'go-next', self.find,
			shct=QKeySequence.FindNext)
		self.actionFindPrev = self.act(self.tr('Previous'), 'go-previous',
			lambda: self.find(back=True), shct=QKeySequence.FindPrevious)
		self.actionReplace = self.act(self.tr('Replace'), 'edit-find-replace',
			lambda: self.find(replace=True))
		self.actionReplaceAll = self.act(self.tr('Replace all'), trig=self.replaceAll)
		menuReplace = QMenu()
		menuReplace.addAction(self.actionReplaceAll)
		self.actionReplace.setMenu(menuReplace)
		self.actionCloseSearch = self.act(self.tr('Close'), 'window-close',
			lambda: self.searchBar.setVisible(False),
			shct=QKeySequence.Cancel)
		self.actionCloseSearch.setPriority(QAction.LowPriority)
		self.actionHelp = self.act(self.tr('Get help online'), 'help-contents', self.openHelp)
		self.aboutWindowTitle = self.tr('About ReText')
		self.actionAbout = self.act(self.aboutWindowTitle, 'help-about', self.aboutDialog)
		self.actionAbout.setMenuRole(QAction.AboutRole)
		self.actionAboutQt = self.act(self.tr('About Qt'))
		self.actionAboutQt.setMenuRole(QAction.AboutQtRole)
		self.actionAboutQt.triggered.connect(qApp.aboutQt)
		availableMarkups = markups.get_available_markups()
		if not availableMarkups:
			print('Warning: no markups are available!')
		if len(availableMarkups) > 1:
			self.chooseGroup = QActionGroup(self)
			markupActions = []
			for markup in availableMarkups:
				markupAction = self.act(markup.name, trigbool=self.markupFunction(markup))
				if markup.name == globalSettings.defaultMarkup:
					markupAction.setChecked(True)
				self.chooseGroup.addAction(markupAction)
				markupActions.append(markupAction)
		self.actionBold = self.act(self.tr('Bold'), shct=QKeySequence.Bold,
			trig=lambda: self.insertFormatting('bold'))
		self.actionItalic = self.act(self.tr('Italic'), shct=QKeySequence.Italic,
			trig=lambda: self.insertFormatting('italic'))
		self.actionUnderline = self.act(self.tr('Underline'), shct=QKeySequence.Underline,
			trig=lambda: self.insertFormatting('underline'))
		self.usefulTags = ('header', 'italic', 'bold', 'underline', 'numbering',
			'bullets', 'image', 'link', 'inline code', 'code block', 'blockquote')
		self.usefulChars = ('deg', 'divide', 'dollar', 'hellip', 'laquo', 'larr',
			'lsquo', 'mdash', 'middot', 'minus', 'nbsp', 'ndash', 'raquo',
			'rarr', 'rsquo', 'times')
		self.formattingBox = QComboBox(self.editBar)
		self.formattingBox.addItem(self.tr('Formatting'))
		self.formattingBox.addItems(self.usefulTags)
		self.formattingBox.activated[str].connect(self.insertFormatting)
		self.symbolBox = QComboBox(self.editBar)
		self.symbolBox.addItem(self.tr('Symbols'))
		self.symbolBox.addItems(self.usefulChars)
		self.symbolBox.activated.connect(self.insertSymbol)
		self.updateStyleSheet()
		menubar = self.menuBar()
		menuFile = menubar.addMenu(self.tr('File'))
		menuEdit = menubar.addMenu(self.tr('Edit'))
		menuHelp = menubar.addMenu(self.tr('Help'))
		menuFile.addAction(self.actionNew)
		menuFile.addAction(self.actionOpen)
		self.menuRecentFiles = menuFile.addMenu(self.tr('Open recent'))
		self.menuRecentFiles.aboutToShow.connect(self.updateRecentFiles)
		menuFile.addAction(self.actionShow)
		menuFile.addAction(self.actionSetEncoding)
		menuFile.addAction(self.actionReload)
		menuFile.addSeparator()
		menuFile.addAction(self.actionSave)
		menuFile.addAction(self.actionSaveAs)
		menuFile.addSeparator()
		menuFile.addAction(self.actionNextTab)
		menuFile.addAction(self.actionPrevTab)
		menuFile.addAction(self.actionCloseCurrentTab)
		menuFile.addSeparator()
		menuExport = menuFile.addMenu(self.tr('Export'))
		menuExport.addAction(self.actionSaveHtml)
		menuExport.addAction(self.actionOdf)
		menuExport.addAction(self.actionPdf)
		if self.extensionActions:
			menuExport.addSeparator()
			for action, mimetype in self.extensionActions:
				menuExport.addAction(action)
			menuExport.aboutToShow.connect(self.updateExtensionsVisibility)
		menuFile.addAction(self.actionPrint)
		menuFile.addAction(self.actionPrintPreview)
		menuFile.addSeparator()
		menuFile.addAction(self.actionQuit)
		menuEdit.addAction(self.actionUndo)
		menuEdit.addAction(self.actionRedo)
		menuEdit.addSeparator()
		menuEdit.addAction(self.actionCut)
		menuEdit.addAction(self.actionCopy)
		menuEdit.addAction(self.actionPaste)
		menuEdit.addSeparator()
		menuEdit.addAction(self.actionMoveUp)
		menuEdit.addAction(self.actionMoveDown)
		menuEdit.addSeparator()
		if enchant is not None:
			menuSC = menuEdit.addMenu(self.tr('Spell check'))
			menuSC.addAction(self.actionEnableSC)
			menuSC.addAction(self.actionSetLocale)
		menuEdit.addAction(self.actionSearch)
		menuEdit.addAction(self.actionGoToLine)
		menuEdit.addAction(self.actionChangeEditorFont)
		menuEdit.addAction(self.actionChangePreviewFont)
		menuEdit.addSeparator()
		if len(availableMarkups) > 1:
			self.menuMode = menuEdit.addMenu(self.tr('Default markup'))
			for markupAction in markupActions:
				self.menuMode.addAction(markupAction)
		menuFormat = menuEdit.addMenu(self.tr('Formatting'))
		menuFormat.addAction(self.actionBold)
		menuFormat.addAction(self.actionItalic)
		menuFormat.addAction(self.actionUnderline)
		if ReTextWebKitPreview is not None or ReTextWebEnginePreview is None:
			menuEdit.addAction(self.actionWebKit)
		else:
			menuEdit.addAction(self.actionWebEngine)
		menuEdit.addSeparator()
		menuEdit.addAction(self.actionViewHtml)
		menuEdit.addAction(self.actionPreview)
		menuEdit.addAction(self.actionTableMode)
		if ReTextFakeVimHandler:
			menuEdit.addAction(self.actionFakeVimMode)
		menuEdit.addSeparator()
		menuEdit.addAction(self.actionFullScreen)
		menuEdit.addAction(self.actionConfig)
		menuHelp.addAction(self.actionHelp)
		menuHelp.addSeparator()
		menuHelp.addAction(self.actionAbout)
		menuHelp.addAction(self.actionAboutQt)
		toolBar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
		toolBar.addAction(self.actionNew)
		toolBar.addSeparator()
		toolBar.addAction(self.actionOpen)
		toolBar.addAction(self.actionSave)
		toolBar.addAction(self.actionPrint)
		toolBar.addSeparator()
		toolBar.addAction(self.actionPreview)
		toolBar.addAction(self.actionFullScreen)
		self.editBar.addAction(self.actionUndo)
		self.editBar.addAction(self.actionRedo)
		self.editBar.addSeparator()
		self.editBar.addAction(self.actionCut)
		self.editBar.addAction(self.actionCopy)
		self.editBar.addAction(self.actionPaste)
		self.editBar.addSeparator()
		self.editBar.addWidget(self.formattingBox)
		self.editBar.addWidget(self.symbolBox)
		self.searchEdit = QLineEdit(self.searchBar)
		self.searchEdit.setPlaceholderText(self.tr('Search'))
		self.searchEdit.returnPressed.connect(self.find)
		self.replaceEdit = QLineEdit(self.searchBar)
		self.replaceEdit.setPlaceholderText(self.tr('Replace with'))
		self.replaceEdit.returnPressed.connect(self.find)
		self.csBox = QCheckBox(self.tr('Case sensitively'), self.searchBar)
		self.searchBar.addWidget(self.searchEdit)
		self.searchBar.addWidget(self.replaceEdit)
		self.searchBar.addSeparator()
		self.searchBar.addWidget(self.csBox)
		self.searchBar.addAction(self.actionFindPrev)
		self.searchBar.addAction(self.actionFind)
		self.searchBar.addAction(self.actionReplace)
		self.searchBar.addAction(self.actionCloseSearch)
		self.searchBar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
		self.searchBar.setVisible(False)
		self.autoSaveEnabled = globalSettings.autoSave
		if self.autoSaveEnabled:
			timer = QTimer(self)
			timer.start(60000)
			timer.timeout.connect(self.saveAll)
		self.ind = None
		if enchant is not None:
			self.sl = globalSettings.spellCheckLocale
			try:
				enchant.Dict(self.sl or None)
			except enchant.errors.Error as e:
				warnings.warn(str(e), RuntimeWarning)
				globalSettings.spellCheck = False
			if globalSettings.spellCheck:
				self.actionEnableSC.setChecked(True)
		self.fileSystemWatcher = QFileSystemWatcher()
		self.fileSystemWatcher.fileChanged.connect(self.fileChanged)
Exemplo n.º 18
0
def main():
    t = time.time()
    if GENERATE_UI and not hasattr(sys, 'frozen'):
        try:
            autohacker_dir = os.path.abspath(
                os.path.join(os.path.dirname(sys.argv[0]), "..", ".."))
            sys.path.append(autohacker_dir)
            sys.path.append(os.path.join(autohacker_dir, "src"))

            import generate_ui

            generate_ui.gen()  # Im Release rausnehmen

            print("Time for generating UI: %.2f seconds" % (time.time() - t),
                  file=sys.stderr)
        except (ImportError, FileNotFoundError):
            print(
                "Will not regenerate UI, because script cant be found. This is okay in "
                "release.",
                file=sys.stderr)

    urh_exe = sys.executable if hasattr(sys, 'frozen') else sys.argv[0]
    urh_exe = os.readlink(urh_exe) if os.path.islink(urh_exe) else urh_exe

    urh_dir = os.path.join(os.path.dirname(urh_exe), "..", "..")
    prefix = os.path.abspath(os.path.normpath(urh_dir))

    src_dir = os.path.join(prefix, "src")
    if os.path.exists(src_dir) and not prefix.startswith("/usr") \
            and not re.match(r"(?i)c:\\program", prefix):
        # Started locally, not installed
        print("Using modules from {0}".format(src_dir), file=sys.stderr)
        sys.path.insert(0, src_dir)

    try:
        import urh.cythonext.signalFunctions
        import urh.cythonext.path_creator
        import urh.cythonext.util
    except ImportError:
        print("Could not find C++ extensions, trying to build them.",
              file=sys.stderr)
        old_dir = os.curdir
        os.chdir(os.path.join(src_dir, "urh", "cythonext"))

        from urh.cythonext import build
        build.main()

        os.chdir(old_dir)

    from urh.controller.MainController import MainController
    from urh import constants

    if constants.SETTINGS.value("use_fallback_theme", False, bool):
        os.environ['QT_QPA_PLATFORMTHEME'] = 'fusion'

    app = QApplication(sys.argv)

    # noinspection PyUnresolvedReferences
    import urh.ui.xtra_icons_rc  # Use oxy theme always
    QIcon.setThemeName("oxy")

    constants.SETTINGS.setValue("default_theme",
                                QApplication.style().objectName())

    if constants.SETTINGS.value("use_fallback_theme", False, bool):
        QApplication.setStyle(QStyleFactory.create("Fusion"))

    mainwindow = MainController()
    mainwindow.showMaximized()
    #mainwindow.setFixedSize(1920, 1080 - 30)  # Youtube

    # Systemfarben als Zeichenfarbe setzen
    widget = QWidget()
    bgcolor = widget.palette().color(QPalette.Background)
    fgcolor = widget.palette().color(QPalette.Foreground)
    selection_color = widget.palette().color(QPalette.Highlight)
    constants.BGCOLOR = bgcolor
    constants.LINECOLOR = fgcolor
    constants.SELECTION_COLOR = selection_color

    if "autoclose" in sys.argv[1:]:
        # Autoclose after 1 second, this is useful for automated testing
        timer = QTimer()
        timer.timeout.connect(app.quit)
        timer.start(1000)

    os._exit(app.exec_(
    ))  # sys.exit() is not enough on Windows and will result in crash on exit
Exemplo n.º 19
0
    def UI_DESIGN(self):
        #######################################start button#####################################
        start = QPushButton('Start', self)
        start.setGeometry(200, 240, 121, 51)
        font = QFont()
        font.setFamily("Arial")
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        start.setFont(font)
        start.setObjectName("start")
        start.clicked.connect(self.start)
        #######################################stop button######################################
        stop = QPushButton('Stop', self)
        stop.setGeometry(340, 240, 111, 51)
        font = QFont()
        font.setFamily("Arial")
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        stop.setFont(font)
        stop.setObjectName("stop")
        stop.clicked.connect(self.stop)
        ######################################computer score label#######################################
        self.computer_score = QLabel('computer score : ', self)
        self.computer_score.setGeometry(100, 30, 181, 31)
        font = QFont()
        font.setFamily("Arial")
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.computer_score.setFont(font)
        self.computer_score.setObjectName("computer_score")
        ######################################player score###################################################
        self.player_score = QLabel('player score : ', self)
        self.player_score.setGeometry(390, 30, 181, 31)
        font = QFont()
        font.setFamily("Arial")
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.player_score.setFont(font)
        self.player_score.setObjectName("player_score")
        #######################################image computer#############################################
        self.imageComputer = QLabel(self)
        self.imageComputer.setGeometry(130, 90, 101, 101)
        self.imageComputer.setText("")
        self.imageComputer.setPixmap(QPixmap("images/rock_com.png"))
        self.imageComputer.setScaledContents(True)
        self.imageComputer.setObjectName("imagecomputer")
        #######################################image game###################################################
        self.imagegame = QLabel(self)
        self.imagegame.setGeometry(270, 90, 111, 101)
        self.imagegame.setText("")
        self.imagegame.setPixmap(QPixmap("images/game.png"))
        self.imagegame.setScaledContents(True)
        self.imagegame.setObjectName("imagegame")
        #########################################image player################################################
        self.imagePlayer = QLabel(self)
        self.imagePlayer.setGeometry(420, 90, 101, 101)
        self.imagePlayer.setText("")
        self.imagePlayer.setPixmap(QPixmap("images/rock_player.png"))
        self.imagePlayer.setScaledContents(True)
        self.imagePlayer.setObjectName("label_3")
        ########################################Timer###############################################
        self.timer = QTimer(self)
        self.timer.setInterval(80)
        self.timer.timeout.connect(self.playGame)

        self.show()
Exemplo n.º 20
0
	def initUI(self):
		
		################### MENU BARS START ##################
		
		MyBar = QMenuBar(self)
		fileMenu = MyBar.addMenu("File")
		fileSavePlt = fileMenu.addAction("Save plots")
		fileSavePlt.triggered.connect(self.save_plots)
		fileSavePlt.setShortcut('Ctrl+P')
		fileSaveSet = fileMenu.addAction("Save settings")        
		fileSaveSet.triggered.connect(self.save_) # triggers closeEvent()
		fileSaveSet.setShortcut('Ctrl+S')
		fileClose = fileMenu.addAction("Close")        
		fileClose.triggered.connect(self.close) # triggers closeEvent()
		fileClose.setShortcut('Ctrl+X')
		
		instMenu = MyBar.addMenu("Instruments")
		self.conMode = instMenu.addAction("Load instruments")
		self.conMode.triggered.connect(self.instrumentsDialog)
		
		################### MENU BARS END ##################
		
		#####################################################
		lbl1 = QLabel("MONOCHROMATOR CM110 settings:", self)
		lbl1.setStyleSheet("color: blue")
		intervals_lbl = QLabel("Number of intervals", self)
		self.combo4 = QComboBox(self)
		mylist4=["1","2"]
		self.combo4.addItems(mylist4)
		self.combo4.setCurrentIndex(mylist4.index(str(self.numofintervals)))
		start_lbl = QLabel("Start[nm]",self)
		stop_lbl = QLabel("Stop[nm]",self)
		step_lbl = QLabel("Step[nm]",self)
		dwelltime = QLabel("Dwell[s]",self)
		
		self.startEdit = [QLineEdit("",self) for tal in range(2)]
		self.stopEdit = [QLineEdit("",self) for tal in range(2)]
		self.stepEdit = [QLineEdit("",self) for tal in range(2)]
		self.dwelltimeEdit = [QLineEdit("",self) for tal in range(2)]
		# disable those fields that will be ignored anyway
		for tal in range(2):
			if tal<self.numofintervals:
				self.startEdit[tal].setText(str(self.start_[tal]))
				self.stopEdit[tal].setText(str(self.stop[tal]))
				self.stepEdit[tal].setText(str(self.step[tal]))
				self.dwelltimeEdit[tal].setText(str(self.dwell_time[tal]))
			else:
				self.startEdit[tal].setEnabled(False)
				self.stopEdit[tal].setEnabled(False)
				self.stepEdit[tal].setEnabled(False)
				self.dwelltimeEdit[tal].setEnabled(False)
		
		lbl3 = QLabel("NEWPORT stepper SMC100:", self)
		lbl3.setStyleSheet("color: blue")
		startst_lbl = QLabel("Start",self)
		stopst_lbl = QLabel("Stop",self)
		stepst_lbl = QLabel("Step",self)
		lcdst_lbl = QLabel("Current pos",self)
		self.startst_Edit = QLineEdit(str(self.startst),self) 
		self.stopst_Edit = QLineEdit(str(self.stopst),self) 
		self.stepst_Edit = QLineEdit(str(self.stepst),self)
		self.lcdst = QLCDNumber(self)
		self.lcdst.setStyleSheet("color: blue")
		#self.lcdst.setFixedHeight(40)
		self.lcdst.setSegmentStyle(QLCDNumber.Flat)
		self.lcdst.setNumDigits(5)
		self.lcdst.display("-----")
		
		lbl2 = QLabel("ARDUINO Mega2560 settings:", self)
		lbl2.setStyleSheet("color: blue")
		dwelltime_lbl = QLabel("Dwell time [ms]",self)
		self.dwelltimeEdit_ard = QLineEdit(str(self.dwell_time_ard),self)
		
		avgpts_lbl = QLabel("Averaging points", self)
		self.combo1 = QComboBox(self)
		mylist=["1","5","10","50","100","200"]
		self.combo1.addItems(mylist)
		self.combo1.setCurrentIndex(mylist.index(str(self.avg_pts)))
		
		lbl4 = QLabel("STORAGE filename and location settings:", self)
		lbl4.setStyleSheet("color: blue")
		filename = QLabel("folder/file",self)
		self.filenameEdit = QLineEdit(self.filename_str,self)
		
		lbl6 = QLabel("PLOT options:", self)
		lbl6.setStyleSheet("color: blue")
		mylist2=["200","400","800","1600","3200","6400"]
		
		schroll_lbl = QLabel("Schroll time after",self)
		self.combo2 = QComboBox(self)
		self.combo2.addItems(mylist2)
		self.combo2.setCurrentIndex(mylist2.index(str(self.schroll_time)))
		
		schroll2_lbl = QLabel("Schroll wavelength after",self)
		self.combo3 = QComboBox(self)
		self.combo3.addItems(mylist2)
		self.combo3.setCurrentIndex(mylist2.index(str(self.schroll_wl)))
		
		##############################################
		
		lbl5 = QLabel("RECORD data and save images:", self)
		lbl5.setStyleSheet("color: blue")
		
		#save_str = QLabel("Store settings", self)
		#self.saveButton = QPushButton("Save",self)
		#self.saveButton.setEnabled(True)
		
		run_str = QLabel("Record lock-in data", self)
		self.runButton = QPushButton("Load instruments",self)
		
		#saveplots_str = QLabel("Save plots as png", self)
		#self.saveplotsButton = QPushButton("Save plots",self)
		#self.saveplotsButton.setEnabled(True)
		'''
		elapsedtime_str = QLabel('Show voltage vs. time', self)
		self.elapsedtimeButton = QPushButton("Plot 2",self)
		self.elapsedtimeButton.setEnabled(False)
		'''
		cancel_str = QLabel("Stop current run", self)
		self.stopButton = QPushButton("STOP",self)
		self.stopButton.setEnabled(False)
		
		##############################################
		
		# status info which button has been pressed
		#self.status_str = QLabel("Edit settings and press SAVE!", self)
		#self.status_str.setStyleSheet("color: green")
		
		##############################################
		
		# status info which button has been pressed
		self.elapsedtime_str = QLabel("TIME trace for storing plots and data:", self)
		self.elapsedtime_str.setStyleSheet("color: blue")
		
		##############################################
		
		self.lcd = QLCDNumber(self)
		self.lcd.setStyleSheet("color: red")
		self.lcd.setFixedHeight(60)
		self.lcd.setSegmentStyle(QLCDNumber.Flat)
		self.lcd.setNumDigits(11)
		self.lcd.display(self.timestr)
			
		##############################################
		# Add all widgets		
		g1_0 = QGridLayout()
		g1_0.addWidget(MyBar,0,0)
		g1_0.addWidget(lbl1,1,0)
		g1_1 = QGridLayout()
		#g1_1.addWidget(cm110port,0,0)
		#g1_1.addWidget(self.cm110portEdit,0,1)
		
		g1_3 = QGridLayout()
		g1_3.addWidget(intervals_lbl,0,0)
		g1_3.addWidget(self.combo4,0,1)
		g1_2 = QGridLayout()
		g1_2.addWidget(start_lbl,0,0)
		g1_2.addWidget(stop_lbl,0,1)
		g1_2.addWidget(step_lbl,0,2)
		g1_2.addWidget(dwelltime,0,3)
		for tal in range(2):
			g1_2.addWidget(self.startEdit[tal],1+tal,0)
			g1_2.addWidget(self.stopEdit[tal],1+tal,1)
			g1_2.addWidget(self.stepEdit[tal],1+tal,2)
			g1_2.addWidget(self.dwelltimeEdit[tal],1+tal,3)
		v1 = QVBoxLayout()
		v1.addLayout(g1_0)
		v1.addLayout(g1_1)
		v1.addLayout(g1_3)
		v1.addLayout(g1_2)
		
		g9_0 = QGridLayout()
		g9_0.addWidget(lbl3,0,0)
		g9_1 = QGridLayout()
		g9_1.addWidget(startst_lbl,0,0)
		g9_1.addWidget(stopst_lbl,0,1)
		g9_1.addWidget(stepst_lbl,0,2)
		g9_1.addWidget(lcdst_lbl,0,3)
		g9_1.addWidget(self.startst_Edit,1,0)
		g9_1.addWidget(self.stopst_Edit,1,1)
		g9_1.addWidget(self.stepst_Edit,1,2)
		g9_1.addWidget(self.lcdst,1,3)
		v9 = QVBoxLayout()
		v9.addLayout(g9_0)
		v9.addLayout(g9_1)
		
		g2_0 = QGridLayout()
		g2_0.addWidget(lbl2,0,0)
		g2_1 = QGridLayout()
		#g2_1.addWidget(ardport,0,0)
		g2_1.addWidget(dwelltime_lbl,0,0)
		g2_1.addWidget(avgpts_lbl,1,0)
		#g2_1.addWidget(self.ardportEdit,0,1)
		g2_1.addWidget(self.dwelltimeEdit_ard,0,1)
		g2_1.addWidget(self.combo1,1,1)
		v2 = QVBoxLayout()
		v2.addLayout(g2_0)
		v2.addLayout(g2_1)
		
		g4_0 = QGridLayout()
		g4_0.addWidget(lbl4,0,0)
		g4_1 = QGridLayout()
		g4_1.addWidget(filename,0,0)
		g4_1.addWidget(self.filenameEdit,0,1)
		v4 = QVBoxLayout()
		v4.addLayout(g4_0)
		v4.addLayout(g4_1)
				
		g7_0 = QGridLayout()
		g7_0.addWidget(lbl6,0,0)
		g7_1 = QGridLayout()
		g7_1.addWidget(schroll2_lbl,0,0)
		g7_1.addWidget(self.combo3,0,1)
		g7_1.addWidget(schroll_lbl,1,0)
		g7_1.addWidget(self.combo2,1,1)
		v7 = QVBoxLayout()
		v7.addLayout(g7_0)
		v7.addLayout(g7_1)
		
		g5_0 = QGridLayout()
		g5_0.addWidget(lbl5,0,0)
		g5_1 = QGridLayout()
		#g5_1.addWidget(save_str,0,0)
		g5_1.addWidget(run_str,0,0)
		#g5_1.addWidget(saveplots_str,2,0)
		g5_1.addWidget(cancel_str,1,0)
		#g5_1.addWidget(self.saveButton,0,1)
		g5_1.addWidget(self.runButton,0,1)
		#g5_1.addWidget(self.saveplotsButton,2,1)
		g5_1.addWidget(self.stopButton,1,1)
		v5 = QVBoxLayout()
		v5.addLayout(g5_0)
		v5.addLayout(g5_1)
		
		g6_0 = QGridLayout()
		g6_0.addWidget(self.elapsedtime_str,0,0)
		g6_0.addWidget(self.lcd,1,0)
		v6 = QVBoxLayout()
		v6.addLayout(g6_0)
		
		# add all groups from v1 to v6 in one vertical group v7
		v8 = QVBoxLayout()
		v8.addLayout(v1)
		v8.addLayout(v9)
		v8.addLayout(v2)
		v8.addLayout(v4)
		v8.addLayout(v7)
		v8.addLayout(v5)
		v8.addLayout(v6)
	
		# set graph  and toolbar to a new vertical group vcan
		vcan = QVBoxLayout()
		self.pw1 = pg.PlotWidget(name="Plot1")  ## giving the plots names allows us to link their axes together
		vcan.addWidget(self.pw1)
		self.pw2 = pg.PlotWidget(name="Plot2")
		vcan.addWidget(self.pw2)

		# SET ALL VERTICAL COLUMNS TOGETHER
		hbox = QHBoxLayout()
		hbox.addLayout(v8,1)
		hbox.addLayout(vcan,3.75)
		
    ##############################################
    # PLOT 1 settings
		# create plot and add it to the figure canvas		
		self.p0 = self.pw1.plotItem
		self.curve1=[self.p0.plot()]
		# create plot and add it to the figure
		self.p0vb = pg.ViewBox()
		self.curve5=pg.PlotCurveItem(pen=None)
		self.p0vb.addItem(self.curve5)
		# connect respective axes to the plot 
		self.p0.showAxis('right')
		self.p0.getAxis('right').setLabel("10-bit Arduino output")
		self.p0.scene().addItem(self.p0vb)
		self.p0.getAxis('right').linkToView(self.p0vb)
		self.p0vb.setXLink(self.p0)
		# Use automatic downsampling and clipping to reduce the drawing load
		self.pw1.setDownsampling(mode='peak')
		self.pw1.setClipToView(True)
		
		# PLOT 2 settings
		# create plot and add it to the figure canvas
		self.p1 = self.pw2.plotItem
		self.curve2=self.p1.plot(pen='r')
		self.curve3=self.p1.plot()
		# create plot and add it to the figure
		self.p2 = pg.ViewBox()
		self.curve4=pg.PlotCurveItem(pen='y')
		self.curve6=pg.PlotCurveItem(pen='m')
		self.p2.addItem(self.curve4)
		self.p2.addItem(self.curve6)
		# connect respective axes to the plot 
		self.p1.showAxis('right')
		self.p1.getAxis('right').setLabel("Wavelength", units='m', color='yellow')
		self.p1.scene().addItem(self.p2)
		self.p1.getAxis('right').linkToView(self.p2)
		self.p2.setXLink(self.p1)
		# Use automatic downsampling and clipping to reduce the drawing load
		self.pw2.setDownsampling(mode='peak')
		self.pw2.setClipToView(True)
		
		# Initialize and set titles and axis names for both plots
		self.clear_vars_graphs()
		###############################################################################
		
		self.inst_list = {}
		self.colors = itertools.cycle(["r", "b", "g", "y", "m", "c", "w"])
		
		self.threadpool = QThreadPool()
		print("Multithreading in Run_COMPexPRO with maximum %d threads" % self.threadpool.maxThreadCount())
		
		# reacts to choises picked in the menu
		self.combo1.activated[str].connect(self.onActivated1)
		self.combo2.activated[str].connect(self.onActivated2)
		self.combo3.activated[str].connect(self.onActivated3)
		self.combo4.activated[str].connect(self.onActivated4)
		
		# save all paramter data in the config file
		#self.saveButton.clicked.connect(self.save_)
		#self.saveButton.clicked.connect(self.set_elapsedtime_text)
	
		# run the main script
		self.runButton.clicked.connect(self.set_run)
		
		# cancel the script run
		self.stopButton.clicked.connect(self.set_stop)
		
		self.allFields(False)
		
		##############################################
		
		self.timer = QTimer(self)
		self.timer.timeout.connect(self.set_disconnect)
		self.timer.setSingleShot(True)
		
		##############################################
		
		self.setGeometry(100, 100, 1100, 650)
		self.setWindowTitle("Monochromator CM110 Control And Data Acqusition")
		
		w = QWidget()
		w.setLayout(hbox)
		self.setCentralWidget(w)
		self.show()
Exemplo n.º 21
0
    def initUI(self):
        ############################
        # Layout'ların tanımlanması
        self.mainVerticalLayout = QVBoxLayout()
        self.upHorizontalLayout = QHBoxLayout()
        self.middleHorizontalLayout = QHBoxLayout()
        self.middleHorizontalLayoutRightVerticalLayout = QVBoxLayout()
        self.downHorizontalLayout = QHBoxLayout()
        self.predictionLayout = QHBoxLayout()

        #Gölgeler
        shadow = QGraphicsDropShadowEffect(blurRadius=5, xOffset=3, yOffset=3)
        shadow2 = QGraphicsDropShadowEffect(blurRadius=6, xOffset=5, yOffset=5)

        #Widget'lerin tanımlanması,tasarlanması ve layout'lara eklenemesi

        ############################
        self.imageCheckout = QLabel()
        self.textCheckout = QLabel()

        ############################

        self.sleepLabel = QLabel()
        self.sleepLabel.setText("Uyku Saatleri :")
        self.sleepLabel.setMaximumWidth(150)
        self.sleepLabel.setStyleSheet("""
        color :#f2f3f4;
        background-color:#3b444b;
        border-left:4px Solid  #a52a2a;
        border-right:4px Solid  #a52a2a;
        padding:4px;
        font-size:14px;
        font-family:Courier;
        border-radius:1px;
        font-weight:650;
        """)
        self.sleepLabel.setGraphicsEffect(shadow)

        sep0 = QLabel(":")
        sep1 = QLabel(":")
        sep2 = QLabel("-")

        self.sleepLabelhourCombo1 = QComboBox()
        self.sleepLabelhourCombo2 = QComboBox()

        for i in range(24):
            if i < 10:
                element = "0" + str(i)
            else:
                element = str(i)
            self.sleepLabelhourCombo1.addItem(element, i)  #element,index
            self.sleepLabelhourCombo2.addItem(element, i)  #element,index

        self.sleepLabelMinuteCombo1 = QComboBox()
        self.sleepLabelMinuteCombo2 = QComboBox()

        for i in range(60):
            if i < 10:
                element = "0" + str(i)
            else:
                element = str(i)
            self.sleepLabelMinuteCombo1.addItem(element, i)
            self.sleepLabelMinuteCombo2.addItem(element, i)

        self.ComboHorizontalLayout = QHBoxLayout()

        self.ComboHorizontalLayout.addWidget(self.sleepLabelhourCombo1)
        self.ComboHorizontalLayout.addWidget(sep0)
        self.ComboHorizontalLayout.addWidget(self.sleepLabelMinuteCombo1)
        self.ComboHorizontalLayout.addWidget(sep2)
        self.ComboHorizontalLayout.addWidget(self.sleepLabelhourCombo2)
        self.ComboHorizontalLayout.addWidget(sep1)
        self.ComboHorizontalLayout.addWidget(self.sleepLabelMinuteCombo2)
        self.ComboHorizontalLayout.addStretch()

        self.sleepEfficiencyLabel = QLabel()
        self.sleepEfficiencyLabel.setText("Uyku verimi : ")
        self.sleepEfficiencyLabel.setStyleSheet("""
        color :#f2f3f4;
        background-color:#3b444b;
        border-left:4px Solid  #a52a2a;
        border-right:4px Solid  #a52a2a;
        padding:4px;
        font-size:14px;
        font-family:Courier;
        border-radius:1px;
        font-weight:650;
        """)
        self.sleepEfficiencyLabel.setMaximumWidth(150)
        self.sleepEfficiencyLabel.setGraphicsEffect(shadow)
        self.sleepEfficiency = QLineEdit()
        self.sleepEfficiency.setMaximumWidth(168)
        self.sleepEfficiency.setText("0-100")

        self.addRange = QPushButton()
        self.addRange.setText("Yeni saat aralığı ekle")
        self.addRange.setStyleSheet("""
        font-family : "Times New Roman";
        font-size : 14px;
        font-weight:650;
        background-color:#065535;
        color:#ffc100;
        
        
        """)
        self.addRange.setMaximumWidth(150)
        self.addRange.setGraphicsEffect(shadow)

        self.addRange.clicked.connect(lambda: self.changeHorizontalHeader(-1))

        ############################
        self.Date = QDateEdit()
        date = QDate()
        currentDate = date.currentDate()
        self.Date.setDate(currentDate)
        ############################

        self.downHorizontalLayout.addStretch()
        self.save = QPushButton()
        self.save.setText("Kaydet")
        self.save.setGraphicsEffect(shadow)
        self.save.setStyleSheet("""
        color : #A52A2A;
        font-weight:bold;
        """)
        self.save.clicked.connect(
            self.saveToDataBase
        )  #Bilgileri veritabanına kaydeden fonksiyonun çağrılması
        ############################

        #Zamalayıcılar
        ############################
        self.timer = QTimer()
        self.timer.timeout.connect(self._update)
        self.timer.start(1000)

        self.timer_job = QTimer()
        self.timer_job.timeout.connect(self.predictionButtonControl)
        self.timer_job.start(1000)

        self.fittedColumnsTimer = QTimer()
        self.fittedColumnsTimer.timeout.connect(self.AlltimeFittedColumns)
        self.fittedColumnsTimer.start(1000)

        ############################

        #Tablo
        self.tableWidget = QTableWidget()
        self.tableWidget.setGeometry(QRect(0, 40, 801, 511))
        self.tableWidget.setRowCount(len(self.predictionVariables))
        self.tableWidget.horizontalHeader().sectionDoubleClicked.connect(
            self.changeHorizontalHeader)

        self.tableWidget.setVerticalHeaderLabels(self.predictionVariables)
        ############################

        self.efficiencyPredictionButton = QPushButton()
        self.efficiencyPredictionButton.setMaximumWidth(160)
        self.efficiencyPredictionButton.clicked.connect(
            self.efficiencyPredictionButtonFunction
        )  #Eğer gerekli şartlar sağlanmış ise tahmin şartları sağlanmış ise tahmin sayfasına yönledirecek fonksiyon
        self.efficiencyPredictionButton.setText("Tahmin Sayfası")
        self.efficiencyPredictionButton.setGraphicsEffect(shadow2)
        self.efficiencyPredictionButton.setStyleSheet("""
        font-family:"Times New Roman";
        font-size:14px;
        font-weight: 650;
        color: #d1b9c7;
        background-color: #130015;
        """)
        self.predictionLayout.addWidget(self.efficiencyPredictionButton)

        self.upHorizontalLayout.addWidget(self.Date)
        self.upHorizontalLayout.addStretch()

        self.middleHorizontalLayout.addWidget(self.tableWidget)

        self.middleHorizontalLayoutRightVerticalLayout.addWidget(self.addRange)
        self.middleHorizontalLayoutRightVerticalLayout.addWidget(
            self.sleepLabel)
        self.middleHorizontalLayoutRightVerticalLayout.addLayout(
            self.ComboHorizontalLayout)
        self.middleHorizontalLayoutRightVerticalLayout.addWidget(
            self.sleepEfficiencyLabel)
        self.middleHorizontalLayoutRightVerticalLayout.addWidget(
            self.sleepEfficiency)
        self.middleHorizontalLayoutRightVerticalLayout.addLayout(
            self.predictionLayout)
        self.middleHorizontalLayoutRightVerticalLayout.addStretch()

        self.downHorizontalLayout.addWidget(self.textCheckout)
        self.downHorizontalLayout.addWidget(self.imageCheckout)
        self.downHorizontalLayout.addWidget(self.save)

        self.middleHorizontalLayout.addLayout(
            self.middleHorizontalLayoutRightVerticalLayout)

        #Oluşturulan Layout'ların ana layouta eklenmesi
        self.mainVerticalLayout.addLayout(self.upHorizontalLayout)
        self.mainVerticalLayout.addLayout(self.middleHorizontalLayout)
        self.mainVerticalLayout.addLayout(self.downHorizontalLayout)

        #Tablo boyutlarının ayarlanması
        self.tableWidget.setMaximumWidth(666)
        self.tableWidget.setMinimumWidth(286)

        self.tableWidget.setMaximumHeight(180)
        self.tableWidget.setMinimumHeight(180)
        self.setMaximumHeight(171)

        self.setLayout(self.mainVerticalLayout)
        #Tablo ismine'sağ tıklandığında menu açılmasını sağlayan kod parçası
        self.tableWidget.setContextMenuPolicy(Qt.CustomContextMenu)  #
        self.tableWidget.customContextMenuRequested.connect(self.generateMenu)
        self.tableWidget.viewport().installEventFilter(self)
    def setupUi(self, MainWindow):
        # 定义一个计时器
        self.timer_video = QTimer()
        self.video_path = None
        self.cap = None
        self.all_images_list = []
        self.image_list_index = 0
        # 主窗口参数设置
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(848, 724)
        palette = QPalette()
        palette.setBrush(MainWindow.backgroundRole(),
                         QBrush(QPixmap('./setup.jpg')))
        MainWindow.setPalette(palette)
        # MainWindow.setStyleSheet("#MainWindow{border-image:url(./setup.jpg);}")
        # 计算中间位置
        size_x = 280
        size_y = 45
        mid_x = int(848 / 2) - int(size_x / 2)
        mid_y = 500
        # 大窗口 centralwidget
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        # 设置显示label
        self.show_label = QtWidgets.QLabel(mainWindow)
        self.show_label.setObjectName('show_label')
        self.show_label.setFrameShape(QtWidgets.QFrame.Box)
        self.show_label.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.show_label.setGeometry(20, 40,
                                    int(848 / 2) + 120,
                                    int(724 / 2) + 60)

        # 创建显示结果的label
        self.text1_label = QtWidgets.QLabel(mainWindow)
        self.text1_label.setObjectName('text1_label')
        self.text1_label.setGeometry(600, 50, 200, 30)

        self.score_label = QtWidgets.QLabel(mainWindow)
        self.score_label.setObjectName('score_label')
        self.score_label.setFrameShape(QtWidgets.QFrame.Box)
        self.score_label.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.score_label.setGeometry(600, 80, 200, 30)

        self.text2_label = QtWidgets.QLabel(mainWindow)
        self.text2_label.setObjectName('text2_label')
        self.text2_label.setGeometry(600, 120, 200, 30)

        self.category_label = QtWidgets.QLabel(mainWindow)
        self.category_label.setObjectName('category_label')
        self.category_label.setFrameShape(QtWidgets.QFrame.Box)
        self.category_label.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.category_label.setGeometry(600, 150, 200, 30)

        # 创建停止/开始按钮
        self.stop_btn = QtWidgets.QPushButton(self.centralwidget)
        self.stop_btn.setObjectName('stop')
        self.stop_btn.setGeometry(QtCore.QRect(650, 220, 100, 50))
        self.stop_btn.setStyleSheet(
            "QPushButton{background-color:rgb(220 ,220 ,220 )}"  # 按键背景色
            "QPushButton:hover{color:white}"  # 光标移动到按钮上面后的前景色
            "QPushButton{border-radius:20px}"  # 圆角半径
            "QPushButton:pressed{background-color:rgb(255 ,250 ,240);border: None;}"  # 按下时的样式
        )
        # 初始状态下不可用
        self.stop_btn.setEnabled(False)

        self.star_btn = QtWidgets.QPushButton(self.centralwidget)
        self.star_btn.setObjectName('star')
        self.star_btn.setGeometry(QtCore.QRect(650, 300, 100, 50))
        self.star_btn.setStyleSheet(
            "QPushButton{background-color:rgb(220 ,220 ,220 )}"  # 按键背景色
            "QPushButton:hover{color:rgb(238 ,106, 80)}"  # 光标移动到按钮上面后的前景色
            "QPushButton{border-radius:20px}"  # 圆角半径
            "QPushButton:pressed{background-color:rgb(255 ,250 ,240);border: None;}"  # 按下时的样式
        )
        # 初始状态下不可用
        self.star_btn.setEnabled(False)

        # 上一张按钮
        self.up_btn = QtWidgets.QPushButton(self.centralwidget)
        self.up_btn.setObjectName('up')
        self.up_btn.setGeometry(QtCore.QRect(600, 380, 200, 70))
        self.up_btn.setStyleSheet(
            "QPushButton{background-color:rgb(220 ,220 ,220 )}"  # 按键背景色
            "QPushButton:hover{color:rgb(238 ,106, 80)}"  # 光标移动到按钮上面后的前景色
            "QPushButton{border-radius:30px}"  # 圆角半径
            "QPushButton:pressed{background-color:rgb(255 ,250 ,240);border: None;}"  # 按下时的样式
        )
        # 初始状态下不可用
        self.up_btn.setEnabled(False)

        # 下一张按钮
        self.next_btn = QtWidgets.QPushButton(self.centralwidget)
        self.next_btn.setObjectName('next')
        self.next_btn.setGeometry(QtCore.QRect(600, 480, 200, 70))
        self.next_btn.setStyleSheet(
            "QPushButton{background-color:rgb(220 ,220 ,220)}"  # 按键背景色
            "QPushButton:hover{color:rgb(238 ,106, 80)}"  # 光标移动到按钮上面后的前景色
            "QPushButton{border-radius:30px}"  # 圆角半径
            "QPushButton:pressed{background-color:rgb(255 ,250 ,240);border: None;}"  # 按下时的样式
        )
        # 初始状态下不可用
        self.next_btn.setEnabled(False)

        # 设置按键参数  第一个按钮,单张图片
        self.file = QtWidgets.QPushButton(self.centralwidget)
        # self.file.setGeometry(QtCore.QRect(57, 660, 175, 28))
        self.file.setGeometry(QtCore.QRect(mid_x, mid_y, size_x, size_y))
        self.file.setObjectName("img_detect")
        self.file.setStyleSheet(
            "QPushButton{background-color:rgb(127 ,255 ,212)}"  # 按键背景色
            "QPushButton:hover{color:rgb(238 ,106, 80)}"  # 光标移动到按钮上面后的前景色
            "QPushButton{border-radius:20px}"  # 圆角半径
            "QPushButton:pressed{background-color:rgb(240, 255, 255);border: None;}"  # 按下时的样式
        )

        # 设置第二个push_button,文件夹  255, 228, 181
        self.fileT = QtWidgets.QPushButton(self.centralwidget)
        self.fileT.setGeometry(QtCore.QRect(mid_x, mid_y + 75, size_x, size_y))
        self.fileT.setObjectName("path_detect")
        self.fileT.setStyleSheet(
            "QPushButton{background-color:rgb(255, 228, 181)}"  # 按键背景色
            "QPushButton:hover{color:rgb(238 ,106, 80)}"  # 光标移动到上面后的前景色
            "QPushButton{border-radius:20px}"  # 圆角半径
            "QPushButton:pressed{background-color:rgb(240, 255, 255);border: None;}"  # 按下时的样式
        )

        # 设置第三个push_button,视频分析
        self.fileD = QtWidgets.QPushButton(self.centralwidget)
        self.fileD.setGeometry(
            QtCore.QRect(mid_x, mid_y + 75 * 2, size_x, size_y))
        self.fileD.setObjectName("video_detect")
        self.fileD.setStyleSheet(
            "QPushButton{background-color:rgb(255 ,193 ,193)}"  # 按键背景色
            "QPushButton:hover{color:rgb(238 ,106, 80)}"  # 光标移动到上面后的前景色
            "QPushButton{border-radius:20px}"  # 圆角半径
            "QPushButton:pressed{background-color:rgb(240, 255, 255);border: None;}"  # 按下时的样式
        )

        # 主窗口及菜单栏标题栏设置
        MainWindow.setCentralWidget(self.centralwidget)  # 设置最大布局为主要窗口
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 848, 26))
        # self.menubar.setGeometry(QtCore.QRect(0, 0, 80, 26))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        # 组件名字及翻译
        self.retranslateUi(MainWindow)
        # 通过名字连接槽
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

        ################button按钮快捷键设置################
        if not self.star_btn.isEnabled():
            self.stop_btn.setShortcut('Space')
        if not self.stop_btn.isEnabled():
            self.star_btn.setShortcut('Space')
        self.up_btn.setShortcut('Up')
        self.next_btn.setShortcut('Down')

        ################button按钮点击事件回调函数################
        # 单图片检测槽函数
        self.file.clicked.connect(self.single_image_detect)
        # 文件夹检测槽函数
        self.fileT.clicked.connect(self.file_path_detect)
        # 视频流检测槽函数
        self.fileD.clicked.connect(self.video_stream_detect)
        # 停止按钮槽函数
        self.stop_btn.clicked.connect(self.stop_event)
        # 开始按钮
        self.star_btn.clicked.connect(self.star_event)
        # 下一张按钮
        self.next_btn.clicked.connect(self.next_event)
        # 上一张按钮
        self.up_btn.clicked.connect(self.up_event)
Exemplo n.º 23
0
    def __init__(self, configuration, eve_data, logger=None, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.setupUi(self)
        self.configuration = configuration
        self.eve_data = eve_data
        self.signals = EveworkerSignals()
        self.event_stop = threading.Event()
        self.alert_system_names_readable = []
        self.update_alert_systems()
        self.threadpool = QThreadPool()
        self.log_location = ""
        self.alarm_location = None
        self.logger = logger
        if self.configuration.value["debug"] and self.logger and self.logger:
            self.logger.write_log("Starting GUI")

        # Eve Time
        self.eve_time_statusbar()
        self.evetimer = QTimer(self)
        self.evetimer.timeout.connect(self.eve_time_statusbar)
        self.evetimer.start(10000)
        if self.configuration.value["debug"] and self.logger:
            self.logger.write_log("Eve Time Started")

        # Recent alerts timer
        self.recent_alerts_timer = QTimer(self)
        self.recent_alerts_timer.timeout.connect(self.alert_recent_update)
        self.recent_alerts_timer.start(10000)
        self.recent_alerts = deque()
        if self.configuration.value["debug"] and self.logger:
            self.logger.write_log("Recent alert timer started")

        # Set initial state
        # Set home and log locations, force uppercase, numbers, hyphen in home field
        self.lineEditHome_System.setText(
            self.configuration.value["home_system"])
        self.lineEditEve_Log_Location.setText(
            self.configuration.value["eve_log_location"])
        self.lineEdit_alarm.setText(self.configuration.value["alarm_sound"])
        self.spinBox_recentalerttimeout.setValue(
            self.configuration.value["alert_timeout"])  # mins

        # Set checkboxes
        if self.configuration.value["display_alerts"]:
            self.checkbox_displayalerts.setChecked(True)
        if self.configuration.value["display_clear"]:
            self.checkBox_displayclear.setChecked(True)
        if self.configuration.value["display_all"]:
            self.checkBox_displayall.setChecked(True)
        if self.configuration.value["filter_clear"]:
            self.checkBox_filterclear.setChecked(True)
        if self.configuration.value["filter_status"]:
            self.checkBox_filterstatus.setChecked(True)
        if self.configuration.value["dark_theme"]:
            self.checkBoxDarkMode.setChecked(True)

        # Set the channel list
        self.channelListWidget.addItems(
            self.configuration.value["watched_channels"])
        self.add_channel()

        # Set the alert slider
        self.horizontalSlider_AlertJumps.setValue(
            self.configuration.value["alert_jumps"])
        self.label_alertjumps.setText(
            str(self.configuration.value["alert_jumps"]))

        # Connections
        # Buttons
        self.pushButtonChoose_Eve_Log_Location.clicked.connect(
            self.choose_log_location)
        self.pushButtonSet_Home.clicked.connect(self.set_home)
        self.clearLogButton.clicked.connect(self.clear_log)
        self.addChannelAddButton.clicked.connect(self.add_channel)
        self.removeChannelButton.clicked.connect(lambda: self.remove_channel(
            self.channelListWidget.selectedItems()))

        # Advanced config
        self.pushButtonChoose_alarm_Location.clicked.connect(
            self.choose_alarm_location)
        self.checkbox_displayalerts.stateChanged.connect(
            lambda: self.checkbox_changed(self.checkbox_displayalerts,
                                          "display_alerts"))
        self.checkBox_displayclear.stateChanged.connect(
            lambda: self.checkbox_changed(self.checkBox_displayclear,
                                          "display_clear"))
        self.checkBox_displayall.stateChanged.connect(
            lambda: self.checkbox_changed(self.checkBox_displayall,
                                          "display_all"))
        self.checkBox_filterclear.stateChanged.connect(
            lambda: self.checkbox_changed(self.checkBox_filterclear,
                                          "filter_clear"))
        self.checkBox_filterstatus.stateChanged.connect(
            lambda: self.checkbox_changed(self.checkBox_filterstatus,
                                          "filter_status"))
        self.checkBoxDarkMode.stateChanged.connect(
            lambda: self.checkbox_changed(self.checkBoxDarkMode, "dark_theme"))

        # Alert silder
        self.horizontalSlider_AlertJumps.valueChanged.connect(
            self.alert_slider_changed)

        # Timeout spinner
        self.spinBox_recentalerttimeout.valueChanged.connect(
            self.recent_alert_spinbox_changed)

        # Figure out where logs are stored if first run
        if self.configuration.value["eve_log_location"] == "":
            self.test_path = ""
            if self.configuration.get_platform() == "unix":
                if self.configuration.value["debug"] and self.logger:
                    self.logger.write_log("Detected OS was Unix")
                self.test_path = Path(
                    str(Path.home()) + "/Games/eve-online/drive_c/users/" +
                    getpass.getuser() + "/My Documents/EVE/logs/Chatlogs/")

                if self.check_path(self.test_path):
                    self.configuration.value["eve_log_location"] = str(
                        self.test_path)

            elif self.configuration.get_platform() == "windows":
                if self.configuration.value["debug"] and self.logger:
                    self.logger.write_log("Detected OS was Windows")
                # Check default path on windows
                self.home_path = Path.home()
                self.test_path = self.home_path / "Documents" / "EVE" / "logs" / "Chatlogs"
                if self.check_path(self.test_path):
                    self.configuration.value["eve_log_location"] = str(
                        self.test_path)
                else:
                    # Check if its on Onedrive instead
                    # C:\Users\ user \OneDrive\Documents\EVE\logs
                    self.test_path_odrive = self.home_path / "OneDrive" / "Documents" / "EVE" / "logs" / "Chatlogs"
                    if self.check_path(self.test_path_odrive):
                        self.configuration.value["eve_log_location"] = str(
                            self.test_path_odrive)

            if self.configuration.value["eve_log_location"] == "":
                self.error_message(
                    "Could not determine Eve log path",
                    "Please select your Eve log path in the config tab",
                    "Default path did not exist", "")
                self.configuration.value["eve_log_location"] = str(Path.home())
                if self.configuration.value["debug"] and self.logger:
                    self.logger.write_log(
                        "GUI could not determine Eve log path!")

            self.lineEditEve_Log_Location.setText(
                configuration.value["eve_log_location"])
            self.configuration.flush_config_to_file()

        # Clean up logs on Windows
        if self.configuration.get_platform() == "windows":
            if self.configuration.value["debug"] and self.logger:
                self.logger.write_log("Windows clean up logs (archive)")
            self.archive_old_logs_windows()

        # Re-set home to calculate alerts
        self.set_home()

        # Watchdog worker thread to monitor logs
        self.eveloghandler_worker = eveloghandler.Eveloghandler_worker(
            self.configuration, self.event_stop, self.logger)
        self.eveloghandler_worker.pass_message.connect(
            self.message_ready_process)
        self.start_watchdog()
        if self.configuration.value["debug"] and self.logger:
            self.logger.write_log("Logfile watchdog thread started")

        # Set recent alerts to blank
        self.label_recentalert1.setText("")
        self.label_recentalert2.setText("")
        self.label_recentalert3.setText("")
        self.label_recentalert4.setText("")
        self.label_recentalert5.setText("")
Exemplo n.º 24
0
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(581, 641)
        MainWindow.setStyleSheet("background:transparent;")
        MainWindow.setAttribute(QtCore.Qt.WA_TranslucentBackground)
        MainWindow.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")

        self.idbox = QtWidgets.QLineEdit(self.centralwidget)
        self.idbox.setGeometry(QtCore.QRect(180, 380, 171, 41))
        font = QtGui.QFont()
        font.setFamily("Nexa Light")
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.idbox.setFont(font)
        self.idbox.setAlignment(QtCore.Qt.AlignCenter)
        self.idbox.setStyleSheet("Background:white")
        self.idbox.setObjectName("idbox")

        self.loginbut = QtWidgets.QPushButton(self.centralwidget)
        self.loginbut.setGeometry(QtCore.QRect(220, 430, 91, 31))
        font = QtGui.QFont()
        font.setFamily("Nexa Bold")
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.loginbut.setFont(font)
        self.loginbut.setStyleSheet(
            "QPushButton {background-color: Black} QPushButton:hover {background-color:grey}QPushButton {border-radius:15px}QPushButton {color:White}QPushButton{border:2px solid yellow}QPushButton:pressed{Background-color:yellow};"
        )
        self.loginbut.setObjectName("loginbut")
        self.loginbut.clicked.connect(self.loggedin)

        self.logoutbut = QtWidgets.QPushButton(self.centralwidget)
        self.logoutbut.setGeometry(QtCore.QRect(220, 470, 91, 31))
        font = QtGui.QFont()
        font.setFamily("Nexa Bold")
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.logoutbut.setFont(font)
        self.logoutbut.setStyleSheet(
            "QPushButton {background-color: Black} QPushButton:hover {background-color:grey}QPushButton {border-radius:15px}QPushButton {color:White}QPushButton{border:2px solid yellow}QPushButton:pressed{Background-color:yellow};"
        )
        self.logoutbut.setObjectName("logoutbut")
        self.logoutbut.clicked.connect(self.loggedout)

        self.adminbut = QtWidgets.QPushButton(self.centralwidget)
        self.adminbut.setGeometry(QtCore.QRect(220, 510, 91, 31))
        font = QtGui.QFont()
        font.setFamily("Nexa Bold")
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.adminbut.setFont(font)
        self.adminbut.setStyleSheet(
            "QPushButton {background-color: Black} QPushButton:hover {background-color:grey}QPushButton{border-radius:15px}QPushButton{color:white}QPushButton{border:2px solid yellow}QPushButton:pressed{background-color:yellow};"
        )
        self.adminbut.setObjectName("adminbut")
        self.adminbut.clicked.connect(self.adminwindow)

        self.exitbut = QtWidgets.QPushButton(self.centralwidget)
        self.exitbut.setGeometry(QtCore.QRect(220, 550, 91, 31))
        font = QtGui.QFont()
        font.setFamily("Nexa Bold")
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.exitbut.setFont(font)
        self.exitbut.setStyleSheet(
            "QPushButton {background-color: Black} QPushButton:hover {background-color:grey}QPushButton{border-radius:15px}QPushButton{color:white}QPushButton{border:2px solid yellow}QPushButton:pressed{background-color:red};"
        )
        self.exitbut.setObjectName("exitbut")
        self.exitbut.clicked.connect(self.exit)

        self.namebox = QtWidgets.QLineEdit(self.centralwidget)
        self.namebox.setGeometry(QtCore.QRect(110, 230, 301, 31))
        font = QtGui.QFont()
        font.setFamily("Nexa Light")
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.namebox.setFont(font)
        self.namebox.setAlignment(QtCore.Qt.AlignCenter)
        self.namebox.setReadOnly(True)
        self.namebox.setStyleSheet("background:white")
        self.namebox.setObjectName("namebox")

        self.programbox = QtWidgets.QLineEdit(self.centralwidget)
        self.programbox.setGeometry(QtCore.QRect(110, 280, 301, 31))
        font = QtGui.QFont()
        font.setFamily("Nexa Light")
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.programbox.setFont(font)
        self.programbox.setAlignment(QtCore.Qt.AlignCenter)
        self.programbox.setReadOnly(True)
        self.programbox.setStyleSheet("background:white")
        self.programbox.setObjectName("programbox")

        self.posbox = QtWidgets.QLineEdit(self.centralwidget)
        self.posbox.setGeometry(QtCore.QRect(110, 330, 301, 31))
        font = QtGui.QFont()
        font.setFamily("Nexa Light")
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.posbox.setFont(font)
        self.posbox.setAlignment(QtCore.Qt.AlignCenter)
        self.posbox.setReadOnly(True)
        self.posbox.setStyleSheet("background:White")
        self.posbox.setObjectName("posbox")

        self.timebox = QtWidgets.QLineEdit(self.centralwidget)
        self.timebox.setGeometry(QtCore.QRect(75, 510, 91, 27))
        font = QtGui.QFont()
        font.setFamily("Nexa Light")
        font.setPointSize(11)
        font.setBold(True)
        font.setWeight(75)
        self.timebox.setFont(font)
        self.timebox.setAlignment(QtCore.Qt.AlignCenter)
        self.timebox.setReadOnly(True)
        self.timebox.setStyleSheet(
            "background:White; border:2px solid yellow;")
        self.timebox.setObjectName("timebox")
        timer = QTimer(self)
        timer.timeout.connect(self.showTime)
        timer.start(1000)

        self.datebox = QtWidgets.QLineEdit(self.centralwidget)
        self.datebox.setGeometry(QtCore.QRect(75, 570, 140, 27))
        font = QtGui.QFont()
        font.setFamily("Nexa Light")
        font.setPointSize(9)
        font.setBold(True)
        font.setWeight(75)
        self.datebox.setFont(font)
        self.datebox.setAlignment(QtCore.Qt.AlignCenter)
        self.datebox.setReadOnly(True)
        self.datebox.setStyleSheet(
            "background:White; border:2px solid yellow;")
        self.datebox.setObjectName("datebox")
        self.showTime()
        self.label = QtWidgets.QLabel(self.centralwidget)
        self.label.setGeometry(QtCore.QRect(20, -20, 521, 641))
        self.label.setObjectName("label")

        self.Time = QtWidgets.QLabel(self.centralwidget)
        self.Time.setGeometry(QtCore.QRect(75, 480, 71, 31))
        font = QtGui.QFont()
        font.setFamily("Nexa Bold")
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.Time.setFont(font)
        self.Time.setStyleSheet("color: rgb(255, 255, 0);")
        self.Time.setObjectName("Time")

        self.Date = QtWidgets.QLabel(self.centralwidget)
        self.Date.setGeometry(QtCore.QRect(75, 540, 71, 31))
        font = QtGui.QFont()
        font.setFamily("Nexa Bold")
        font.setPointSize(14)
        font.setBold(True)
        font.setWeight(75)
        self.Date.setFont(font)
        self.Date.setStyleSheet("color: rgb(255, 255, 0);")
        self.Date.setObjectName("Date")
        self.label.raise_()
        self.timebox.raise_()
        self.datebox.raise_()
        self.namebox.raise_()
        self.programbox.raise_()
        self.posbox.raise_()
        self.idbox.raise_()
        self.loginbut.raise_()
        self.logoutbut.raise_()
        self.adminbut.raise_()
        self.Time.raise_()
        self.Date.raise_()
        self.exitbut.raise_()
        MainWindow.setCentralWidget(self.centralwidget)
        MainWindow.keyPressEvent = self.defineKeyPressEvent

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
Exemplo n.º 25
0
    def __init__(self, *args):
        super().__init__(*args)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        OptionsController.write_default_options()

        self.project_save_timer = QTimer()
        self.project_manager = ProjectManager(self)
        self.plugin_manager = PluginManager()
        self.signal_tab_controller = SignalTabController(
            self.project_manager, parent=self.ui.tab_interpretation)
        self.ui.tab_interpretation.layout().addWidget(
            self.signal_tab_controller)
        self.compare_frame_controller = CompareFrameController(
            parent=self.ui.tab_protocol,
            plugin_manager=self.plugin_manager,
            project_manager=self.project_manager)

        self.ui.tab_protocol.layout().addWidget(self.compare_frame_controller)

        self.generator_tab_controller = GeneratorTabController(
            self.compare_frame_controller,
            self.project_manager,
            parent=self.ui.tab_generator)

        self.undo_group = QUndoGroup()
        self.undo_group.addStack(self.signal_tab_controller.signal_undo_stack)
        self.undo_group.addStack(
            self.compare_frame_controller.protocol_undo_stack)
        self.undo_group.addStack(
            self.generator_tab_controller.generator_undo_stack)
        self.undo_group.setActiveStack(
            self.signal_tab_controller.signal_undo_stack)
        self.ui.progressBar.hide()

        self.participant_legend_model = ParticipantLegendListModel(
            self.project_manager.participants)
        self.ui.listViewParticipants.setModel(self.participant_legend_model)

        gtc = self.generator_tab_controller
        gtc.ui.splitter.setSizes([gtc.width() / 0.7, gtc.width() / 0.3])

        self.ui.tab_generator.layout().addWidget(self.generator_tab_controller)

        self.signal_protocol_dict = {}
        """:type: dict[SignalFrameController,ProtocolAnalyzer]"""
        self.signal_tab_controller.ui.lLoadingFile.setText("")

        self.ui.lnEdtTreeFilter.setClearButtonEnabled(True)

        group = QActionGroup(self)
        self.ui.actionFSK.setActionGroup(group)
        self.ui.actionOOK.setActionGroup(group)
        self.ui.actionNone.setActionGroup(group)
        self.ui.actionPSK.setActionGroup(group)

        self.signal_tab_controller.ui.lShiftStatus.clear()

        self.recentFileActionList = []
        self.create_connects()
        self.update_recent_action_list()

        self.filemodel = FileSystemModel(self)
        path = QDir.homePath()

        self.filemodel.setIconProvider(FileIconProvider())
        self.filemodel.setRootPath(path)
        self.file_proxy_model = FileFilterProxyModel(self)
        self.file_proxy_model.setSourceModel(self.filemodel)
        self.ui.fileTree.setModel(self.file_proxy_model)

        self.ui.fileTree.setRootIndex(
            self.file_proxy_model.mapFromSource(self.filemodel.index(path)))
        self.ui.fileTree.setToolTip(path)
        self.ui.fileTree.header().setSectionResizeMode(0, QHeaderView.Stretch)
        self.ui.fileTree.header().setSectionResizeMode(1,
                                                       QHeaderView.Interactive)
        self.ui.fileTree.setFocus()

        self.generator_tab_controller.table_model.cfc = self.compare_frame_controller

        self.ui.actionConvert_Folder_to_Project.setEnabled(False)

        undo_action = self.undo_group.createUndoAction(self)
        undo_action.setIcon(QIcon.fromTheme("edit-undo"))
        undo_action.setShortcut(QKeySequence.Undo)
        self.ui.menuEdit.insertAction(self.ui.actionMinimize_all, undo_action)

        redo_action = self.undo_group.createRedoAction(self)
        redo_action.setIcon(QIcon.fromTheme("edit-redo"))
        redo_action.setShortcut(QKeySequence.Redo)

        self.ui.splitter.setSizes([0, 1])

        self.ui.menuEdit.insertAction(self.ui.actionMinimize_all, redo_action)
        self.refresh_main_menu()

        self.apply_default_view()
        self.project_save_timer.start(
            ProjectManager.AUTOSAVE_INTERVAL_MINUTES * 60 * 1000)

        self.ui.actionProject_settings.setVisible(False)
        self.ui.actionSave_project.setVisible(False)

        # Disabled because never used
        self.ui.actionMinimize_all.setVisible(False)
        self.ui.actionMaximize_all.setVisible(False)
Exemplo n.º 26
0
    def __init__(self, database, server, config):
        super().__init__()
        # База данных сервера
        self.database = database

        self.server_thread = server
        self.config = config

        # кнопка выход
        self.exitAction = QAction('Выход', self)
        self.exitAction.setShortcut('Ctrl+X')
        self.exitAction.triggered.connect(qApp.quit)
        # кнопка настройки сервера
        self.config_button = QAction('Настройки сервера', self)
        # кнопка обновления списка клиентов
        self.refresh_button = QAction('Обновление списка', self)
        # кнопка истории сообщений
        self.show_history_button = QAction('История пользователей', self)

        # Кнопка регистрации пользователя
        self.register_button = QAction('Регистрация пользователя', self)

        # Кнопка удаления пользователя
        self.remove_button = QAction('Удаление пользователя', self)

        # Статусбар
        self.statusBar()
        self.statusBar().showMessage('Сервер запущен')
        # Тулбар
        self.toolbar = self.addToolBar('MainBar')
        self.toolbar.addAction(self.refresh_button)
        self.toolbar.addAction(self.show_history_button)
        self.toolbar.addAction(self.register_button)
        self.toolbar.addAction(self.remove_button)
        self.toolbar.addAction(self.config_button)
        self.toolbar.addAction(self.exitAction)

        # настройка вида основного окна
        self.setFixedSize(800, 600)
        self.setWindowTitle('Message server')

        self.label = QLabel('Список подключённых клиентов:', self)
        self.label.setFixedSize(240, 15)
        self.label.move(10, 25)
        # Окно со списком подключённых клиентов.
        self.active_clients_table = QTableView(self)
        self.active_clients_table.move(10, 45)
        self.active_clients_table.setFixedSize(780, 400)

        # Таймер, обновляющий список клиентов 1 раз в секунду
        self.timer = QTimer()
        self.timer.timeout.connect(self.create_gui_model)
        self.timer.start(1000)

        # Связываем кнопки с процедурами
        self.refresh_button.triggered.connect(self.create_gui_model)
        self.show_history_button.triggered.connect(self.show_statistics)
        self.config_button.triggered.connect(self.server_config)
        self.register_button.triggered.connect(self.reg_user)
        self.remove_button.triggered.connect(self.rem_user)

        # Отображаем окно.
        self.show()
Exemplo n.º 27
0
    def setupUi(self, MainWindow):

        # set IP
        addr = 'http://192.168.43.47:8888'
        self.test_url = addr + '/api/test'
        content_type = 'image/jpeg'
        self.headers = {'content-type': content_type}
        self.clientImID = int(round(time.time() * 1000))
        self.resDict = {}
        self.imgHeight = 1024
        self.imgWidth = 1280
        self.laserImg = np.zeros((self.imgHeight, self.imgWidth))
        self.inferredImg = np.zeros((self.imgHeight, self.imgWidth))
        self.nolightImg = np.zeros((self.imgHeight, self.imgWidth))

        #查看图片是否正常采集
        self.laser_img_got = 0
        self.inferred_img_got = 0
        self.nolight_img_got = 0

        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(800, 600)
        self.laser_trigger = 0
        self.inferred_trigger = 0
        self.nolight_trigger = 0
        self.laser_exposure = 4000
        self.inferred_exposure = 3000
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.img_win = QtWidgets.QLabel(self.centralwidget)
        self.img_win.setGeometry(QtCore.QRect(10, 10, 600, 480))
        self.img_win.setText("")
        self.img_win.setPixmap(QtGui.QPixmap("black.png"))
        self.img_win.setScaledContents(True)
        self.img_win.setObjectName("label")
        self.settingButton = QtWidgets.QPushButton(self.centralwidget)
        self.settingButton.setGeometry(QtCore.QRect(660, 410, 111, 61))
        font = QtGui.QFont()
        font.setFamily("Agency FB")
        font.setPointSize(18)
        font.setBold(True)
        font.setWeight(75)
        self.settingButton.setFont(font)
        self.settingButton.setObjectName("settingButton")
        self.label_2 = QtWidgets.QLabel(self.centralwidget)
        self.label_2.setGeometry(QtCore.QRect(23, 520, 121, 31))
        font = QtGui.QFont()
        font.setFamily("Agency FB")
        font.setPointSize(18)
        font.setBold(True)
        font.setWeight(75)
        self.label_2.setFont(font)
        self.label_2.setObjectName("label_2")
        self.label_3 = QtWidgets.QLabel(self.centralwidget)
        self.label_3.setGeometry(QtCore.QRect(160, 520, 261, 31))
        font = QtGui.QFont()
        font.setFamily("Agency FB")
        font.setPointSize(18)
        font.setBold(True)
        font.setWeight(75)
        self.label_3.setFont(font)
        self.label_3.setObjectName("label_3")
        self.label_4 = QtWidgets.QLabel(self.centralwidget)
        self.label_4.setGeometry(QtCore.QRect(640, 20, 91, 31))
        font = QtGui.QFont()
        font.setFamily("Agency FB")
        font.setPointSize(18)
        font.setBold(True)
        font.setWeight(75)
        self.label_4.setFont(font)
        self.label_4.setObjectName("label_4")
        self.label_5 = QtWidgets.QLabel(self.centralwidget)
        self.label_5.setGeometry(QtCore.QRect(660, 60, 91, 21))
        font = QtGui.QFont()
        font.setFamily("Times New Roman")
        font.setPointSize(22)
        font.setBold(True)
        font.setWeight(75)
        self.label_5.setFont(font)
        self.label_5.setObjectName("label_5")
        self.manualButton = QtWidgets.QPushButton(self.centralwidget)
        self.manualButton.setGeometry(QtCore.QRect(660, 330, 111, 71))
        font = QtGui.QFont()
        font.setFamily("Agency FB")
        font.setPointSize(18)
        font.setBold(True)
        font.setWeight(75)
        self.manualButton.setFont(font)
        self.manualButton.setObjectName("manualButton")
        self.confirmButton = QtWidgets.QPushButton(self.centralwidget)
        self.confirmButton.setGeometry(QtCore.QRect(630, 120, 61, 61))
        font = QtGui.QFont()
        font.setFamily("Agency FB")
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.confirmButton.setFont(font)
        self.confirmButton.setObjectName("confirmButton")
        self.cancelButton = QtWidgets.QPushButton(self.centralwidget)
        self.cancelButton.setGeometry(QtCore.QRect(720, 120, 61, 61))
        font = QtGui.QFont()
        font.setFamily("Agency FB")
        font.setPointSize(12)
        font.setBold(True)
        font.setWeight(75)
        self.cancelButton.setFont(font)
        self.cancelButton.setObjectName("cancelButton")
        self.label_6 = QtWidgets.QLabel(self.centralwidget)
        self.label_6.setGeometry(QtCore.QRect(650, 220, 121, 31))
        font = QtGui.QFont()
        font.setFamily("Agency FB")
        font.setPointSize(18)
        font.setBold(True)
        font.setWeight(75)
        self.label_6.setFont(font)
        self.label_6.setObjectName("label_6")

        self.exitButton = QtWidgets.QPushButton(self.centralwidget)
        self.exitButton.setGeometry(QtCore.QRect(660, 480, 111, 61))
        font = QtGui.QFont()
        font.setFamily("Agency FB")
        font.setPointSize(18)
        font.setBold(True)
        font.setWeight(75)
        self.exitButton.setFont(font)
        self.exitButton.setObjectName("exitButton")

        # 测试用##############################
        self.capButton = QtWidgets.QPushButton(self.centralwidget)
        self.capButton.setGeometry(QtCore.QRect(550, 510, 91, 41))
        self.capButton.setObjectName("capButton")
        self.initCamButton = QtWidgets.QPushButton(self.centralwidget)
        self.initCamButton.setGeometry(QtCore.QRect(280, 510, 121, 41))
        self.initCamButton.setObjectName("initCamButton")
        self.stopCamButton = QtWidgets.QPushButton(self.centralwidget)
        self.stopCamButton.setGeometry(QtCore.QRect(410, 510, 121, 41))
        self.stopCamButton.setObjectName("stopCamButton")
        #####################################


        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 23))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.led = LedIndicatorWidget.LedIndicator(self.centralwidget)
        self.led.setDisabled(True)
        self.led.setGeometry(QtCore.QRect(690, 270, 31, 31))

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        MainWindow.setWindowFlags(Qt.FramelessWindowHint)
        self.exitButton.clicked.connect(MainWindow.close)
        self.manualButton.clicked.connect(self.showManualUI)
        self.settingButton.clicked.connect(self.showSettingUI)
        #打开/关闭相机
        self.initCamButton.clicked.connect(self.get_real_time_img)
        self.stopCamButton.clicked.connect(self.stop_cam)

        self.capButton.clicked.connect(self.simulate_cap_images)

        self.settingButton.setDisabled(True)
        self.stopCamButton.setDisabled(True)

        self.resized = cv2.imread('black.png')
        height, width, bytesPerComponent = self.resized.shape
        bytesPerLine = bytesPerComponent * width

        if (bytesPerComponent == 3):
            self.QImg2 = QImage(self.resized.data, width, height, bytesPerLine,
                                QImage.Format_RGB888)
        else:
            self.QImg2 = QImage(self.resized.data, width, height, bytesPerLine,
                                QImage.Format_Grayscale8)

        if (bytesPerComponent == 3):
            self.QImg2 = QImage(self.resized.data, width, height, bytesPerLine,
                                QImage.Format_RGB888).rgbSwapped()
        self.pixmap = QtGui.QPixmap.fromImage(self.QImg2)

        self.confirmButton.clicked.connect(self.confirm_result)
        self.cancelButton.clicked.connect(self.cancel_result)

        self.timer = QTimer()
        self.timer.timeout.connect(self.update_realtime_label)
        self.timer.start(50)

        self.timer2 = QTimer()
        self.timer2.timeout.connect(self.test_connection)
        self.timer2.start(50)
    def __init__(self, key, address, properties, api_prefix, plugin_path):
        super().__init__(key, address, properties, api_prefix)
        # Store the address of the master.
        self._master_address = address
        name_property = properties.get(b"name", b"")
        if name_property:
            name = name_property.decode("utf-8")
        else:
            name = key

        self._plugin_path = plugin_path

        self.setName(name)
        description = i18n_catalog.i18nc(
            "@action:button Preceded by 'Ready to'.", "Print over network")
        self.setShortDescription(description)
        self.setDescription(description)

        self._stage = OutputStage.ready
        host_override = os.environ.get("CLUSTER_OVERRIDE_HOST", "")
        if host_override:
            Logger.log(
                "w",
                "Environment variable CLUSTER_OVERRIDE_HOST is set to [%s], cluster hosts are now set to this host",
                host_override)
            self._host = "http://" + host_override
        else:
            self._host = "http://" + address

        # is the same as in NetworkPrinterOutputDevicePlugin
        self._cluster_api_version = "1"
        self._cluster_api_prefix = "/cluster-api/v" + self._cluster_api_version + "/"
        self._api_base_uri = self._host + self._cluster_api_prefix

        self._file_name = None
        self._progress_message = None
        self._request = None
        self._reply = None

        # The main reason to keep the 'multipart' form data on the object
        # is to prevent the Python GC from claiming it too early.
        self._multipart = None

        self._print_view = None
        self._request_job = []

        self._monitor_view_qml_path = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            "ClusterMonitorItem.qml")
        self._control_view_qml_path = os.path.join(
            os.path.dirname(os.path.abspath(__file__)),
            "ClusterControlItem.qml")

        self._print_jobs = []
        self._print_job_by_printer_uuid = {}
        self._print_job_by_uuid = {}  # Print jobs by their own uuid
        self._printers = []
        self._printers_dict = {}  # by unique_name

        self._connected_printers_type_count = []
        self._automatic_printer = {
            "unique_name": "",
            "friendly_name": "Automatic"
        }  # empty unique_name IS automatic selection
        self._selected_printer = self._automatic_printer

        self._cluster_status_update_timer = QTimer()
        self._cluster_status_update_timer.setInterval(5000)
        self._cluster_status_update_timer.setSingleShot(False)
        self._cluster_status_update_timer.timeout.connect(
            self._requestClusterStatus)

        self._can_pause = True
        self._can_abort = True
        self._can_pre_heat_bed = False
        self._cluster_size = int(properties.get(b"cluster_size", 0))

        self._cleanupRequest()

        #These are texts that are to be translated for future features.
        temporary_translation = i18n_catalog.i18n(
            "This printer is not set up to host a group of connected Ultimaker 3 printers."
        )
        temporary_translation2 = i18n_catalog.i18nc(
            "Count is number of printers.",
            "This printer is the host for a group of {count} connected Ultimaker 3 printers."
        ).format(count=3)
        temporary_translation3 = i18n_catalog.i18n(
            "{printer_name} has finished printing '{job_name}'. Please collect the print and confirm clearing the build plate."
        )  #When finished.
        temporary_translation4 = i18n_catalog.i18n(
            "{printer_name} is reserved to print '{job_name}'. Please change the printer's configuration to match the job, for it to start printing."
        )  #When configuration changed.
Exemplo n.º 29
0
    def __init__(self, parent=None, controller=None):
        super().__init__(parent=parent, controller=controller)

        self._token = CancelToken()

        self._uiDebouncer = QTimer()
        self._uiDebouncer.setSingleShot(True)
        self._uiDebouncer.timeout.connect(self.on_debounced_gui)

        self._params = 0

        # region LO params
        self._spinPlo = QDoubleSpinBox(parent=self)
        self._spinPlo.setMinimum(-30)
        self._spinPlo.setMaximum(30)
        self._spinPlo.setSingleStep(1)
        self._spinPlo.setValue(-5)
        self._spinPlo.setSuffix(' дБм')
        self._devices._layout.addRow('Pгет=', self._spinPlo)

        self._spinFloMin = QDoubleSpinBox(parent=self)
        self._spinFloMin.setMinimum(0)
        self._spinFloMin.setMaximum(40)
        self._spinFloMin.setSingleStep(1)
        self._spinFloMin.setValue(0.05)
        self._spinFloMin.setSuffix(' ГГц')
        self._devices._layout.addRow('Fгет.мин=', self._spinFloMin)

        self._spinFloMax = QDoubleSpinBox(parent=self)
        self._spinFloMax.setMinimum(0)
        self._spinFloMax.setMaximum(40)
        self._spinFloMax.setSingleStep(1)
        self._spinFloMax.setValue(3.05)
        self._spinFloMax.setSuffix(' ГГц')
        self._devices._layout.addRow('Fгет.макс=', self._spinFloMax)

        self._spinFloDelta = QDoubleSpinBox(parent=self)
        self._spinFloDelta.setMinimum(0)
        self._spinFloDelta.setMaximum(40)
        self._spinFloDelta.setSingleStep(0.1)
        self._spinFloDelta.setValue(0.5)
        self._spinFloDelta.setSuffix(' ГГц')
        self._devices._layout.addRow('ΔFгет=', self._spinFloDelta)

        self._checkX2FreqLo = QCheckBox(parent=self)
        self._checkX2FreqLo.setChecked(False)
        self._devices._layout.addRow('x2 Fгет.', self._checkX2FreqLo)
        # endregion LO

        # region RF params
        self._spinPrfMin = QDoubleSpinBox(parent=self)
        self._spinPrfMin.setMinimum(-30)
        self._spinPrfMin.setMaximum(30)
        self._spinPrfMin.setSingleStep(1)
        self._spinPrfMin.setValue(-20)
        self._spinPrfMin.setSuffix(' дБм')
        self._devices._layout.addRow('Pвх.мин=', self._spinPrfMin)

        self._spinPrfMax = QDoubleSpinBox(parent=self)
        self._spinPrfMax.setMinimum(-30)
        self._spinPrfMax.setMaximum(30)
        self._spinPrfMax.setSingleStep(1)
        self._spinPrfMax.setValue(6)
        self._spinPrfMax.setSuffix(' дБм')
        self._devices._layout.addRow('Pвх.макс=', self._spinPrfMax)

        self._spinPrfDelta = QDoubleSpinBox(parent=self)
        self._spinPrfDelta.setMinimum(-30)
        self._spinPrfDelta.setMaximum(30)
        self._spinPrfDelta.setSingleStep(1)
        self._spinPrfDelta.setValue(2)
        self._spinPrfDelta.setSuffix(' дБм')
        self._devices._layout.addRow('ΔPвх.=', self._spinPrfDelta)

        self._spinFrfMin = QDoubleSpinBox(parent=self)
        self._spinFrfMin.setMinimum(0)
        self._spinFrfMin.setMaximum(40)
        self._spinFrfMin.setSingleStep(1)
        self._spinFrfMin.setValue(0.06)
        self._spinFrfMin.setSuffix(' ГГц')
        self._devices._layout.addRow('Fвх.мин=', self._spinFrfMin)

        self._spinFrfMax = QDoubleSpinBox(parent=self)
        self._spinFrfMax.setMinimum(0)
        self._spinFrfMax.setMaximum(40)
        self._spinFrfMax.setSingleStep(1)
        self._spinFrfMax.setValue(3.06)
        self._spinFrfMax.setSuffix(' ГГц')
        self._devices._layout.addRow('Fвх.макс=', self._spinFrfMax)

        self._spinFrfDelta = QDoubleSpinBox(parent=self)
        self._spinFrfDelta.setMinimum(0)
        self._spinFrfDelta.setMaximum(40)
        self._spinFrfDelta.setSingleStep(0.1)
        self._spinFrfDelta.setValue(0.5)
        self._spinFrfDelta.setSuffix(' ГГц')
        self._devices._layout.addRow('ΔFвх.=', self._spinFrfDelta)
        # endregion

        # region source params
        self._spinUsrc = QDoubleSpinBox(parent=self)
        self._spinUsrc.setMinimum(4.75)
        self._spinUsrc.setMaximum(5.25)
        self._spinUsrc.setSingleStep(0.25)
        self._spinUsrc.setValue(5)
        self._spinUsrc.setSuffix(' В')
        self._devices._layout.addRow('Uпит.=', self._spinUsrc)
        # endregion

        # region calc params
        self._spinLoss = QDoubleSpinBox(parent=self)
        self._spinLoss.setMinimum(0)
        self._spinLoss.setMaximum(50)
        self._spinLoss.setSingleStep(1)
        self._spinLoss.setValue(0.82)
        self._spinLoss.setSuffix(' дБ')
        self._devices._layout.addRow('Пбал.=', self._spinLoss)
        # endregion

        # region SA params
        self._spinRefLevel = QDoubleSpinBox(parent=self)
        self._spinRefLevel.setMinimum(-20)
        self._spinRefLevel.setMaximum(20)
        self._spinRefLevel.setSingleStep(1)
        self._spinRefLevel.setValue(10)
        self._spinRefLevel.setSuffix(' дБ')
        self._devices._layout.addRow('Ref.level=', self._spinRefLevel)

        self._spinScaleY = QDoubleSpinBox(parent=self)
        self._spinScaleY.setMinimum(0)
        self._spinScaleY.setMaximum(50)
        self._spinScaleY.setSingleStep(1)
        self._spinScaleY.setValue(5)
        self._spinScaleY.setSuffix(' дБ')
        self._devices._layout.addRow('Scale y=', self._spinScaleY)
Exemplo n.º 30
0
    def __init__(self, mode):
        super(MainWindow, self).__init__()
        # Running mode of this gui. Options:
        #  - server-gui: Normal mode, starts bluesky server together with gui
        #  - client: starts only gui in client mode, can connect to existing
        #    server.
        self.mode = mode

        self.radarwidget = RadarWidget()
        self.nd = ND(shareWidget=self.radarwidget)
        self.infowin = InfoWindow()

        try:
            self.docwin = DocWindow(self)
        except Exception as e:
            print('Couldnt make docwindow:', e)
        # self.aman = AMANDisplay()
        gltimer = QTimer(self)
        gltimer.timeout.connect(self.radarwidget.updateGL)
        gltimer.timeout.connect(self.nd.updateGL)
        gltimer.start(50)

        if is_osx:
            app.instance().setWindowIcon(
                QIcon(os.path.join(bs.settings.gfx_path, 'bluesky.icns')))
        else:
            app.instance().setWindowIcon(
                QIcon(os.path.join(bs.settings.gfx_path, 'icon.gif')))

        uic.loadUi(os.path.join(bs.settings.gfx_path, 'mainwindow.ui'), self)

        # list of buttons to connect to, give icons, and tooltips
        #           the button         the icon      the tooltip    the callback
        buttons = {
            self.zoomin: ['zoomin.svg', 'Zoom in', self.buttonClicked],
            self.zoomout: ['zoomout.svg', 'Zoom out', self.buttonClicked],
            self.panleft: ['panleft.svg', 'Pan left', self.buttonClicked],
            self.panright: ['panright.svg', 'Pan right', self.buttonClicked],
            self.panup: ['panup.svg', 'Pan up', self.buttonClicked],
            self.pandown: ['pandown.svg', 'Pan down', self.buttonClicked],
            self.ic: ['stop.svg', 'Initial condition', self.buttonClicked],
            self.op: ['play.svg', 'Operate', self.buttonClicked],
            self.hold: ['pause.svg', 'Hold', self.buttonClicked],
            self.fast: ['fwd.svg', 'Enable fast-time', self.buttonClicked],
            self.fast10:
            ['ffwd.svg', 'Fast-forward 10 seconds', self.buttonClicked],
            self.sameic: ['frwd.svg', 'Restart same IC', self.buttonClicked],
            self.showac: ['AC.svg', 'Show/hide aircraft', self.buttonClicked],
            self.showpz: ['PZ.svg', 'Show/hide PZ', self.buttonClicked],
            self.showapt:
            ['apt.svg', 'Show/hide airports', self.buttonClicked],
            self.showwpt:
            ['wpt.svg', 'Show/hide waypoints', self.buttonClicked],
            self.showlabels:
            ['lbl.svg', 'Show/hide text labels', self.buttonClicked],
            self.showmap:
            ['geo.svg', 'Show/hide satellite image', self.buttonClicked],
            self.shownodes:
            ['nodes.svg', 'Show/hide node list', self.buttonClicked]
        }

        for b in buttons.items():
            # Set icon
            if not b[1][0] is None:
                icon = QIcon(
                    os.path.join(bs.settings.gfx_path, 'icons/' + b[1][0]))
                b[0].setIcon(icon)
            # Set tooltip
            if not b[1][1] is None:
                b[0].setToolTip(b[1][1])
            # Connect clicked signal
            b[0].clicked.connect(b[1][2])

        # Link menubar buttons
        self.action_Open.triggered.connect(self.show_file_dialog)
        self.action_Save.triggered.connect(self.buttonClicked)
        self.actionBlueSky_help.triggered.connect(self.show_doc_window)

        self.radarwidget.setParent(self.centralwidget)
        self.verticalLayout.insertWidget(0, self.radarwidget, 1)
        # Connect to io client's nodelist changed signal
        bs.net.nodes_changed.connect(self.nodesChanged)
        bs.net.actnodedata_changed.connect(self.actnodedataChanged)
        bs.net.event_received.connect(self.on_simevent_received)
        bs.net.stream_received.connect(self.on_simstream_received)
        bs.net.signal_quit.connect(self.closeEvent)

        self.nodetree.setVisible(False)
        self.nodetree.setIndentation(0)
        self.nodetree.setColumnCount(2)
        self.nodetree.setStyleSheet('padding:0px')
        self.nodetree.setAttribute(Qt.WA_MacShowFocusRect, False)
        self.nodetree.header().resizeSection(0, 130)
        self.nodetree.itemClicked.connect(self.nodetreeClicked)
        self.maxhostnum = 0
        self.hosts = dict()
        self.nodes = dict()

        fgcolor = '#%02x%02x%02x' % fg
        bgcolor = '#%02x%02x%02x' % bg

        self.stackText.setStyleSheet('color:' + fgcolor +
                                     '; background-color:' + bgcolor)
        self.lineEdit.setStyleSheet('color:' + fgcolor +
                                    '; background-color:' + bgcolor)

        self.nconf_cur = self.nconf_tot = self.nlos_cur = self.nlos_tot = 0

        app.instance().installEventFilter(self)