Exemplo n.º 1
0
    def __init__(self, parent=None):
        super(AddDialogWidget, self).__init__(parent)

        nameLabel = QLabel("Name")
        addressLabel = QLabel("Address")
        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok |
                                      QDialogButtonBox.Cancel)

        self.nameText = QLineEdit()
        self.addressText = QTextEdit()

        grid = QGridLayout()
        grid.setColumnStretch(1, 2)
        grid.addWidget(nameLabel, 0, 0)
        grid.addWidget(self.nameText, 0, 1)
        grid.addWidget(addressLabel, 1, 0, Qt.AlignLeft | Qt.AlignTop)
        grid.addWidget(self.addressText, 1, 1, Qt.AlignLeft)

        layout = QVBoxLayout()
        layout.addLayout(grid)
        layout.addWidget(buttonBox)

        self.setLayout(layout)

        self.setWindowTitle("Add a Contact")

        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)
Exemplo n.º 2
0
    def __init__(self, previewImage, fileName):
        super(ImageView, self).__init__()

        self.fileName = fileName

        mainLayout = QVBoxLayout(self)
        self.imageLabel = QLabel()
        self.imageLabel.setPixmap(QPixmap.fromImage(previewImage))
        mainLayout.addWidget(self.imageLabel)

        topLayout = QHBoxLayout()
        self.fileNameLabel = QLabel(QDir.toNativeSeparators(fileName))
        self.fileNameLabel.setTextInteractionFlags(Qt.TextBrowserInteraction)

        topLayout.addWidget(self.fileNameLabel)
        topLayout.addStretch()
        copyButton = QPushButton("Copy")
        copyButton.setToolTip("Copy file name to clipboard")
        topLayout.addWidget(copyButton)
        copyButton.clicked.connect(self.copy)
        launchButton = QPushButton("Launch")
        launchButton.setToolTip("Launch image viewer")
        topLayout.addWidget(launchButton)
        launchButton.clicked.connect(self.launch)
        mainLayout.addLayout(topLayout)
Exemplo n.º 3
0
    def __init__(self, argv, parentQWidget = None):
        QWidget.__init__(self)

        const.mode_interactive = 1
        const.mode_file = 2
        const.mode_batch = 3
        const.mode_default = const.mode_batch

        arg_file = ''
        if '-i' in argv:
            mode = const.mode_interactive
        elif '-b' in argv:
            mode = const.mode_batch
        elif '-f' in argv:
            mode = const.mode_file
            idx = argv.index('-f')
            arg_file = argv[idx+1]

        src_path = None
        if '-s' in argv:
            idx = argv.index('-s')
            src_path = argv[idx+1]

        if '-c' in argv:
            idx = argv.index('-c')
            cfg_file = argv[idx+1]

        hbox = QHBoxLayout()
        vbox = QVBoxLayout()
        scrollView = ScrollArea()
        headerView = Header.Header(self)
        scrollView.connectHeaderView(headerView)
        headerView.connectMainView(scrollView.mainView.drawer)
        vbox.addWidget(headerView)
        vbox.addWidget(scrollView)

        toolBox = ToolBox.ToolBox(mode)

        hbox.addLayout(vbox)
        hbox.addLayout(toolBox)

        self.controller = Kitchen.Kitchen(mode,arg_file,cfg_file)
        self.controller.connectView(scrollView.mainView.drawer)
        self.controller.connectToolBox(toolBox)
        self.controller.start()

        srcViewer = SourceViewer.SourceViewer()
        srcViewer.createIndex(src_path)

        toolBox.connectMsgRcv(headerView)
        toolBox.connectMsgRcv(scrollView.mainView.drawer)
        toolBox.connectMsgRcv(self.controller)
        toolBox.connectDiagramView(scrollView.mainView.drawer)

        scrollView.mainView.drawer.setToolBox(toolBox)
        scrollView.mainView.drawer.connectSourceViewer(srcViewer)

        self.setLayout(hbox)
Exemplo n.º 4
0
	def __init__(self, parent = None):
		super(Form, self).__init__(parent)

		self.setWindowTitle('My Form')

		self.edit = QLineEdit('Write your name here...')
		self.button = QPushButton('Show Greetings')

		layout = QVBoxLayout()
		layout.addWidget(self.edit)
		layout.addWidget(self.button)
		self.setLayout(layout)

		self.button.clicked.connect(self.greetings)
Exemplo n.º 5
0
    def __init__(self, hiddenLifeline, parent = None):
        super(ShowLifeLineDialog, self).__init__(parent)

        self.theHidden = hiddenLifeline
        layout = QVBoxLayout(self)

        listTitle = QLabel("The message you want to see is blocked by a hidden class object.\n\n%s\n\nDo you want to show the hidden class object?" % hiddenLifeline)
        layout.addWidget(listTitle)

        buttons = QtGui.QDialogButtonBox(QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel, QtCore.Qt.Horizontal, self)
        buttons.button(QDialogButtonBox.Ok).setText('Yes')
        buttons.button(QDialogButtonBox.Cancel).setText('No')
        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)
        layout.addWidget(buttons)
Exemplo n.º 6
0
    def __init__(self, parent=None):
        super(NewAddressTab, self).__init__(parent)

        descriptionLabel = QLabel("There are no contacts in your address book."
                                   "\nClick Add to add new contacts.")

        addButton = QPushButton("Add")

        layout = QVBoxLayout()
        layout.addWidget(descriptionLabel)
        layout.addWidget(addButton, 0, Qt.AlignCenter)

        self.setLayout(layout)

        addButton.clicked.connect(self.addEntry)
Exemplo n.º 7
0
    def addThreadList(self,threads):

        if not self.groupBoxThreadInfo:
            self.groupBoxThreadInfo = QGroupBox()
            self.threadInfo = QLabel("Thread Info.")
            self.groupBoxThreadInfo.setStyleSheet("QGroupBox {border: 1px solid gray; border-radius: 9px; margin-top: 0.5em} QGroupBox::title {subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px;")

        if not self.threadvbox:
            self.threadvbox = QVBoxLayout()

        if not self.listThread:
            self.listThread = QListWidget()
            
        self.listThread.setFixedWidth(200)
        self.listThread.setSelectionMode(QAbstractItemView.MultiSelection)
        QtCore.QObject.connect(self.listThread, QtCore.SIGNAL("itemClicked(QListWidgetItem *)"), self.toggleThreadDisplay)
        self.threadvbox.addWidget(self.threadInfo)
        self.threadvbox.addWidget(self.listThread)
        self.groupBoxThreadInfo.setLayout(self.threadvbox)
        self.addWidget(self.groupBoxThreadInfo)
        self.groupBoxThreadInfo.setSizePolicy(self.sizePolicy)

        for id in threads:
            item = QListWidgetItem(id)
            self.listThread.addItem(item)
Exemplo n.º 8
0
    def initUI(self):
        self.setWindowTitle(self.tr("Tic-Tac-Toe"))
        layout = QVBoxLayout()
        self.setLayout(layout)
        gridLayout = QGridLayout()
        gridLayout.setSpacing(3)
        aiComboBox = QComboBox(self)
        aiComboBox.addItems([self.tr(ai) for ai in self.AIs])
        aiComboBox.currentTextChanged.connect(self.selectAI)
        layout.addWidget(aiComboBox)
        layout.addLayout(gridLayout)

        for tile in self.ticTacToe:
            button = QTicTacToe.QTileButton(self, tile)
            gridLayout.addWidget(button, tile.row, tile.column)
            button.clicked.connect(button.clickEvent)
            tile.delegate = button
Exemplo n.º 9
0
    def initUI(self):
        self.setWindowTitle(self.tr("Fourplay"))
        layout = QVBoxLayout()
        self.setLayout(layout)
        discGridLayout = QGridLayout()
        discGridLayout.setSpacing(4)
        aiComboBox = QComboBox(self)
        aiComboBox.addItems([self.tr(ai) for ai in self.AIs])
        aiComboBox.currentTextChanged.connect(lambda: self.selectAI())
        layout.addWidget(aiComboBox)
        layout.addLayout(discGridLayout)

        for disc in self.fourPlay:
            qDisc = QFourPlay.QDiscButton(self)
            discGridLayout.addWidget(qDisc, disc.row, disc.column)
            qDisc.clicked.connect(lambda qDisc=qDisc, disc=disc: qDisc.clickEvent(disc))
            qDisc.marked(disc)
            disc.delegate = qDisc
Exemplo n.º 10
0
    def __init__(self, parent=None):
        super(AddressWidget, self).__init__(parent)

        self.tableModel = TableModel()
        self.tableView = QTableView()
        self.setupTable()

        statusLabel = QLabel("Tabular data view demo")

        layout = QVBoxLayout()
        layout.addWidget(self.tableView)
        layout.addWidget(statusLabel)
        self.setLayout(layout)
        self.setWindowTitle("Address Book")
        self.resize(800,500)

        # add test data
        self.populateTestData()
Exemplo n.º 11
0
class MyWidget(QWidget):
    def __init__(self):
        QWidget.__init__(self)
 
        self.hello = ["Hallo welt!", "Ciao mondo!",
            "Hei maailma!", "Hola mundo!", "Hei verden!"]
 
        self.button = QPushButton("Click me!")
        self.text = QLabel("Hello World")
        self.text.setAlignment(Qt.AlignCenter)
 
        self.layout = QVBoxLayout()
        self.layout.addWidget(self.text)
        self.layout.addWidget(self.button)
        self.setLayout(self.layout)
 
        self.button.clicked.connect(self.magic)
 
    def magic(self):
        self.text.setText(random.choice(self.hello))
Exemplo n.º 12
0
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        self.server = FortuneServer()

        statusLabel = QLabel()
        statusLabel.setTextInteractionFlags(Qt.TextBrowserInteraction)
        statusLabel.setWordWrap(True)
        quitButton = QPushButton("Quit")
        quitButton.setAutoDefault(False)

        if not self.server.listen():
            QMessageBox.critical(self, "Threaded Fortune Server",
                    "Unable to start the server: %s." % self.server.errorString())
            self.close()
            return

        for ipAddress in QNetworkInterface.allAddresses():
            if ipAddress != QHostAddress.LocalHost and ipAddress.toIPv4Address() != 0:
                break
        else:
            ipAddress = QHostAddress(QHostAddress.LocalHost)

        ipAddress = ipAddress.toString()

        statusLabel.setText("The server is running on\n\nIP: %s\nport: %d\n\n"
                "Run the Fortune Client example now." % (ipAddress, self.server.serverPort()))

        quitButton.clicked.connect(self.close)

        buttonLayout = QHBoxLayout()
        buttonLayout.addStretch(1)
        buttonLayout.addWidget(quitButton)
        buttonLayout.addStretch(1)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(statusLabel)
        mainLayout.addLayout(buttonLayout)
        self.setLayout(mainLayout)

        self.setWindowTitle("Threaded Fortune Server")
Exemplo n.º 13
0
    def __init__(self, parent=None):
        super(HelpWindow,self).__init__(parent)

        self.setWindowTitle("Facepager 3.0 - Help")
        self.setMinimumWidth(600);
        self.setMinimumHeight(600);
        central = QWidget()
        self.setCentralWidget(central)
        vLayout = QVBoxLayout(central)

        self.page = MyQWebEnginePage()
        self.browser = QWebEngineView(central)
        self.browser.setPage(self.page)

        vLayout.addWidget(self.browser)
        hLayout = QHBoxLayout()
        vLayout.addLayout(hLayout)
        hLayout.addStretch(5)
        dismiss = QPushButton(central)
        dismiss.setText("Close")
        dismiss.clicked.connect(self.hide)
        hLayout.addWidget(dismiss)
Exemplo n.º 14
0
    def initializeWindow(self):
        layout = QVBoxLayout()

        self.m_deviceBox = QComboBox()
        self.m_deviceBox.activated[int].connect(self.deviceChanged)
        for deviceInfo in QAudioDeviceInfo.availableDevices(QAudio.AudioOutput):
            self.m_deviceBox.addItem(deviceInfo.deviceName(), deviceInfo)

        layout.addWidget(self.m_deviceBox)

        self.m_modeButton = QPushButton()
        self.m_modeButton.clicked.connect(self.toggleMode)
        self.m_modeButton.setText(self.PUSH_MODE_LABEL)

        layout.addWidget(self.m_modeButton)

        self.m_suspendResumeButton = QPushButton(
                clicked=self.toggleSuspendResume)
        self.m_suspendResumeButton.setText(self.SUSPEND_LABEL)

        layout.addWidget(self.m_suspendResumeButton)

        volumeBox = QHBoxLayout()
        volumeLabel = QLabel("Volume:")
        self.m_volumeSlider = QSlider(Qt.Horizontal, minimum=0, maximum=100,
                singleStep=10)
        self.m_volumeSlider.valueChanged.connect(self.volumeChanged)

        volumeBox.addWidget(volumeLabel)
        volumeBox.addWidget(self.m_volumeSlider)

        layout.addLayout(volumeBox)

        window = QWidget()
        window.setLayout(layout)

        self.setCentralWidget(window)
Exemplo n.º 15
0
    def __init__(self, lifeline, defaultName, parent = None):
        super(ClusterDialog, self).__init__(parent)

        self.lifeline = lifeline
        layout = QVBoxLayout(self)

        message = QLabel('Enter group name')
        layout.addWidget(message)

        self.editClusterName = QLineEdit(defaultName)
        self.editClusterName.setFixedHeight(30)
        self.editClusterName.setFixedWidth(400)
        self.editClusterName.textChanged.connect(self.validateCluster)
        layout.addWidget(self.editClusterName)

        self.validation_msg = QLabel(' ')
        layout.addWidget(self.validation_msg)

        buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, QtCore.Qt.Horizontal, self)
        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)
        layout.addWidget(buttons)

        self.validateCluster()
Exemplo n.º 16
0
    def test_setLayout(self):
        layout = QVBoxLayout()
        btn1 = QPushButton("button_v1")
        layout.addWidget(btn1)

        btn2 = QPushButton("button_v2")
        layout.addWidget(btn2)

        layout2 = QHBoxLayout()

        btn1 = QPushButton("button_h1")
        layout2.addWidget(btn1)

        btn2 = QPushButton("button_h2")
        layout2.addWidget(btn2)

        layout.addLayout(layout2)

        widget = QWidget()
        widget.setLayout(layout)
Exemplo n.º 17
0
    def __init__(self, messages, hiddenLifelines, parent = None):
        super(HiddenMessageDialog, self).__init__(parent)

        self.lifelineList = hiddenLifelines
        self.msgList = messages
        layout = QVBoxLayout(self)

        listTitle = QLabel('Hidden Messages')
        layout.addWidget(listTitle)

        self.listHiddenMessages = QTableWidget(len(self.msgList),4)
        self.listHiddenMessages.setHorizontalHeaderLabels(['Index','Name','Departure','Destination'])
        self.listHiddenMessages.setFixedWidth(400)
        #self.listHiddenMessages.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)
        self.listHiddenMessages.setSelectionBehavior(QAbstractItemView.SelectRows)

        for idx, msg in enumerate(self.msgList):
            self.listHiddenMessages.setItem(idx,0,QTableWidgetItem("%d" % msg['messageindex']))
            self.listHiddenMessages.setItem(idx,1,QTableWidgetItem(msg['message']))
            item = QTableWidgetItem(msg['departure']['class'])
            item.setTextAlignment(QtCore.Qt.AlignmentFlag.AlignRight)
            if msg['departure']['class'] in self.lifelineList:
                item.setForeground(QColor(200,200,200)) 
            self.listHiddenMessages.setItem(idx,2,item)

            item = QTableWidgetItem(msg['dest'])
            item.setTextAlignment(QtCore.Qt.AlignmentFlag.AlignRight)
            if msg['dest'] in self.lifelineList:
                item.setForeground(QColor(200,200,200)) 
            self.listHiddenMessages.setItem(idx,3,item)

        layout.addWidget(self.listHiddenMessages)

        buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, QtCore.Qt.Horizontal, self)
        buttons.button(QDialogButtonBox.Ok).setText('Show')
        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)
        layout.addWidget(buttons)
Exemplo n.º 18
0
class JoinDialog(QDialog):
    def __init__(self, parent=None):
        super(JoinDialog, self).__init__(parent)

        # formatting
        self.setWindowTitle("Join room")

        # validator
        regexp = QtCore.QRegExp('[A-Za-z0-9_]+')
        validator = QtGui.QRegExpValidator(regexp)

        # widgets
        self.room_nameInput = QLineEdit()
        self.room_nameInput.setValidator(validator)

        self.passwordInput = QLineEdit()
        self.passwordInput.setValidator(validator)
        self.passwordInput.setEchoMode(QLineEdit.Password)

        # OK and Cancel buttons
        self.buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self)
        self.buttons.button(QDialogButtonBox.Ok).setText('Join')
        self.buttons.setCenterButtons(True)

        # signals
        self.room_nameInput.textChanged.connect(self.check_input)
        self.room_nameInput.textChanged.emit(self.room_nameInput.text())

        self.passwordInput.textChanged.connect(self.check_input)
        self.passwordInput.textChanged.emit(self.passwordInput.text())

        # layout
        self.mainLayout = QVBoxLayout(self)
        self.mainLayout.addWidget(self.room_nameInput)
        self.mainLayout.addWidget(self.passwordInput)
        self.mainLayout.addWidget(self.buttons)

        self.buttons.accepted.connect(self.accept)
        self.buttons.rejected.connect(self.reject)

        # self.buttons.setEnabled(False)
        self.room_nameInput.setFocus()

    def check_input(self, *args, **kwargs):
        sender = self.sender()
        validator = sender.validator()
        state = validator.validate(sender.text(), 0)[0]

        if state == QtGui.QValidator.Acceptable:
            color = '#ffffff'
        elif state == QtGui.QValidator.Intermediate:
            color = '#ffffff'
        else:
            color = '#f6989d' # red
        sender.setStyleSheet('QLineEdit { background-color: %s }' % color)

    # get current data from the dialog
    def get_room_nameInput(self):
        return self.room_nameInput.text()

    # get current data from the dialog
    def getPasswordInput(self):
        return self.passwordInput.text()

    # static method to create the dialog and return (date, time, accepted)
    @staticmethod
    def run(parent=None):
        dialog = JoinDialog(parent)
        result = dialog.exec_()
        room_name = dialog.get_room_nameInput()
        password = dialog.getPasswordInput()
        return room_name, password, result == QDialog.Accepted
Exemplo n.º 19
0
    def __init__(self, database: Database):

        super(GUI, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        # self.ui.actionGuardar.triggered.connect(self.save_figure)
        self.ui.actionSalir.triggered.connect(self.close)
        self.ui.actionReiniciar.triggered.connect(self.restart_figure)

        self.ui.actionMapa.setChecked(False)
        self.ui.actionFuncion_de_Adquisici_n.setChecked(True)
        self.ui.actionAutomatic.setChecked(False)
        self.ui.action3D.setEnabled(True)

        self.ui.actionMapa.triggered.connect(self.update_images)
        self.ui.actionPredicci_n_GP.triggered.connect(self.update_images)
        self.ui.actionIncertidumbre_GP.triggered.connect(self.update_images)
        self.ui.actionFuncion_de_Adquisici_n.triggered.connect(
            self.update_images)
        self.ui.action3D.triggered.connect(self.send_request)
        self.ui.actionAutomatic.triggered.connect(self.change_automatic)

        self.auto_BO = self.ui.actionAutomatic.isChecked()

        self.db = database
        initial_map = obtain_map_data("E:/ETSI/Proyecto/data/Map/" +
                                      self.db.properties_df['map'].values[0] +
                                      "/map.yaml")
        sensors = {}
        for data in self.db.properties_df.values:
            if data[1] not in sensors.keys():
                sensors[data[1]] = initial_map
        self.selected_sensor = list(sensors.keys())[0]
        self.acq_func = self.db.properties_df["acq"][0]

        wid = QWidget()
        wid.resize(250, 150)
        hbox = QHBoxLayout(wid)

        self.map_fig = Figure(figsize=(7, 5),
                              dpi=72,
                              facecolor=(1, 1, 1),
                              edgecolor=(0, 0, 0))
        self.map_canvas = FigureCanvas(self.map_fig)
        self.map_toolbar = NavigationToolbar(self.map_canvas, self)
        self.map_lay = QVBoxLayout()
        self.map_lay.addWidget(self.map_toolbar)
        self.map_lay.addWidget(self.map_canvas)

        self.gp_fig = Figure(figsize=(7, 5),
                             dpi=72,
                             facecolor=(1, 1, 1),
                             edgecolor=(0, 0, 0))
        self.gp_canvas = FigureCanvas(self.gp_fig)
        self.gp_toolbar = NavigationToolbar(self.gp_canvas, self)
        self.gp_lay = QVBoxLayout()
        self.gp_lay.addWidget(self.gp_toolbar)
        self.gp_lay.addWidget(self.gp_canvas)

        self.std_fig = Figure(figsize=(7, 5),
                              dpi=72,
                              facecolor=(1, 1, 1),
                              edgecolor=(0, 0, 0))
        self.std_canvas = FigureCanvas(self.std_fig)
        self.std_toolbar = NavigationToolbar(self.std_canvas, self)
        self.std_lay = QVBoxLayout()
        self.std_lay.addWidget(self.std_toolbar)
        self.std_lay.addWidget(self.std_canvas)

        self.acq_fig = Figure(figsize=(7, 5),
                              dpi=72,
                              facecolor=(1, 1, 1),
                              edgecolor=(0, 0, 0))
        self.acq_canvas = FigureCanvas(self.acq_fig)
        self.acq_toolbar = NavigationToolbar(self.acq_canvas, self)
        self.acq_lay = QVBoxLayout()
        self.acq_lay.addWidget(self.acq_toolbar)
        self.acq_lay.addWidget(self.acq_canvas)

        hbox.addLayout(self.map_lay)
        hbox.addLayout(self.gp_lay)
        hbox.addLayout(self.std_lay)
        hbox.addLayout(self.acq_lay)

        self.map_canvas.setVisible(False)
        self.map_toolbar.setVisible(False)

        # self.acq_canvas.setVisible(False)
        # self.acq_toolbar.setVisible(False)

        self.setCentralWidget(wid)
        wid.show()

        self.image = []
        self.data = []
        self.titles = []
        self.nans = np.load(
            open('E:/ETSI/Proyecto/data/Databases/numpy_files/nans.npy', 'rb'))
        self.shape = None
        self.axes = []
        self.drone_pos_ax = []
        self.drone_goals_ax = dict()
        self.voronoi_ax = dict()
        self.signal_from_gp_std = False

        xticks = np.arange(0, 1000, 200)
        yticks = np.arange(0, 1500, 200)
        xnticks = [str(num * 10) for num in xticks]
        ynticks = [str(num * 10) for num in yticks]
        self.colors = ["#3B4D77", "#C09235", "#B72F56", "#91B333", "#FFD100"]

        i = 1
        cmap = cm.get_cmap("coolwarm")
        my_cmap = cmap(np.arange(cmap.N))
        my_cmap[:, -1] = np.linspace(1, 0, cmap.N)
        my_cmap = ListedColormap(my_cmap)
        ax = self.map_fig.add_subplot(111)
        # plt.subplot(row, col, i)
        self.image.append(
            ax.imshow(sensors[self.selected_sensor],
                      origin='lower',
                      cmap=my_cmap,
                      zorder=5))
        ax.grid(True, zorder=0, color="white")
        ax.set_facecolor('#eaeaf2')
        ax.tick_params(axis="both", labelsize=30)
        ax.set_ylabel('y [m]', fontsize=30)
        ax.set_xlabel('x [m]', fontsize=30)
        ax.set_xticks(xticks)  # values
        ax.set_xticklabels(xnticks)  # labels
        ax.set_yticks(yticks)  # values
        ax.set_yticklabels(ynticks)  # labels
        self.titles.append("{} real".format(self.selected_sensor))
        # ax.set_title("Map for sensor {}".format(key))
        self.data.append(sensors[self.selected_sensor])
        self.axes.append(ax)
        # return base.from_list(cmap_name, color_list, N)
        ax = self.gp_fig.add_subplot(111)
        # cm.get_cmap(base_cmap, N)
        current_cmap = copy(cm.get_cmap("plasma"))
        current_cmap.set_bad(color="#00000000")
        self.image.append(
            ax.imshow(sensors[self.selected_sensor],
                      origin='lower',
                      cmap=current_cmap,
                      zorder=5))
        ax.grid(True, zorder=0, color="white")
        ax.set_facecolor('#eaeaf2')
        self.titles.append("{} gp".format(self.selected_sensor))
        # ax.set_title("Sensor {} Gaussian Process Regression".format(key))
        ax.tick_params(axis="both", labelsize=30)
        # ax.set_ylabel('y [m]', fontsize=30)
        ax.set_xlabel('x [m]', fontsize=30)
        ax.set_xticks(xticks)  # values
        ax.set_xticklabels(xnticks)  # labels
        ax.set_yticks(yticks)  # values
        ax.set_yticklabels(ynticks)  # labels
        self.data.append(sensors[self.selected_sensor])
        self.image[-1].set_clim(vmin=-2.586, vmax=1.7898)
        cb = self.gp_fig.colorbar(self.image[i], ax=ax)
        cb.ax.tick_params(labelsize=20)
        cb.ax.set_xlabel(r'$SE(\mu (x))$', fontsize=30)
        self.axes.append(ax)
        ax = self.std_fig.add_subplot(111)
        current_cmap = copy(cm.get_cmap("summer"))
        current_cmap.set_bad(color="#00000000")
        self.image.append(
            ax.imshow(sensors[self.selected_sensor],
                      origin='lower',
                      cmap=current_cmap,
                      zorder=5,
                      vmin=0.0,
                      vmax=1.0))
        ax.grid(True, zorder=0, color="white")
        ax.set_facecolor('#eaeaf2')
        self.titles.append("{} gp un".format(self.selected_sensor))
        # ax.set_title("Sensor {} GP Uncertainty".format(key))
        ax.tick_params(axis="both", labelsize=30)
        # ax.set_ylabel('y [m]', fontsize=30)
        ax.set_xlabel('x [m]', fontsize=30)
        ax.set_xticks(xticks)  # values
        ax.set_xticklabels(xnticks)  # labels
        ax.set_yticks(yticks)  # values
        ax.set_yticklabels(ynticks)  # labels
        self.data.append(sensors[self.selected_sensor])
        # self.image[-1].set_clim(vmin=0.0, vmax=1.0)
        cb = self.gp_fig.colorbar(self.image[i + 1], ax=ax)
        cb.ax.tick_params(labelsize=20)
        cb.ax.set_xlabel(r'$\sigma (x)$', fontsize=30)
        self.axes.append(ax)
        ax = self.acq_fig.add_subplot(111)
        current_cmap = copy(cm.get_cmap("YlGn_r"))
        current_cmap.set_bad(color="#00000000")
        self.image.append(
            ax.imshow(sensors[self.selected_sensor],
                      origin='lower',
                      cmap=current_cmap,
                      zorder=5))
        ax.grid(True, zorder=0, color="white")
        ax.set_facecolor('#eaeaf2')
        self.titles.append("{} acq".format(self.selected_sensor))
        # ax.set_title("Sensor {} Acquisition Function".format(key))
        ax.tick_params(axis="both", labelsize=30)
        # ax.set_ylabel('y', fontsize=30)
        ax.set_xlabel('x [m]', fontsize=30)
        ax.set_xticks(xticks)  # values
        ax.set_xticklabels(xnticks)  # labels
        ax.set_yticks(yticks)  # values
        ax.set_yticklabels(ynticks)  # labels
        self.data.append(sensors[self.selected_sensor])
        # cb = self.gp_fig.colorbar(self.image[i + 2], ax=ax, orientation='horizontal')
        # cb.ax.set_xlabel(r'$\mathrm{\mathsf{SEI}} (x)$')
        self.axes.append(ax)
        i += 4
        if self.shape is None:
            self.shape = np.shape(sensors[self.selected_sensor])

        self.row = None
        self.col = None
        self.vmin = 0
        self.vmax = 0
        self.sm = None

        self.coordinator = Coordinator(self.data[0], {"s1"})
        # self.real_map = np.load("E:/ETSI/Proyecto/data/Databases/numpy_files/random_12.npy")
        self.update_thread = QTimer()
        self.update_thread.setInterval(250)
        self.update_thread.timeout.connect(self.update_request)
        self.update_thread.start()

        self.signalManager = SignalManager()
        self.signalManager.sensor_sig.connect(self.request_sensors_update)
        self.signalManager.drones_sig.connect(self.request_drones_update)
        self.signalManager.goals_sig.connect(self.request_goals_update)
        self.signalManager.proper_sig.connect(self.request_proper_update)
        self.signalManager.images_ready.connect(self.update_images)
        self.current_drone_pos = np.zeros((1, 2))
    def _setupUI(self):
        self.setWindowTitle("Export Attributes to USD")
        layout = QVBoxLayout()

        # This section contains the attributes tagged for export.
        label = QLabel()
        label.setText('Exported Attributes:')
        layout.addWidget(label)

        self.exportedAttrsModel = ExportedAttributesModel()
        self.exportedAttrsView = ExportedAttributesView()
        self.exportedAttrsView.verticalHeader().hide()
        self.exportedAttrsView.setModel(self.exportedAttrsModel)
        selectionModel = self.exportedAttrsView.selectionModel()
        selectionModel.selectionChanged.connect(self._onExportedAttrsSelectionChanged)
        self.exportedAttrsModel.dataChanged.connect(self._onModelDataChanged)
        layout.addWidget(self.exportedAttrsView)

        self.removeExportedAttrButton = QPushButton("Remove Exported Attribute")
        self.removeExportedAttrButton.clicked.connect(self._onRemoveExportedAttrPressed)
        self.removeExportedAttrButton.setEnabled(False)
        layout.addWidget(self.removeExportedAttrButton)

        # This section contains the attributes available for export.
        label = QLabel()
        label.setText('Available Attributes:')
        layout.addWidget(label)

        self.userDefinedCheckBox = QCheckBox('User Defined')
        self.userDefinedCheckBox.setToolTip('Show only user-defined (dynamic) attributes')
        self.userDefinedCheckBox.setChecked(True)
        self.userDefinedCheckBox.stateChanged.connect(self._syncUI)
        layout.addWidget(self.userDefinedCheckBox)

        self.addAttrsModel = AddAttributesModel()
        self.addAttrsView = AddAttributesView()
        self.addAttrsView.setModel(self.addAttrsModel)
        selectionModel = self.addAttrsView.selectionModel()
        selectionModel.selectionChanged.connect(self._onAddAttrsSelectionChanged)
        self.addAttrsModel.dataChanged.connect(self._onModelDataChanged)
        layout.addWidget(self.addAttrsView)

        self.addExportedAttrButton = QPushButton("Add Exported Attribute")
        self.addExportedAttrButton.clicked.connect(self._onAddExportedAttrPressed)
        self.addExportedAttrButton.setEnabled(False)
        layout.addWidget(self.addExportedAttrButton)

        self.setLayout(layout)
Exemplo n.º 21
0
 def build_vertical_layout(self):
     self.vertical_layout = QVBoxLayout(self.central_widget)
     self.vertical_layout.setObjectName(u"vertical_layout")
Exemplo n.º 22
0
    def __init__(self, parent=None):
        QWidget.__init__(self)
        self.parent = parent
        self.parent.addWidget(self)
        self.auto_login, self.auto_pwd, self.auto_email, self.auto_time = data.get_autofill(
        )
        self.gridLayout = QGridLayout(self)
        self.gridLayout.setContentsMargins(0, 0, 0, 0)
        self.gridLayout.setSpacing(0)
        self.gridLayout.setColumnStretch(0, 3)
        self.gridLayout.setColumnStretch(1, 7)

        self.pushButton_auto = QPushButton(self)
        self.pushButton_auto.setText("Autofill")
        self.pushButton_auto.setStyleSheet(styles.btn_allegro_ops_auto)
        self.pushButton_auto.setCheckable(True)
        self.pushButton_auto.setChecked(True)
        self.pushButton_auto.clicked.connect(lambda: self.on_auto())
        self.gridLayout.addWidget(self.pushButton_auto, 0, 0, 1, 1)

        self.pushButton_help = QPushButton(self)
        self.pushButton_help.setText("Help")
        self.pushButton_help.setStyleSheet(styles.btn_allegro_ops_auto)
        self.pushButton_help.setCheckable(True)
        self.pushButton_help.setChecked(False)
        self.pushButton_help.clicked.connect(lambda: self.on_help())
        self.gridLayout.addWidget(self.pushButton_help, 1, 0, 1, 1)

        self.spacer_btn_d = QSpacerItem(40, 20, QSizePolicy.Expanding)
        self.gridLayout.addItem(self.spacer_btn_d, 2, 0, 1, 1)

        self.stackedWidget = QStackedWidget(self)
        self.stackedWidget.setStyleSheet(
            """QStackedWidget{background-color: #fff;}""")
        self.gridLayout.addWidget(self.stackedWidget, 0, 1, 3, 1)

        self.widget_auto = QWidget(self.stackedWidget)
        self.widget_auto.setStyleSheet("""QWidget{background-color: #fff;}""")
        self.stackedWidget.addWidget(self.widget_auto)

        self.widget_help = QWidget(self.stackedWidget)
        self.widget_help.setStyleSheet("""QWidget{background-color: #fff;}""")
        self.stackedWidget.addWidget(self.widget_help)

        self.gridLayout_help = QVBoxLayout(self.widget_help)
        self.gridLayout_help.setContentsMargins(50, 50, 50, 50)
        self.gridLayout_help.setSpacing(50)

        self.label_help = QLabel(self.widget_help)
        self.label_help.setStyleSheet(styles.label_lineEdit)
        self.label_help.setWordWrap(True)
        self.label_help.setText(styles.help_text)
        self.gridLayout_help.addWidget(self.label_help)

        self.spacer_help = QSpacerItem(40, 20, QSizePolicy.Expanding)
        self.gridLayout_help.addItem(self.spacer_help)

        self.gridLayout_auto = QGridLayout(self.widget_auto)
        self.gridLayout_auto.setContentsMargins(0, 0, 0, 0)
        self.gridLayout_auto.setSpacing(20)
        self.gridLayout_auto.setColumnStretch(0, 1)
        self.gridLayout_auto.setColumnStretch(1, 1)
        self.gridLayout_auto.setColumnStretch(2, 1)
        self.gridLayout_auto.setColumnStretch(3, 1)
        self.gridLayout_auto.setRowStretch(0, 3)
        self.gridLayout_auto.setRowStretch(1, 1)
        self.gridLayout_auto.setRowStretch(2, 1)
        self.gridLayout_auto.setRowStretch(3, 1)
        self.gridLayout_auto.setRowStretch(4, 1)
        self.gridLayout_auto.setRowStretch(5, 1)
        self.gridLayout_auto.setRowStretch(6, 3)

        self.lineEdit_login = QLineEdit(self.widget_auto)
        self.lineEdit_login.setMinimumSize(QSize(0, 60))
        self.lineEdit_login.setSizeIncrement(QSize(40, 40))
        self.lineEdit_login.setStyleSheet(styles.lineEdit_opt)
        self.gridLayout_auto.addWidget(self.lineEdit_login, 1, 2, 1, 1)
        self.lineEdit_login.setPlaceholderText(
            "login or email of your account")
        self.lineEdit_login.setText(self.auto_login)

        self.lineEdit_password = QLineEdit(self.widget_auto)
        self.lineEdit_password.setMinimumSize(QSize(20, 60))
        self.lineEdit_password.setStyleSheet(styles.lineEdit_opt)
        self.lineEdit_password.setEchoMode(QLineEdit.Password)
        self.lineEdit_password.setReadOnly(False)
        self.gridLayout_auto.addWidget(self.lineEdit_password, 2, 2, 1, 1)
        self.lineEdit_password.setPlaceholderText("password of your account")
        self.lineEdit_password.setText(self.auto_pwd)

        self.lineEdit_email = QLineEdit(self.widget_auto)
        self.lineEdit_email.setMinimumSize(QSize(0, 60))
        self.lineEdit_email.setStyleSheet(styles.lineEdit_opt)
        self.lineEdit_email.setFrame(True)
        self.lineEdit_email.setEchoMode(QLineEdit.Normal)
        self.gridLayout_auto.addWidget(self.lineEdit_email, 3, 2, 1, 1)
        self.lineEdit_email.setPlaceholderText(
            "email to which the notification will be sent")
        self.lineEdit_email.setText(self.auto_email)

        self.lineEdit_time = QLineEdit(self.widget_auto)
        self.lineEdit_time.setMinimumSize(QSize(0, 60))
        self.lineEdit_time.setStyleSheet(styles.lineEdit)
        self.gridLayout_auto.addWidget(self.lineEdit_time, 4, 2, 1, 1)
        self.lineEdit_time.setPlaceholderText("interval between refreshes")
        self.lineEdit_time.setText(str(self.auto_time))

        self.label_login = QLabel("Allegro login", self)
        self.label_login.setStyleSheet(styles.label_lineEdit)
        self.gridLayout_auto.addWidget(self.label_login, 1, 1, 1, 1)

        self.label_password = QLabel("Allegro password", self)
        self.label_password.setStyleSheet(styles.label_lineEdit)
        self.gridLayout_auto.addWidget(self.label_password, 2, 1, 1, 1)

        self.label_email = QLabel("Email to notificate", self)
        self.label_email.setStyleSheet(styles.label_lineEdit)
        self.gridLayout_auto.addWidget(self.label_email, 3, 1, 1, 1)

        self.label_time = QLabel("Refresh time[s]", self)
        self.label_time.setStyleSheet(styles.label_lineEdit)
        self.gridLayout_auto.addWidget(self.label_time, 4, 1, 1, 1)

        self.pushButton_set = QPushButton("Set", self.widget_auto)
        self.pushButton_set.clicked.connect(lambda: self.on_set())
        self.pushButton_set.setMinimumSize(QSize(0, 40))
        self.pushButton_set.setStyleSheet(styles.btn_dark)
        self.gridLayout_auto.addWidget(self.pushButton_set, 5, 2, 1, 1)

        self.spacer_auto_l = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                         QSizePolicy.Minimum)
        self.gridLayout_auto.addItem(self.spacer_auto_l, 1, 1, 1, 1)

        self.spacer_auto_r = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                         QSizePolicy.Minimum)
        self.gridLayout_auto.addItem(self.spacer_auto_r, 1, 3, 1, 1)

        self.spacer_auto_t = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                         QSizePolicy.Minimum)
        self.gridLayout_auto.addItem(self.spacer_auto_t, 0, 0, 1, 1)

        self.spacer_auto_b = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                         QSizePolicy.Minimum)
        self.gridLayout_auto.addItem(self.spacer_auto_b, 6, 0, 1, 1)
Exemplo n.º 23
0
    def getRundown(self, silent=False):
        rtext = ""
        self.rundownCount = 0
        for _condi, _pkdf in self.pk_extracted_by_condi.items():

            _Np = len(_pkdf.index)
            _NROI = len(_pkdf.columns)
            ten_percent = int(_Np / 10)
            rtext += "{} condition, 10% of peaks count is {} peaks\n".format(
                _condi, ten_percent)
            # look at first 5 peaks
            _firsttenpc = _pkdf.iloc[0:ten_percent].describe().loc["mean"]
            # look at last 5 peaks
            _lasttenpc = _pkdf.iloc[-1 - ten_percent:-1].describe().loc["mean"]

            _tdf = self.tracedata[_condi]
            _max = _tdf.max()
            _SD = _tdf.std()

            _bestSNR = _max / _SD
            _startSNR = _firsttenpc / _SD
            _endSNR = _lasttenpc / _SD
            #print ("ff, lf : {} {}".format(_firstfive, _lastfive))

            _rundownRatio = _lasttenpc.div(_firsttenpc).sort_values()
            self.rundownCount += _rundownRatio[
                _rundownRatio < self.rundownThreshold].count()

            _rd_SNR = pd.concat([_rundownRatio, _bestSNR, _startSNR, _endSNR],
                                axis=1)
            _rd_SNR.columns = [
                'Rundown', 'Best SNR', 'Initial SNR', 'Final SNR'
            ]

            rtext += "Rundown (amplitude ratio: last 10% / first 10%) and signal to noise ratio (start, end)\nfor {} ROIs (ROIs with worst rundown first):\n{}\n\n".format(
                _NROI,
                _rd_SNR.round(2).to_string())

        rtext += "Total number of traces with rundown worse than threshold ({}): {}\n".format(
            self.rundownThreshold, self.rundownCount)

        print(rtext)

        if not silent:
            ###Make a pop up window of these results
            qmb = QDialog()
            qmb.setWindowTitle('Rundown {}'.format(self.name))
            qmb.setGeometry(800, 600, 600, 600)
            self.rundownText = QtGui.QTextEdit()
            font = QtGui.QFont()
            font.setFamily('Courier')
            font.setFixedPitch(True)
            font.setPointSize(12)
            self.rundownText.setCurrentFont(font)
            self.rundownText.setText(rtext)
            self.rundownText.setReadOnly(True)

            #add buttons, make it the right size
            qmb.layout = QVBoxLayout()
            qmb.layout.addWidget(self.rundownText)
            qmb.setLayout(qmb.layout)
            qmb.exec_()
Exemplo n.º 24
0
class SaveDialog(QDialog):
    def __init__(self, parent, nodes):
        super(SaveDialog, self).__init__(parent)

        self.all_nodes = nodes
        self.export_nodes = []
        self.nodes_check_box_list = []
        self.export_dir = ''
        self.package_name = ''

        # create UI

        # main layouts and widgets
        self.main_vertical_layout = QVBoxLayout(self)
        self.horizontal_layout = QHBoxLayout(self)
        self.nodes_vertical_layout = QVBoxLayout(self)
        self.nodes_vertical_layout.setAlignment(Qt.AlignTop)
        self.export_widget = QWidget(self)
        self.export_widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Expanding)
        self.export_layout = QVBoxLayout(self)
        self.export_layout.setAlignment(Qt.AlignTop)
        self.export_widget.setLayout(self.export_layout)

        # nodes selection section
        self.nodes_group_box = QGroupBox(self)

        self.nodes_group_box.setLayout(QVBoxLayout(self))
        self.nodes_group_box.setTitle('Select nodes to export')

        self.nodes_scroll_area = QScrollArea(self)
        nodes_list_widget = QWidget()
        nodes_list_widget.setLayout(self.nodes_vertical_layout)

        for i in range(len(nodes)):
            n = nodes[i]
            node_check_box = QCheckBox(n.title)
            node_check_box.setObjectName('node_check_box_' + str(i))
            node_check_box.setChecked(True)
            self.nodes_vertical_layout.addWidget(node_check_box)
            self.nodes_check_box_list.append(node_check_box)

        self.nodes_scroll_area.setWidget(nodes_list_widget)
        self.nodes_group_box.layout().addWidget(self.nodes_scroll_area)

        # export settings section
        self.select_package_dir_button = QPushButton('Select package dir',
                                                     self)
        self.select_package_dir_button.clicked.connect(self.select_package_dir)

        self.package_dir_label = QLabel('package dir: -')

        self.export_button = QPushButton('export', self)
        self.export_button.clicked.connect(self.export)

        self.export_layout.addWidget(self.select_package_dir_button)
        self.export_layout.addWidget(self.package_dir_label)
        self.export_layout.addWidget(self.export_button)

        # button box
        self.button_box = QDialogButtonBox(self)
        self.button_box.setStandardButtons(QDialogButtonBox.Ok)
        self.button_box.button(QDialogButtonBox.Ok).clicked.connect(self.close)

        # merge layouts
        self.horizontal_layout.addWidget(self.nodes_group_box)
        self.horizontal_layout.addWidget(self.export_widget)
        self.main_vertical_layout.addLayout(self.horizontal_layout)
        self.main_vertical_layout.addWidget(self.button_box)

        self.setWindowTitle('Export Nodes')
        self.resize(500, 300)

    def select_package_dir(self):
        self.export_dir = QFileDialog.getExistingDirectory(
            self,
            'Select the package folder where your nodes shall be exported at',
            '../packages')
        self.package_name = os.path.basename(self.export_dir)
        self.package_dir_label.setText('package dir: ' + self.export_dir)

    def update_export_nodes(self):
        self.export_nodes.clear()

        for i in range(len(self.nodes_check_box_list)):
            check_box: QCheckBox = self.nodes_check_box_list[i]
            if check_box.isChecked():
                self.export_nodes.append(self.all_nodes[int(
                    check_box.objectName()[15:])])

    def export(self):
        self.update_export_nodes()

        nodes_dict = {}
        module_name_separator = '___'

        nodes_list = []
        node_titles_count = {}  # title (str) : number (int)
        for i in range(len(self.export_nodes)):
            n: Node = self.export_nodes[i]

            c_w: NodeContentWidget = n.content_widget

            node_number = 0
            title = c_w.get_node_title()
            if title in node_titles_count.values():
                node_number = node_titles_count[title]  # index
                node_titles_count[title] += 1
            else:
                node_titles_count[title] = 1

            node_data = c_w.get_json_data(
                package_name=self.package_name,
                module_name_separator=module_name_separator,
                number=node_number)

            nodes_list.append(node_data)

        nodes_dict['nodes'] = nodes_list

        info_dict = {'type': 'vyScriptFP nodes package'}

        whole_dict = {
            **info_dict,
            **nodes_dict
        }  # merges single two dictionaries to one

        json_data = json.dumps(whole_dict)
        print(json_data)

        # create dirs and save files
        if not os.path.isdir(self.export_dir + '/nodes'):
            os.mkdir(self.export_dir + '/nodes')

        save_file(self.export_dir + '/' + self.package_name + '.rpc',
                  json_data)

        for i in range(len(self.export_nodes)):
            n = self.export_nodes[i]
            module_name = nodes_list[i]['module name']

            # create node folder
            node_dir = self.export_dir + '/nodes/' + module_name
            if not os.path.isdir(node_dir):
                os.mkdir(node_dir)

            # create widgets folder
            widgets_dir = node_dir + '/widgets'
            if not os.path.isdir(widgets_dir):
                os.mkdir(widgets_dir)

            n.content_widget.save_metacode_files(
                node_dir=node_dir,
                widgets_dir=widgets_dir,
                module_name_separator=module_name_separator,
                module_name=module_name)
Exemplo n.º 25
0
class SubtitleTabManager(GlobalSetting):
    activation_signal = Signal(bool)
    tab_clicked_signal = Signal()

    def __init__(self):
        super().__init__()
        self.subtitle_tabs = []
        self.subtitle_tabs_indices = []
        self.current_index_counter = 0
        self.current_tab_index = 0
        self.subtitle_tab_comboBox = SubtitleTabComboBox()
        self.subtitle_tab_delete_button = SubtitleTabDeleteButton()
        self.MainLayout = QVBoxLayout()
        self.subtitle_tab_setting_layout = QHBoxLayout()
        self.setLayout(self.MainLayout)
        self.subtitle_tabs.append(
            SubtitleSelectionSetting(self.current_index_counter))
        self.subtitle_tabs_indices.append(self.current_index_counter)
        self.current_index_counter += 1
        self.current_subtitle_tab = self.subtitle_tabs[-1]
        self.current_subtitle_tab.is_there_old_files_signal.connect(
            self.update_is_there_old_files)
        self.current_subtitle_tab.is_there_old_files_signal.connect(
            self.update_is_subtitle_enabled)
        self.subtitle_tab_setting_layout.addWidget(self.subtitle_tab_comboBox)
        self.subtitle_tab_setting_layout.addWidget(
            self.subtitle_tab_delete_button)
        self.subtitle_tab_setting_layout.addStretch(1)
        self.MainLayout.addLayout(self.subtitle_tab_setting_layout)
        self.MainLayout.addWidget(self.current_subtitle_tab)
        self.subtitle_tab_delete_button.hide()
        self.activation_signal.emit(True)
        self.connect_signals()

    def connect_signals(self):
        self.subtitle_tab_comboBox.current_tab_changed_signal.connect(
            self.change_current_tab)
        self.subtitle_tab_comboBox.create_new_tab_signal.connect(
            self.create_new_tab)
        self.subtitle_tab_delete_button.remove_tab_signal.connect(
            self.delete_current_tab)
        self.tab_clicked_signal.connect(self.tab_clicked)

    def change_current_tab(self, tab_index):
        real_index = self.subtitle_tabs_indices[tab_index]
        self.MainLayout.replaceWidget(self.current_subtitle_tab,
                                      self.subtitle_tabs[tab_index])
        self.current_subtitle_tab.hide()
        self.subtitle_tabs[tab_index].show()
        self.current_subtitle_tab = self.subtitle_tabs[tab_index]
        self.current_tab_index = real_index
        if real_index == 0:
            self.subtitle_tab_delete_button.hide()
        else:
            self.subtitle_tab_delete_button.show()
        self.subtitle_tab_delete_button.set_is_there_old_file(
            len(GlobalSetting.SUBTITLE_FILES_LIST[real_index]) > 0)
        self.current_subtitle_tab.tab_clicked_signal.emit()

    def create_new_tab(self):
        self.subtitle_tabs.append(
            SubtitleSelectionSetting(self.current_index_counter))
        self.subtitle_tabs_indices.append(self.current_index_counter)
        self.current_tab_index = self.current_index_counter
        self.current_index_counter += 1
        self.MainLayout.replaceWidget(self.current_subtitle_tab,
                                      self.subtitle_tabs[-1])
        self.current_subtitle_tab.hide()
        self.subtitle_tabs[-1].show()
        self.current_subtitle_tab = self.subtitle_tabs[-1]
        self.current_subtitle_tab.is_there_old_files_signal.connect(
            self.update_is_there_old_files)
        self.current_subtitle_tab.is_there_old_files_signal.connect(
            self.update_is_subtitle_enabled)
        self.subtitle_tab_delete_button.show()
        self.current_subtitle_tab.tab_clicked_signal.emit()

    def delete_current_tab(self):
        index_to_delete = self.current_tab_index
        index_in_list = self.subtitle_tabs_indices.index(
            self.current_tab_index)
        previous_tab_index = index_in_list - 1
        self.MainLayout.replaceWidget(self.subtitle_tabs[index_in_list],
                                      self.subtitle_tabs[previous_tab_index])
        self.subtitle_tab_comboBox.delete_tab(index_in_list)
        self.subtitle_tabs[index_in_list].hide()
        self.subtitle_tabs[index_in_list].deleteLater()
        self.subtitle_tabs.remove(self.subtitle_tabs[index_in_list])
        self.current_subtitle_tab = self.subtitle_tabs[previous_tab_index]
        self.current_subtitle_tab.show()
        self.subtitle_tabs_indices.remove(index_to_delete)
        GlobalSetting.SUBTITLE_FILES_LIST.pop(index_to_delete, None)
        GlobalSetting.SUBTITLE_FILES_ABSOLUTE_PATH_LIST.pop(
            index_to_delete, None)
        GlobalSetting.SUBTITLE_DELAY.pop(index_to_delete, None)
        GlobalSetting.SUBTITLE_TRACK_NAME.pop(index_to_delete, None)
        GlobalSetting.SUBTITLE_SET_DEFAULT.pop(index_to_delete, None)
        GlobalSetting.SUBTITLE_SET_FORCED.pop(index_to_delete, None)
        GlobalSetting.SUBTITLE_SET_AT_TOP.pop(index_to_delete, None)
        GlobalSetting.SUBTITLE_TAB_ENABLED.pop(index_to_delete, None)
        GlobalSetting.SUBTITLE_LANGUAGE.pop(index_to_delete, None)
        self.current_tab_index = self.subtitle_tabs_indices[previous_tab_index]

    def update_is_there_old_files(self, new_state):
        self.subtitle_tab_delete_button.set_is_there_old_file(new_state)

    def update_is_subtitle_enabled(self):
        for state in GlobalSetting.SUBTITLE_TAB_ENABLED.values():
            if state:
                self.activation_signal.emit(True)
                GlobalSetting.SUBTITLE_ENABLED = True
                return
        GlobalSetting.SUBTITLE_ENABLED = False
        self.activation_signal.emit(False)

    def tab_clicked(self):
        self.current_subtitle_tab.tab_clicked_signal.emit()
        if not GlobalSetting.JOB_QUEUE_EMPTY:
            self.subtitle_tab_delete_button.setEnabled(False)
            self.subtitle_tab_comboBox.hide_new_tab_option()
        else:
            self.subtitle_tab_delete_button.setEnabled(True)
            self.subtitle_tab_comboBox.show_new_tab_option()

    def set_default_directory(self):
        for subtitle_tab in self.subtitle_tabs:
            subtitle_tab.set_default_directory()
Exemplo n.º 26
0
    def _create_reg(self, ind_list, name, width, color):
        # Create a widget to hold the register's bits
        reg_widget = QWidget(self)
        reg_layout = QVBoxLayout(reg_widget)
        reg_widget.setLayout(reg_layout)
        reg_layout.setSpacing(0)
        reg_layout.setMargin(0)

        # Create a widget to hold the register's label and value textbox
        label_value = QWidget(reg_widget)
        lv_layout = QHBoxLayout(label_value)
        label_value.setLayout(lv_layout)
        lv_layout.setSpacing(1)
        lv_layout.setMargin(0)
        reg_layout.addWidget(label_value)

        # Create a label to show the register's name
        reg_label = QLabel(name, label_value)
        reg_label.setAlignment(Qt.AlignCenter)
        font = reg_label.font()
        font.setPointSize(8)
        reg_label.setFont(font)
        lv_layout.addWidget(reg_label)

        # Create a textbox to show the register's value in octal
        n_digits = int((width + 2) / 3)
        if n_digits == 1:
            value_width = 25
        elif n_digits == 2:
            value_width = 30
        else:
            value_width = 45

        reg_value = QLineEdit(label_value)
        reg_value.setReadOnly(True)
        reg_value.setMaximumSize(value_width, 32)
        reg_value.setText(n_digits * '0')
        font = QFont('Monospace')
        font.setStyleHint(QFont.TypeWriter)
        font.setPointSize(10)
        reg_value.setFont(font)
        reg_value.setAlignment(Qt.AlignCenter)
        lv_layout.addWidget(reg_value)

        # Create a frame to hold the register's bits
        bit_frame = QFrame(reg_widget)
        bit_layout = QHBoxLayout(bit_frame)
        bit_layout.setSpacing(1)
        bit_layout.setMargin(0)
        bit_frame.setLayout(bit_layout)
        bit_frame.setFrameStyle(QFrame.StyledPanel | QFrame.Raised)

        # Add indicators for each bit in the register, from MSB to LSB
        for i in range(width, 0, -1):
            ind = Indicator(bit_frame, color)
            ind.setFixedSize(20, 32)
            bit_layout.addWidget(ind)
            ind_list.insert(0, ind)

            # Add separators between each group of 3 bits
            if (i > 1) and ((i % 3) == 1):
                sep = QFrame(bit_frame)
                sep.setFrameStyle(QFrame.VLine | QFrame.Raised)
                bit_layout.addWidget(sep)

        reg_layout.addWidget(bit_frame)

        return reg_widget, reg_value
Exemplo n.º 27
0
    def initGeneratorLayout(self):
        self.generatorPage = QWidget()
        self.generatorLayout = QVBoxLayout()
        self.generatorLayout.setAlignment(Qt.AlignTop)
        self.generatorPage.setLayout(self.generatorLayout)

        self.gameplay = QGroupBox("Gameplay")
        self.gameplayLayout = QGridLayout()
        self.gameplayLayout.setAlignment(Qt.AlignTop)
        self.gameplay.setLayout(self.gameplayLayout)

        self.supercarrier = QCheckBox()
        self.supercarrier.setChecked(self.game.settings.supercarrier)
        self.supercarrier.toggled.connect(self.applySettings)

        self.generate_marks = QCheckBox()
        self.generate_marks.setChecked(self.game.settings.generate_marks)
        self.generate_marks.toggled.connect(self.applySettings)

        self.never_delay_players = QCheckBox()
        self.never_delay_players.setChecked(
            self.game.settings.never_delay_player_flights)
        self.never_delay_players.toggled.connect(self.applySettings)
        self.never_delay_players.setToolTip(
            "When checked, player flights with a delayed start time will be "
            "spawned immediately. AI wingmen may begin startup immediately.")

        self.gameplayLayout.addWidget(QLabel("Use Supercarrier Module"), 0, 0)
        self.gameplayLayout.addWidget(self.supercarrier, 0, 1, Qt.AlignRight)
        self.gameplayLayout.addWidget(QLabel("Put Objective Markers on Map"),
                                      1, 0)
        self.gameplayLayout.addWidget(self.generate_marks, 1, 1, Qt.AlignRight)
        self.gameplayLayout.addWidget(QLabel("Never delay player flights"), 2,
                                      0)
        self.gameplayLayout.addWidget(self.never_delay_players, 2, 1,
                                      Qt.AlignRight)

        self.performance = QGroupBox("Performance")
        self.performanceLayout = QGridLayout()
        self.performanceLayout.setAlignment(Qt.AlignTop)
        self.performance.setLayout(self.performanceLayout)

        self.smoke = QCheckBox()
        self.smoke.setChecked(self.game.settings.perf_smoke_gen)
        self.smoke.toggled.connect(self.applySettings)

        self.red_alert = QCheckBox()
        self.red_alert.setChecked(self.game.settings.perf_red_alert_state)
        self.red_alert.toggled.connect(self.applySettings)

        self.arti = QCheckBox()
        self.arti.setChecked(self.game.settings.perf_artillery)
        self.arti.toggled.connect(self.applySettings)

        self.moving_units = QCheckBox()
        self.moving_units.setChecked(self.game.settings.perf_moving_units)
        self.moving_units.toggled.connect(self.applySettings)

        self.infantry = QCheckBox()
        self.infantry.setChecked(self.game.settings.perf_infantry)
        self.infantry.toggled.connect(self.applySettings)

        self.ai_parking_start = QCheckBox()
        self.ai_parking_start.setChecked(
            self.game.settings.perf_ai_parking_start)
        self.ai_parking_start.toggled.connect(self.applySettings)

        self.destroyed_units = QCheckBox()
        self.destroyed_units.setChecked(
            self.game.settings.perf_destroyed_units)
        self.destroyed_units.toggled.connect(self.applySettings)

        self.culling = QCheckBox()
        self.culling.setChecked(self.game.settings.perf_culling)
        self.culling.toggled.connect(self.applySettings)

        self.culling_distance = QSpinBox()
        self.culling_distance.setMinimum(50)
        self.culling_distance.setMaximum(10000)
        self.culling_distance.setValue(
            self.game.settings.perf_culling_distance)
        self.culling_distance.valueChanged.connect(self.applySettings)

        self.performanceLayout.addWidget(
            QLabel("Smoke visual effect on frontline"), 0, 0)
        self.performanceLayout.addWidget(self.smoke,
                                         0,
                                         1,
                                         alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(
            QLabel("SAM starts in RED alert mode"), 1, 0)
        self.performanceLayout.addWidget(self.red_alert,
                                         1,
                                         1,
                                         alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(QLabel("Artillery strikes"), 2, 0)
        self.performanceLayout.addWidget(self.arti,
                                         2,
                                         1,
                                         alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(QLabel("Moving ground units"), 3, 0)
        self.performanceLayout.addWidget(self.moving_units,
                                         3,
                                         1,
                                         alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(
            QLabel("Generate infantry squads along vehicles"), 4, 0)
        self.performanceLayout.addWidget(self.infantry,
                                         4,
                                         1,
                                         alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(
            QLabel(
                "AI planes parking start (AI starts in flight if disabled)"),
            5, 0)
        self.performanceLayout.addWidget(self.ai_parking_start,
                                         5,
                                         1,
                                         alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(
            QLabel("Include destroyed units carcass"), 6, 0)
        self.performanceLayout.addWidget(self.destroyed_units,
                                         6,
                                         1,
                                         alignment=Qt.AlignRight)

        self.performanceLayout.addWidget(QHorizontalSeparationLine(), 7, 0, 1,
                                         2)
        self.performanceLayout.addWidget(
            QLabel("Culling of distant units enabled"), 8, 0)
        self.performanceLayout.addWidget(self.culling,
                                         8,
                                         1,
                                         alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(QLabel("Culling distance (km)"), 9, 0)
        self.performanceLayout.addWidget(self.culling_distance,
                                         9,
                                         1,
                                         alignment=Qt.AlignRight)

        self.generatorLayout.addWidget(self.gameplay)
        self.generatorLayout.addWidget(
            QLabel(
                "Disabling settings below may improve performance, but will impact the overall quality of the experience."
            ))
        self.generatorLayout.addWidget(self.performance)
Exemplo n.º 28
0
    def _init_widgets(self):

        # the instruction
        instr_lbl = QLabel("Instruction")
        instr_box = QLineEdit("TODO")
        instr_box.setReadOnly(True)

        self._instr_layout = QHBoxLayout()
        self._instr_layout.addWidget(instr_lbl)
        self._instr_layout.addWidget(instr_box)

        # the function
        func_lbl = QLabel("Function")
        func_box = QLineEdit("TODO")
        func_box.setReadOnly(True)

        self._func_layout = QHBoxLayout()
        self._func_layout.addWidget(func_lbl)
        self._func_layout.addWidget(func_box)

        #
        # location
        #
        location_group = QGroupBox("Location")

        self._before_radio = QRadioButton("Before the instruction")
        self._after_radio = QRadioButton("After the instruction")
        location_layout = QVBoxLayout()
        location_layout.addWidget(self._before_radio)
        location_layout.addWidget(self._after_radio)
        location_layout.addStretch(1)

        self._before_radio.setChecked(True)

        location_group.setLayout(location_layout)

        #
        # target atoms
        #

        # function argument
        self._arg_radiobox = QRadioButton("Function argument")
        self._arg_radiobox.clicked.connect(self._on_targetatoms_radiobutton_clicked)
        self._arg_box = QLineEdit("")

        # register
        self._reg_radiobox = QRadioButton("Register")
        self._reg_radiobox.clicked.connect(self._on_targetatoms_radiobutton_clicked)
        self._reg_box = QLineEdit("")

        atom_type_group = QGroupBox("Atom type")
        atom_type_layout = QVBoxLayout()
        atom_type_layout.addWidget(self._arg_radiobox)
        # atom_type_layout.addWidget(self._reg_radiobox)
        atom_type_layout.addStretch(1)
        atom_type_group.setLayout(atom_type_layout)

        atom_layout = QVBoxLayout()
        arg_layout = QHBoxLayout()
        arg_lbl = QLabel("Argument index")
        self._arg_widget = QWidget()
        self._arg_widget.setLayout(arg_layout)
        arg_layout.addWidget(arg_lbl)
        arg_layout.addWidget(self._arg_box)

        reg_layout = QHBoxLayout()
        reg_lbl = QLabel("Register name")
        self._reg_widget = QWidget()
        self._reg_widget.setLayout(reg_layout)
        reg_layout.addWidget(reg_lbl)
        reg_layout.addWidget(self._reg_box)

        atom_layout.addWidget(self._arg_widget)
        atom_layout.addWidget(self._reg_widget)

        self._arg_radiobox.setChecked(True)
        self._reg_widget.setHidden(True)

        #
        # buttons
        #
        ok_btn = QPushButton("OK")
        ok_btn.clicked.connect(self._on_ok_clicked)
        cancel_btn = QPushButton("Cancel")
        cancel_btn.clicked.connect(self._on_cancel_clicked)

        buttons_layout = QHBoxLayout()
        buttons_layout.addWidget(ok_btn)
        buttons_layout.addWidget(cancel_btn)

        layout = QVBoxLayout()
        if self._function is not None:
            func_box.setText(function_prototype_str(self._function))
            layout.addLayout(self._func_layout)
        else:
            layout.addLayout(self._instr_layout)
        layout.addWidget(location_group)
        layout.addWidget(atom_type_group)
        layout.addLayout(atom_layout)
        layout.addLayout(buttons_layout)

        self.setLayout(layout)
Exemplo n.º 29
0
class WdParameterEditBase(QWidget):
    def __init__(self, prop, parent=None):
        super().__init__(parent)
        self.layout = QVBoxLayout()
        self.layout.setSizeConstraint(self.layout.SetFixedSize)
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.layout.setSpacing(0)
        self.setLayout(self.layout)
        self._updating_semaphore = Lock()
        self.property = prop
        self.widgets = []
        self.wdparameter: Optional[Parameter] = None
        self._model_handler = lambda change: self._on_model_changed(change)

    def add_subwidget(self, widget: QWidget):
        self.layout.addWidget(widget)
        self.setSizePolicy(widget.sizePolicy())

    # def minimumSizeHint(self) -> QSize:
    #     size = super().minimumSizeHint()
    #     for w in self.children():
    #         size.expandedTo(w.minimumSizeHint())
    #     return size
    #
    # def sizeHint(self) -> QSize:
    #     size = super().sizeHint()
    #     for w in self.children():
    #         size.expandedTo(w.sizeHint())
    #     return size

    def set_parameter(self, parameter: Parameter):
        try:
            self.wdparameter.unobserve(self._model_handler, self.property)
        except (AttributeError, ValueError):
            pass
        self.wdparameter = parameter
        self.update_from_model()
        self.wdparameter.observe(self._model_handler, self.property)

    def update_from_model(self):
        try:
            self._updating_semaphore.acquire(blocking=False)
            if self.wdparameter is None:
                self.set_view_value('')
            else:
                val = getattr(self.wdparameter, self.property)
                self.set_view_value(val)
        finally:
            self._updating_semaphore.release()

    def _on_model_changed(self, change):
        if not self._updating_semaphore.locked():
            self.update_from_model()

    def set_view_value(self, value):
        raise NotImplementedError

    def set_model_value(self, value):
        try:
            if self._updating_semaphore.acquire(blocking=True):
                setattr(self.wdparameter, self.property, value)
        finally:
            self._updating_semaphore.release()
Exemplo n.º 30
0
    def __init__(self):
        super().__init__()
        self.label = QLabel('Which city do you live in?')
        self.rbtn1 = QRadioButton('New York')
        self.rbtn2 = QRadioButton('Houston')
        self.label2 = QLabel("")

        self.label3 = QLabel('Which state do you live in?')
        self.rbtn3 = QRadioButton('New York')
        self.rbtn4 = QRadioButton('Texas')
        self.label4 = QLabel("")

        self.btngroup1 = QButtonGroup()
        self.btngroup2 = QButtonGroup()

        self.btngroup1.addButton(self.rbtn1)
        self.btngroup1.addButton(self.rbtn2)
        self.btngroup2.addButton(self.rbtn3)
        self.btngroup2.addButton(self.rbtn4)

        self.rbtn1.toggled.connect(self.onClicked)
        self.rbtn2.toggled.connect(self.onClicked)

        self.rbtn3.toggled.connect(self.onClickedState)
        self.rbtn4.toggled.connect(self.onClickedState)

        layout = QVBoxLayout()
        layout.addWidget(self.label)
        layout.addWidget(self.rbtn1)
        layout.addWidget(self.rbtn2)
        layout.addWidget(self.label2)

        layout.addWidget(self.label3)
        layout.addWidget(self.rbtn3)
        layout.addWidget(self.rbtn4)
        layout.addWidget(self.label4)

        self.setGeometry(200, 200, 300, 150)

        self.setLayout(layout)
        self.setWindowTitle('Radio Button Example')

        self.show()
Exemplo n.º 31
0
    def _init_widgets(self):

        # status
        status_box = QGroupBox(self)
        status_box.setTitle("Status")

        self._status_label = QLabel(self)
        self._status_label.setText(self.workspace.instance.sync.status_string)

        status_layout = QVBoxLayout()
        status_layout.addWidget(self._status_label)

        status_box.setLayout(status_layout)

        # table

        self._team_table = QTeamTable(self.workspace.instance)
        team_box = QGroupBox(self)
        team_box.setTitle("Team")

        # operations

        # pull function button
        pullfunc_btn = QPushButton(self)
        pullfunc_btn.setText("Pull func")
        pullfunc_btn.setToolTip("Pull current function from the selected user")
        pullfunc_btn.clicked.connect(self._on_pullfunc_clicked)

        # push function button
        pushfunc_btn = QPushButton()
        pushfunc_btn.setText('Push func')
        pushfunc_btn.setToolTip("Push current function to the repo")
        pushfunc_btn.clicked.connect(self._on_pushfunc_clicked)

        # pull patches button
        pullpatches_btn = QPushButton(self)
        pullpatches_btn.setText("Pull patches")
        pullpatches_btn.setToolTip("Pull all patches from the selected user")
        pullpatches_btn.clicked.connect(self._on_pullpatches_clicked)

        actions_box = QGroupBox(self)
        actions_box.setTitle("Actions")
        actions_layout = QHBoxLayout()
        actions_layout.addWidget(pullfunc_btn)
        actions_layout.addWidget(pushfunc_btn)
        actions_layout.addWidget(pullpatches_btn)
        actions_box.setLayout(actions_layout)

        team_layout = QVBoxLayout()
        team_layout.addWidget(self._team_table)
        team_layout.addWidget(actions_box)
        team_box.setLayout(team_layout)

        main_layout = QVBoxLayout()
        main_layout.addWidget(status_box)
        main_layout.addWidget(team_box)

        self.setLayout(main_layout)
Exemplo n.º 32
0
    def __init__(self):
        super().__init__()

        self.mainLayout = QVBoxLayout()

        self.dataLayout = QHBoxLayout()
        self.generatorLabel = QLabel("Generator")
        self.mLabel = QLabel("\u03BC")
        self.mLine = QLineEdit("10")
        self.sigmaLabel = QLabel("\u03C3")
        self.sigmaLine = QLineEdit("1")
        self.genBox = QFormLayout()
        self.genBox.addWidget(self.generatorLabel)
        self.genBox.addRow(self.mLabel, self.mLine)
        self.genBox.addRow(self.sigmaLabel, self.sigmaLine)

        self.processorLabel = QLabel("Processor")
        self.aLabel = QLabel("a")
        self.aLine = QLineEdit("5")
        self.bLabel = QLabel("b")
        self.bLine = QLineEdit("15")
        self.procBox = QFormLayout()
        self.procBox.addWidget(self.processorLabel)
        self.procBox.addRow(self.aLabel, self.aLine)
        self.procBox.addRow(self.bLabel, self.bLine)

        self.genBox.setSpacing(10)
        self.procBox.setSpacing(10)
        self.dataLayout.addLayout(self.genBox)
        self.dataLayout.addLayout(self.procBox)
        self.dataLayout.setSpacing(30)

        self.hLayout = QHBoxLayout()

        self.numLayout = QFormLayout()
        self.numLabel = QLabel("Number of requests")
        self.numLine = QLineEdit("10000")
        self.numLayout.addWidget(self.numLabel)
        self.numLayout.addWidget(self.numLine)

        self.deltLayout = QFormLayout()
        self.deltLabel = QLabel("\u0394t")
        self.deltLine = QLineEdit("1")
        self.deltLayout.addWidget(self.deltLabel)
        self.deltLayout.addWidget(self.deltLine)

        self.probLayout = QFormLayout()
        self.probLabel = QLabel("Probability of returning")
        self.probLine = QLineEdit("0")
        self.probLayout.addWidget(self.probLabel)
        self.probLayout.addWidget(self.probLine)


        self.numLayout.setSpacing(10)
        self.deltLayout.setSpacing(10)
        self.probLayout.setSpacing(10)

        self.hLayout.addLayout(self.numLayout)
        self.hLayout.addLayout(self.deltLayout)
        self.hLayout.addLayout(self.probLayout)
        self.hLayout.setSpacing(30)

        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)

        line1 = QFrame()
        line1.setFrameShape(QFrame.HLine)
        line1.setFrameShadow(QFrame.Sunken)

        self.answerLabel = QLabel("Optimal length of queue")
        self.dtLabel = QLabel("\u0394t")
        self.dtLine = QLabel()
        self.dtLine.setFrameShape(QFrame.WinPanel)
        self.dtLine.setFrameShadow(QFrame.Raised)
        self.eventLabel = QLabel("Events")
        self.eventLine = QLabel()
        self.eventLine.setFrameShape(QFrame.WinPanel)
        self.eventLine.setFrameShadow(QFrame.Raised)
        self.answerBox = QFormLayout()
        self.answerBox.addWidget(self.answerLabel)
        self.answerBox.addRow(self.dtLabel, self.dtLine)
        self.answerBox.addRow(self.eventLabel, self.eventLine)

        self.button = QPushButton("Calculate")
        self.button.clicked.connect(self.calculate)
        self.button.setMinimumSize(100,65)
        self.button.setMaximumSize(200, 65)
        self.buttonLayout = QVBoxLayout()
        self.buttonLayout.addWidget(self.button)
        self.buttonLayout.setAlignment(Qt.AlignBottom)

        self.answLayout = QHBoxLayout()
        self.answLayout.addLayout(self.answerBox)
        self.answLayout.addLayout(self.buttonLayout)
        #self.answLayout.setAlignment(Qt.AlignBottom)

        self.mainLayout.addLayout(self.dataLayout)
        self.mainLayout.addWidget(line)
        self.mainLayout.addLayout(self.hLayout)
        self.mainLayout.addWidget(line1)
        self.mainLayout.addLayout(self.answLayout)

        self.mainLayout.setAlignment(Qt.AlignVCenter)
        self.mainLayout.setSpacing(20)
        self.setLayout(self.mainLayout)
Exemplo n.º 33
0
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(484, 433)
        self.centralWidget = QWidget(MainWindow)
        sizePolicy = QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.centralWidget.sizePolicy().hasHeightForWidth())
        self.centralWidget.setSizePolicy(sizePolicy)
        self.centralWidget.setObjectName("centralWidget")
        self.verticalLayout_2 = QVBoxLayout(self.centralWidget)
        self.verticalLayout_2.setContentsMargins(11, 11, 11, 11)
        self.verticalLayout_2.setSpacing(6)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.verticalLayout = QVBoxLayout()
        self.verticalLayout.setSpacing(6)
        self.verticalLayout.setObjectName("verticalLayout")
        self.lcdNumber = QLCDNumber(self.centralWidget)
        self.lcdNumber.setDigitCount(10)
        self.lcdNumber.setObjectName("lcdNumber")
        self.verticalLayout.addWidget(self.lcdNumber)
        self.gridLayout = QGridLayout()
        self.gridLayout.setSpacing(6)
        self.gridLayout.setObjectName("gridLayout")
        self.pushButton_n4 = QPushButton(self.centralWidget)
        self.pushButton_n4.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_n4.setFont(font)
        self.pushButton_n4.setStyleSheet("QPushButton {\n"
"color: #1976D2;\n"
"}")
        self.pushButton_n4.setObjectName("pushButton_n4")
        self.gridLayout.addWidget(self.pushButton_n4, 3, 0, 1, 1)
        self.pushButton_n1 = QPushButton(self.centralWidget)
        self.pushButton_n1.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_n1.setFont(font)
        self.pushButton_n1.setStyleSheet("QPushButton {\n"
"color: #1976D2;\n"
"}")
        self.pushButton_n1.setObjectName("pushButton_n1")
        self.gridLayout.addWidget(self.pushButton_n1, 4, 0, 1, 1)
        self.pushButton_n8 = QPushButton(self.centralWidget)
        self.pushButton_n8.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_n8.setFont(font)
        self.pushButton_n8.setStyleSheet("QPushButton {\n"
"color: #1976D2;\n"
"}")
        self.pushButton_n8.setObjectName("pushButton_n8")
        self.gridLayout.addWidget(self.pushButton_n8, 2, 1, 1, 1)
        self.pushButton_mul = QPushButton(self.centralWidget)
        self.pushButton_mul.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(False)
        font.setWeight(50)
        self.pushButton_mul.setFont(font)
        self.pushButton_mul.setObjectName("pushButton_mul")
        self.gridLayout.addWidget(self.pushButton_mul, 2, 3, 1, 1)
        self.pushButton_n7 = QPushButton(self.centralWidget)
        self.pushButton_n7.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_n7.setFont(font)
        self.pushButton_n7.setStyleSheet("QPushButton {\n"
"color: #1976D2;\n"
"}")
        self.pushButton_n7.setObjectName("pushButton_n7")
        self.gridLayout.addWidget(self.pushButton_n7, 2, 0, 1, 1)
        self.pushButton_n6 = QPushButton(self.centralWidget)
        self.pushButton_n6.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_n6.setFont(font)
        self.pushButton_n6.setStyleSheet("QPushButton {\n"
"color: #1976D2;\n"
"}")
        self.pushButton_n6.setObjectName("pushButton_n6")
        self.gridLayout.addWidget(self.pushButton_n6, 3, 2, 1, 1)
        self.pushButton_n5 = QPushButton(self.centralWidget)
        self.pushButton_n5.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_n5.setFont(font)
        self.pushButton_n5.setStyleSheet("QPushButton {\n"
"color: #1976D2;\n"
"}")
        self.pushButton_n5.setObjectName("pushButton_n5")
        self.gridLayout.addWidget(self.pushButton_n5, 3, 1, 1, 1)
        self.pushButton_n0 = QPushButton(self.centralWidget)
        self.pushButton_n0.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_n0.setFont(font)
        self.pushButton_n0.setStyleSheet("QPushButton {\n"
"color: #1976D2;\n"
"}")
        self.pushButton_n0.setObjectName("pushButton_n0")
        self.gridLayout.addWidget(self.pushButton_n0, 5, 0, 1, 1)
        self.pushButton_n2 = QPushButton(self.centralWidget)
        self.pushButton_n2.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_n2.setFont(font)
        self.pushButton_n2.setStyleSheet("QPushButton {\n"
"color: #1976D2;\n"
"}")
        self.pushButton_n2.setObjectName("pushButton_n2")
        self.gridLayout.addWidget(self.pushButton_n2, 4, 1, 1, 1)
        self.pushButton_n9 = QPushButton(self.centralWidget)
        self.pushButton_n9.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_n9.setFont(font)
        self.pushButton_n9.setStyleSheet("QPushButton {\n"
"color: #1976D2;\n"
"}")
        self.pushButton_n9.setObjectName("pushButton_n9")
        self.gridLayout.addWidget(self.pushButton_n9, 2, 2, 1, 1)
        self.pushButton_n3 = QPushButton(self.centralWidget)
        self.pushButton_n3.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_n3.setFont(font)
        self.pushButton_n3.setStyleSheet("QPushButton {\n"
"color: #1976D2;\n"
"}")
        self.pushButton_n3.setObjectName("pushButton_n3")
        self.gridLayout.addWidget(self.pushButton_n3, 4, 2, 1, 1)
        self.pushButton_div = QPushButton(self.centralWidget)
        self.pushButton_div.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(False)
        font.setWeight(50)
        self.pushButton_div.setFont(font)
        self.pushButton_div.setObjectName("pushButton_div")
        self.gridLayout.addWidget(self.pushButton_div, 1, 3, 1, 1)
        self.pushButton_sub = QPushButton(self.centralWidget)
        self.pushButton_sub.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(False)
        font.setWeight(50)
        self.pushButton_sub.setFont(font)
        self.pushButton_sub.setObjectName("pushButton_sub")
        self.gridLayout.addWidget(self.pushButton_sub, 3, 3, 1, 1)
        self.pushButton_add = QPushButton(self.centralWidget)
        self.pushButton_add.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(False)
        font.setWeight(50)
        self.pushButton_add.setFont(font)
        self.pushButton_add.setObjectName("pushButton_add")
        self.gridLayout.addWidget(self.pushButton_add, 4, 3, 1, 1)
        self.pushButton_ac = QPushButton(self.centralWidget)
        self.pushButton_ac.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(False)
        font.setWeight(50)
        self.pushButton_ac.setFont(font)
        self.pushButton_ac.setStyleSheet("QPushButton {\n"
"    color: #f44336;\n"
"}")
        self.pushButton_ac.setObjectName("pushButton_ac")
        self.gridLayout.addWidget(self.pushButton_ac, 1, 0, 1, 1)
        self.pushButton_mr = QPushButton(self.centralWidget)
        self.pushButton_mr.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(False)
        font.setWeight(50)
        self.pushButton_mr.setFont(font)
        self.pushButton_mr.setStyleSheet("QPushButton {\n"
"   color: #FFC107;\n"
"}")
        self.pushButton_mr.setObjectName("pushButton_mr")
        self.gridLayout.addWidget(self.pushButton_mr, 1, 2, 1, 1)
        self.pushButton_m = QPushButton(self.centralWidget)
        self.pushButton_m.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(False)
        font.setWeight(50)
        self.pushButton_m.setFont(font)
        self.pushButton_m.setStyleSheet("QPushButton {\n"
"   color: #FFC107;\n"
"}")
        self.pushButton_m.setObjectName("pushButton_m")
        self.gridLayout.addWidget(self.pushButton_m, 1, 1, 1, 1)
        self.pushButton_pc = QPushButton(self.centralWidget)
        self.pushButton_pc.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(False)
        font.setWeight(50)
        self.pushButton_pc.setFont(font)
        self.pushButton_pc.setObjectName("pushButton_pc")
        self.gridLayout.addWidget(self.pushButton_pc, 5, 1, 1, 1)
        self.pushButton_eq = QPushButton(self.centralWidget)
        self.pushButton_eq.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_eq.setFont(font)
        self.pushButton_eq.setStyleSheet("QPushButton {\n"
"color: #4CAF50;\n"
"}")
        self.pushButton_eq.setObjectName("pushButton_eq")
        self.gridLayout.addWidget(self.pushButton_eq, 5, 2, 1, 2)
        self.verticalLayout.addLayout(self.gridLayout)
        self.verticalLayout_2.addLayout(self.verticalLayout)
        MainWindow.setCentralWidget(self.centralWidget)
        self.menuBar = QMenuBar(MainWindow)
        self.menuBar.setGeometry(QRect(0, 0, 484, 22))
        self.menuBar.setObjectName("menuBar")
        self.menuFile = QMenu(self.menuBar)
        self.menuFile.setObjectName("menuFile")
        MainWindow.setMenuBar(self.menuBar)
        self.statusBar = QStatusBar(MainWindow)
        self.statusBar.setObjectName("statusBar")
        MainWindow.setStatusBar(self.statusBar)
        self.actionExit = QAction(MainWindow)
        self.actionExit.setObjectName("actionExit")
        self.actionReset = QAction(MainWindow)
        self.actionReset.setObjectName("actionReset")
        self.menuFile.addAction(self.actionReset)
        self.menuFile.addAction(self.actionExit)
        self.menuBar.addAction(self.menuFile.menuAction())

        self.retranslateUi(MainWindow)
        QMetaObject.connectSlotsByName(MainWindow)
Exemplo n.º 34
0
    def makeDialog(self):
        """Create the controls for the dialog"""

        self.setWindowTitle("Extract peaks according to reference pattern")
        layout = QGridLayout()
        w = QWidget()
        w.setLayout(layout)

        self.resize(500, 400)
        vbox = QVBoxLayout()
        vbox.addWidget(w)
        self.setLayout(vbox)

        self.N_ROI_label = QLabel('Extracting peaks')

        #will be altered as soon as data loads
        self.skipRB = QCheckBox('Skip ROIs with SNR less than')
        self.skipRB.setChecked(False)
        self.skipRB.setLayoutDirection(QtCore.Qt.LeftToRight)
        self.skipRB.stateChanged.connect(self.maskLowSNR)

        self.skipSB = pg.SpinBox(value=3, step=.2, bounds=[1, 10], delay=0)
        self.skipSB.setFixedSize(60, 25)
        self.skipSB.valueChanged.connect(self.maskLowSNR)

        psr_label = QLabel('Search range around peak (data points)')
        self.psrSB = pg.SpinBox(value=3,
                                step=2,
                                bounds=[1, 7],
                                delay=0,
                                int=True)
        self.psrSB.setFixedSize(60, 25)

        #will be altered as soon as data loads
        self.noiseRB = QCheckBox('Treat peaks as failures when < SD x')
        self.noiseRB.setChecked(False)
        self.noiseRB.setLayoutDirection(QtCore.Qt.LeftToRight)
        self.noiseRB.stateChanged.connect(self.setFailures)
        self.noiseRB.setDisabled(True)

        self.noiseSB = pg.SpinBox(value=1.5, step=.1, bounds=[.2, 10], delay=0)
        self.noiseSB.setFixedSize(60, 25)
        self.noiseSB.valueChanged.connect(self.setFailures)
        self.noiseSB.setDisabled(True)

        self.peaksLabel = QLabel('No peaks set to be failures.')

        _doScrapeBtn = QPushButton('Extract responses')
        _doScrapeBtn.clicked.connect(self.scrapePeaks)

        self.getRundownBtn = QPushButton('Calculate rundown')
        self.getRundownBtn.clicked.connect(self.getRundown)
        self.getRundownBtn.setDisabled(True)

        _cancelBtn = QPushButton('Cancel')
        _cancelBtn.clicked.connect(self.reject)

        self.acceptBtn = QPushButton('Accept and Return')
        self.acceptBtn.clicked.connect(self.prepareAccept)
        self.acceptBtn.setDisabled(True)

        layout.addWidget(self.N_ROI_label, 0, 0, 1, 2)

        layout.addWidget(self.skipRB, 1, 0, 1, 3)
        layout.addWidget(self.skipSB, 1, 2, 1, 1)

        layout.addWidget(psr_label, 2, 0, 1, 2)
        layout.addWidget(self.psrSB, row=2, col=2)

        layout.addWidget(self.noiseRB, 3, 0, 1, 3)
        layout.addWidget(self.noiseSB, 3, 2, 1, 1)
        layout.addWidget(self.peaksLabel, 4, 0, 1, -1)

        layout.addWidget(_doScrapeBtn, 5, 0)
        layout.addWidget(self.getRundownBtn, 5, 1)
        layout.addWidget(_cancelBtn, 6, 1)
        layout.addWidget(self.acceptBtn, 6, 2)

        self.setLayout(layout)
Exemplo n.º 35
0
 def _init_widgets(self):
     self.main = SourceCodeViewerTabWidget()
     self.main.viewer = self
     main_layout = QVBoxLayout()
     main_layout.addWidget(self.main)
     self.setLayout(main_layout)
Exemplo n.º 36
0
    def __init__(self, parent, nodes):
        super(SaveDialog, self).__init__(parent)

        self.all_nodes = nodes
        self.export_nodes = []
        self.nodes_check_box_list = []
        self.export_dir = ''
        self.package_name = ''

        # create UI

        # main layouts and widgets
        self.main_vertical_layout = QVBoxLayout(self)
        self.horizontal_layout = QHBoxLayout(self)
        self.nodes_vertical_layout = QVBoxLayout(self)
        self.nodes_vertical_layout.setAlignment(Qt.AlignTop)
        self.export_widget = QWidget(self)
        self.export_widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Expanding)
        self.export_layout = QVBoxLayout(self)
        self.export_layout.setAlignment(Qt.AlignTop)
        self.export_widget.setLayout(self.export_layout)

        # nodes selection section
        self.nodes_group_box = QGroupBox(self)

        self.nodes_group_box.setLayout(QVBoxLayout(self))
        self.nodes_group_box.setTitle('Select nodes to export')

        self.nodes_scroll_area = QScrollArea(self)
        nodes_list_widget = QWidget()
        nodes_list_widget.setLayout(self.nodes_vertical_layout)

        for i in range(len(nodes)):
            n = nodes[i]
            node_check_box = QCheckBox(n.title)
            node_check_box.setObjectName('node_check_box_' + str(i))
            node_check_box.setChecked(True)
            self.nodes_vertical_layout.addWidget(node_check_box)
            self.nodes_check_box_list.append(node_check_box)

        self.nodes_scroll_area.setWidget(nodes_list_widget)
        self.nodes_group_box.layout().addWidget(self.nodes_scroll_area)

        # export settings section
        self.select_package_dir_button = QPushButton('Select package dir',
                                                     self)
        self.select_package_dir_button.clicked.connect(self.select_package_dir)

        self.package_dir_label = QLabel('package dir: -')

        self.export_button = QPushButton('export', self)
        self.export_button.clicked.connect(self.export)

        self.export_layout.addWidget(self.select_package_dir_button)
        self.export_layout.addWidget(self.package_dir_label)
        self.export_layout.addWidget(self.export_button)

        # button box
        self.button_box = QDialogButtonBox(self)
        self.button_box.setStandardButtons(QDialogButtonBox.Ok)
        self.button_box.button(QDialogButtonBox.Ok).clicked.connect(self.close)

        # merge layouts
        self.horizontal_layout.addWidget(self.nodes_group_box)
        self.horizontal_layout.addWidget(self.export_widget)
        self.main_vertical_layout.addLayout(self.horizontal_layout)
        self.main_vertical_layout.addWidget(self.button_box)

        self.setWindowTitle('Export Nodes')
        self.resize(500, 300)
Exemplo n.º 37
0
    def _init_widgets(self):
        self._linear_viewer = QLinearDisassembly(self.workspace,
                                                 self,
                                                 parent=self)
        self._flow_graph = QDisassemblyGraph(self.workspace, self, parent=self)
        self._feature_map = QFeatureMap(self, parent=self)
        self._statusbar = QDisasmStatusBar(self, parent=self)

        vlayout = QVBoxLayout()
        vlayout.addWidget(self._feature_map)
        vlayout.addWidget(self._flow_graph)
        vlayout.addWidget(self._linear_viewer)
        vlayout.addWidget(self._statusbar)
        vlayout.setContentsMargins(0, 0, 0, 0)

        self._feature_map.setMaximumHeight(25)
        vlayout.setStretchFactor(self._feature_map, 0)
        vlayout.setStretchFactor(self._flow_graph, 1)
        vlayout.setStretchFactor(self._linear_viewer, 1)
        vlayout.setStretchFactor(self._statusbar, 0)

        hlayout = QHBoxLayout()
        hlayout.addLayout(vlayout)

        self.setLayout(hlayout)

        self.display_disasm_graph()
        # self.display_linear_viewer()

        self.workspace.plugins.instrument_disassembly_view(self)
Exemplo n.º 38
0
    def __init__(self, parent=None):
        super().__init__(parent)

        self.setWindowTitle(self.tr("Edit Word set"))
        self.setWindowIcon(QIcon(cm.DIR_ICONS + "app.png"))

        box = QVBoxLayout()
        self.add_button = QPushButton(self.tr("Add"))
        self.add_file_button = QPushButton(self.tr("Add from file..."))
        self.del_button = QPushButton(self.tr("Remove"))
        self.del_button.setDisabled(True)

        self.save_button = QPushButton(self.tr("Save"))
        self.save_button.setDisabled(True)
        self.cancel_button = QPushButton(self.tr("Cancel"))

        box.addWidget(self.add_button)
        box.addWidget(self.del_button)
        box.addWidget(self.add_file_button)
        box.addStretch()
        box.addWidget(self.save_button)
        box.addWidget(self.cancel_button)

        self.view = QListView()
        self.model = QStringListModel()
        self.view.setModel(self.model)
        self.view.setSelectionMode(QAbstractItemView.ExtendedSelection)

        hlayout = QHBoxLayout()
        hlayout.addWidget(self.view)
        hlayout.addLayout(box)

        self.setLayout(hlayout)

        self.add_button.pressed.connect(self.on_add)
        self.del_button.pressed.connect(self.on_remove)
        self.add_file_button.pressed.connect(self.on_load_file)

        self.cancel_button.pressed.connect(self.reject)
        self.save_button.pressed.connect(self.accept)
        # Item selected in view
        self.view.selectionModel().selectionChanged.connect(
            self.on_item_selected)
        # Data changed in model
        self.model.dataChanged.connect(self.on_data_changed)
        self.model.rowsInserted.connect(self.on_data_changed)
        self.model.rowsRemoved.connect(self.on_data_changed)
Exemplo n.º 39
0
class OptionsDock(QDockWidget):
    def __init__(self, model, FM, parent=None):
        super(OptionsDock, self).__init__(parent)

        self.model = model
        self.FM = FM
        self.mw = parent

        self.setSizePolicy(QSizePolicy.Fixed,
                           QSizePolicy.Expanding)  # Doesn't work?
        self.setAllowedAreas(QtCore.Qt.LeftDockWidgetArea
                             | QtCore.Qt.RightDockWidgetArea)

        # Create Controls
        self.createOriginBox()
        self.createOptionsBox()
        self.createResolutionBox()

        # Create submit button
        self.applyButton = QPushButton("Apply Changes")
        self.applyButton.setMinimumHeight(self.FM.height() *
                                          1.6)  # Mac bug fix
        self.applyButton.clicked.connect(self.mw.applyChanges)

        # Create Zoom box
        self.zoomBox = QSpinBox()
        self.zoomBox.setSuffix(' %')
        self.zoomBox.setRange(25, 2000)
        self.zoomBox.setValue(100)
        self.zoomBox.setSingleStep(25)
        self.zoomBox.valueChanged.connect(self.mw.editZoom)
        self.zoomLayout = QHBoxLayout()
        self.zoomLayout.addWidget(QLabel('Zoom:'))
        self.zoomLayout.addWidget(self.zoomBox)
        self.zoomLayout.setContentsMargins(0, 0, 0, 0)
        self.zoomWidget = QWidget()
        self.zoomWidget.setLayout(self.zoomLayout)

        # Create Layout
        self.dockLayout = QVBoxLayout()
        self.dockLayout.addWidget(self.originGroupBox)
        self.dockLayout.addWidget(self.optionsGroupBox)
        self.dockLayout.addWidget(self.resGroupBox)
        self.dockLayout.addWidget(self.applyButton)
        self.dockLayout.addStretch()
        self.dockLayout.addWidget(HorizontalLine())
        self.dockLayout.addWidget(self.zoomWidget)

        self.optionsWidget = QWidget()
        self.optionsWidget.setLayout(self.dockLayout)
        self.setWidget(self.optionsWidget)

    def createOriginBox(self):

        # X Origin
        self.xOrBox = QDoubleSpinBox()
        self.xOrBox.setDecimals(9)
        self.xOrBox.setRange(-99999, 99999)
        self.xOrBox.valueChanged.connect(
            lambda value: self.mw.editSingleOrigin(value, 0))

        # Y Origin
        self.yOrBox = QDoubleSpinBox()
        self.yOrBox.setDecimals(9)
        self.yOrBox.setRange(-99999, 99999)
        self.yOrBox.valueChanged.connect(
            lambda value: self.mw.editSingleOrigin(value, 1))

        # Z Origin
        self.zOrBox = QDoubleSpinBox()
        self.zOrBox.setDecimals(9)
        self.zOrBox.setRange(-99999, 99999)
        self.zOrBox.valueChanged.connect(
            lambda value: self.mw.editSingleOrigin(value, 2))

        # Origin Form Layout
        self.orLayout = QFormLayout()
        self.orLayout.addRow('X:', self.xOrBox)
        self.orLayout.addRow('Y:', self.yOrBox)
        self.orLayout.addRow('Z:', self.zOrBox)
        #self.orLayout.setVerticalSpacing(4)
        self.orLayout.setLabelAlignment(QtCore.Qt.AlignLeft)
        self.orLayout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)

        # Origin Group Box
        self.originGroupBox = QGroupBox('Origin')
        self.originGroupBox.setLayout(self.orLayout)

    def createOptionsBox(self):

        # Width
        self.widthBox = QDoubleSpinBox(self)
        self.widthBox.setRange(.1, 99999)
        self.widthBox.valueChanged.connect(self.mw.editWidth)

        # Height
        self.heightBox = QDoubleSpinBox(self)
        self.heightBox.setRange(.1, 99999)
        self.heightBox.valueChanged.connect(self.mw.editHeight)

        # ColorBy
        self.colorbyBox = QComboBox(self)
        self.colorbyBox.addItem("material")
        self.colorbyBox.addItem("cell")
        self.colorbyBox.currentTextChanged[str].connect(self.mw.editColorBy)

        # Basis
        self.basisBox = QComboBox(self)
        self.basisBox.addItem("xy")
        self.basisBox.addItem("xz")
        self.basisBox.addItem("yz")
        self.basisBox.currentTextChanged.connect(self.mw.editBasis)

        # Advanced Color Options
        self.colorOptionsButton = QPushButton('Color Options...')
        self.colorOptionsButton.setMinimumHeight(self.FM.height() * 1.6)
        self.colorOptionsButton.clicked.connect(self.mw.showColorDialog)

        # Options Form Layout
        self.opLayout = QFormLayout()
        self.opLayout.addRow('Width:', self.widthBox)
        self.opLayout.addRow('Height:', self.heightBox)
        self.opLayout.addRow('Basis:', self.basisBox)
        self.opLayout.addRow('Color By:', self.colorbyBox)
        self.opLayout.addRow(self.colorOptionsButton)
        self.opLayout.setLabelAlignment(QtCore.Qt.AlignLeft)
        self.opLayout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)

        # Options Group Box
        self.optionsGroupBox = QGroupBox('Options')
        self.optionsGroupBox.setLayout(self.opLayout)

    def createResolutionBox(self):

        # Horizontal Resolution
        self.hResBox = QSpinBox(self)
        self.hResBox.setRange(1, 99999)
        self.hResBox.setSingleStep(25)
        self.hResBox.setSuffix(' px')
        self.hResBox.valueChanged.connect(self.mw.editHRes)

        # Vertical Resolution
        self.vResLabel = QLabel('Pixel Height:')
        self.vResBox = QSpinBox(self)
        self.vResBox.setRange(1, 99999)
        self.vResBox.setSingleStep(25)
        self.vResBox.setSuffix(' px')
        self.vResBox.valueChanged.connect(self.mw.editVRes)

        # Ratio checkbox
        self.ratioCheck = QCheckBox("Fixed Aspect Ratio", self)
        self.ratioCheck.stateChanged.connect(self.mw.toggleAspectLock)

        # Resolution Form Layout
        self.resLayout = QFormLayout()
        self.resLayout.addRow(self.ratioCheck)
        self.resLayout.addRow('Pixel Width:', self.hResBox)
        self.resLayout.addRow(self.vResLabel, self.vResBox)
        self.resLayout.setLabelAlignment(QtCore.Qt.AlignLeft)
        self.resLayout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)

        # Resolution Group Box
        self.resGroupBox = QGroupBox("Resolution")
        self.resGroupBox.setLayout(self.resLayout)

    def updateDock(self):
        self.updateOrigin()
        self.updateWidth()
        self.updateHeight()
        self.updateColorBy()
        self.updateBasis()
        self.updateAspectLock()
        self.updateHRes()
        self.updateVRes()

    def updateOrigin(self):
        self.xOrBox.setValue(self.model.activeView.origin[0])
        self.yOrBox.setValue(self.model.activeView.origin[1])
        self.zOrBox.setValue(self.model.activeView.origin[2])

    def updateWidth(self):
        self.widthBox.setValue(self.model.activeView.width)

    def updateHeight(self):
        self.heightBox.setValue(self.model.activeView.height)

    def updateColorBy(self):
        self.colorbyBox.setCurrentText(self.model.activeView.colorby)

    def updateBasis(self):
        self.basisBox.setCurrentText(self.model.activeView.basis)

    def updateAspectLock(self):
        if self.model.activeView.aspectLock:
            self.ratioCheck.setChecked(True)
            self.vResBox.setDisabled(True)
            self.vResLabel.setDisabled(True)
        else:
            self.ratioCheck.setChecked(False)
            self.vResBox.setDisabled(False)
            self.vResLabel.setDisabled(False)

    def updateHRes(self):
        self.hResBox.setValue(self.model.activeView.hRes)

    def updateVRes(self):
        self.vResBox.setValue(self.model.activeView.vRes)

    def revertToCurrent(self):
        cv = self.model.currentView

        self.xOrBox.setValue(cv.origin[0])
        self.yOrBox.setValue(cv.origin[1])
        self.zOrBox.setValue(cv.origin[2])

        self.widthBox.setValue(cv.width)
        self.heightBox.setValue(cv.height)

    def resizeEvent(self, event):
        self.mw.resizeEvent(event)

    def hideEvent(self, event):
        self.mw.resizeEvent(event)

    def showEvent(self, event):
        self.mw.resizeEvent(event)

    def moveEvent(self, event):
        self.mw.resizeEvent(event)
Exemplo n.º 40
0
class MainWindow(QMainWindow):
    font: QFont
    vertical_layout: QVBoxLayout
    central_widget: QWidget
    text_box: QPlainTextEdit
    recognize_button: QPushButton

    assistant: AssistantInterface

    def __init__(self, assistant: AssistantInterface):
        super().__init__()

        qInitResources()

        self.assistant = assistant

        self.build_layout()
        self.init_handlers()

    def build_layout(self):
        self.setup_window()
        self.setup_styles()
        self.setup_font()

        self.build_central_widget()
        self.build_vertical_layout()
        self.build_text_box()
        self.build_recognize_button()

        QMetaObject.connectSlotsByName(self)

    def setup_window(self):
        window_size = QSize(420, 700)

        self.setObjectName("window")
        self.resize(window_size)
        self.setMinimumSize(window_size)
        self.setMaximumSize(window_size)
        self.setWindowTitle(u"Voice Assistant")
        self.setAutoFillBackground(False)

    def setup_styles(self):
        file = QFile(":/styles/style.css")
        file.open(QFile.ReadOnly)

        byte_array = file.readAll()

        file.close()

        self.setStyleSheet(byte_array.data().decode())

    def setup_font(self):
        self.font = QFont()
        self.font.setFamily(u"Helvetica")
        self.font.setPointSize(18)

    def build_central_widget(self):
        size_policy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        size_policy.setHorizontalStretch(0)
        size_policy.setVerticalStretch(0)

        self.central_widget = QWidget(self)
        self.central_widget.setObjectName(u"central_widget")
        self.central_widget.setSizePolicy(size_policy)

        self.setCentralWidget(self.central_widget)

    def build_vertical_layout(self):
        self.vertical_layout = QVBoxLayout(self.central_widget)
        self.vertical_layout.setObjectName(u"vertical_layout")

    def build_text_box(self):
        text_box_size = QSize(420, 600)

        self.text_box = QPlainTextEdit(self.central_widget)
        self.text_box.setObjectName(u"text_box")
        self.text_box.setMaximumSize(text_box_size)
        self.text_box.setFont(self.font)
        self.text_box.setContextMenuPolicy(Qt.NoContextMenu)
        self.text_box.setUndoRedoEnabled(False)
        self.text_box.setReadOnly(True)
        self.text_box.setPlaceholderText("Waiting for your question...")

        self.vertical_layout.addWidget(self.text_box)

    def build_recognize_button(self):
        button_size = QSize(140, 40)

        self.recognize_button = QPushButton(self.central_widget)
        self.recognize_button.setObjectName(u"recognize_button")
        self.recognize_button.setEnabled(True)
        self.recognize_button.setMinimumSize(button_size)
        self.recognize_button.setMaximumSize(button_size)
        self.recognize_button.setFont(self.font)
        self.recognize_button.setAutoFillBackground(False)
        self.recognize_button.setText("Recognize")
        self.recognize_button.setShortcut("Return")

        self.vertical_layout.addWidget(self.recognize_button, 0,
                                       Qt.AlignHCenter)

    def init_handlers(self):
        self.recognize_button.pressed.connect(self.start_recognition)
        self.assistant.on_wake = self.on_assistant_started
        self.assistant.on_sleep = self.on_assistant_finished
        self.assistant.on_assistant_listen = self.on_recognize_started
        self.assistant.on_user_message = self.on_user_text
        self.assistant.on_assistant_message = self.on_assistant_text

    def on_assistant_started(self):
        self.recognize_button.setEnabled(False)

    def on_assistant_finished(self):
        self.recognize_button.setEnabled(True)
        self.recognize_button.setText("Recognize")

    def on_recognize_started(self):
        self.async_play_sound()
        self.recognize_button.setText("Listening...")

    def on_user_text(self, user_text: str):
        self.recognize_button.setText("Processing...")
        self.append_message(f"[You] {user_text}")

    def on_assistant_text(self, assistant_answer: str):
        signed_text = f"[{self.assistant.get_name()}] {assistant_answer}"
        self.append_message(signed_text)

    def append_message(self, message: str):
        self.text_box.appendPlainText(f"{message}\n")

    def start_recognition(self):
        coroutine = self.assistant.handle()
        asyncio.create_task(coroutine)

    @async_function
    def async_play_sound(self):
        file = QFile(":/sounds/click.mp3")
        file.open(QFile.ReadOnly)

        byte_array = file.readAll()

        file.close()

        with tempfile.NamedTemporaryFile("wb", delete=True) as temp:
            temp.write(byte_array.data())
            playsound(temp.name)

    def closeEvent(self, event: QCloseEvent):
        for task in asyncio.all_tasks():
            task.cancel()

        asyncio.get_running_loop().stop()

    async def start(self):
        self.show()
Exemplo n.º 41
0
class ColorDialog(QDialog):
    def __init__(self, model, FM, parent=None):
        super(ColorDialog, self).__init__(parent)

        self.setWindowTitle('Color Options')

        self.model = model
        self.FM = FM
        self.mw = parent

        self.createDialogLayout()

    def createDialogLayout(self):

        self.createGeneralTab()

        self.cellTable = self.createDomainTable(self.mw.cellsModel)
        self.matTable = self.createDomainTable(self.mw.materialsModel)
        self.cellTab = self.createDomainTab(self.cellTable)
        self.matTab = self.createDomainTab(self.matTable)

        self.tabs = QTabWidget()
        self.tabs.setMaximumHeight(800)
        self.tabs.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.tabs.addTab(self.generalTab, 'General')
        self.tabs.addTab(self.cellTab, 'Cells')
        self.tabs.addTab(self.matTab, 'Materials')

        self.createButtonBox()

        self.colorDialogLayout = QVBoxLayout()
        #self.colorDialogLayout.setContentsMargins(0, 0, 0, 0)
        self.colorDialogLayout.addWidget(self.tabs)
        self.colorDialogLayout.addWidget(self.buttonBox)
        self.setLayout(self.colorDialogLayout)

    def createGeneralTab(self):

        # Masking options
        self.maskingCheck = QCheckBox('')
        self.maskingCheck.stateChanged.connect(self.mw.toggleMasking)

        self.maskColorButton = QPushButton()
        self.maskColorButton.setCursor(QtCore.Qt.PointingHandCursor)
        self.maskColorButton.setFixedWidth(self.FM.width("XXXXXXXXXX"))
        self.maskColorButton.setFixedHeight(self.FM.height() * 1.5)
        self.maskColorButton.clicked.connect(self.mw.editMaskingColor)

        # Highlighting options
        self.hlCheck = QCheckBox('')
        self.hlCheck.stateChanged.connect(self.mw.toggleHighlighting)

        self.hlColorButton = QPushButton()
        self.hlColorButton.setCursor(QtCore.Qt.PointingHandCursor)
        self.hlColorButton.setFixedWidth(self.FM.width("XXXXXXXXXX"))
        self.hlColorButton.setFixedHeight(self.FM.height() * 1.5)
        self.hlColorButton.clicked.connect(self.mw.editHighlightColor)

        self.alphaBox = QDoubleSpinBox()
        self.alphaBox.setRange(0, 1)
        self.alphaBox.setSingleStep(.05)
        self.alphaBox.valueChanged.connect(self.mw.editAlpha)

        self.seedBox = QSpinBox()
        self.seedBox.setRange(1, 999)
        self.seedBox.valueChanged.connect(self.mw.editSeed)

        # General options
        self.bgButton = QPushButton()
        self.bgButton.setCursor(QtCore.Qt.PointingHandCursor)
        self.bgButton.setFixedWidth(self.FM.width("XXXXXXXXXX"))
        self.bgButton.setFixedHeight(self.FM.height() * 1.5)
        self.bgButton.clicked.connect(self.mw.editBackgroundColor)

        self.colorbyBox = QComboBox(self)
        self.colorbyBox.addItem("material")
        self.colorbyBox.addItem("cell")
        self.colorbyBox.currentTextChanged[str].connect(self.mw.editColorBy)

        formLayout = QFormLayout()
        formLayout.setAlignment(QtCore.Qt.AlignHCenter)
        formLayout.setFormAlignment(QtCore.Qt.AlignHCenter)
        formLayout.setLabelAlignment(QtCore.Qt.AlignLeft)
        #formLayout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)

        formLayout.addRow('Masking:', self.maskingCheck)
        formLayout.addRow('Mask Color:', self.maskColorButton)
        formLayout.addRow(HorizontalLine())
        formLayout.addRow('Highlighting:', self.hlCheck)
        formLayout.addRow('Highlight Color:', self.hlColorButton)
        formLayout.addRow('Highlight Alpha:', self.alphaBox)
        formLayout.addRow('Highlight Seed:', self.seedBox)
        formLayout.addRow(HorizontalLine())
        formLayout.addRow('Background Color:          ', self.bgButton)
        formLayout.addRow('Color Plot By:', self.colorbyBox)

        generalLayout = QHBoxLayout()
        innerWidget = QWidget()
        generalLayout.setAlignment(QtCore.Qt.AlignVCenter)
        innerWidget.setLayout(formLayout)
        generalLayout.addStretch(1)
        generalLayout.addWidget(innerWidget)
        generalLayout.addStretch(1)

        self.generalTab = QWidget()
        self.generalTab.setLayout(generalLayout)

    def createDomainTable(self, domainmodel):

        domainTable = QTableView()
        domainTable.setModel(domainmodel)
        domainTable.setItemDelegate(DomainDelegate(domainTable))
        domainTable.verticalHeader().setVisible(False)
        domainTable.resizeColumnsToContents()
        domainTable.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        domainTable.horizontalHeader().setSectionResizeMode(
            1, QHeaderView.Stretch)

        return domainTable

    def createDomainTab(self, domaintable):

        domainTab = QWidget()
        domainTab.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        domainLayout = QVBoxLayout()
        domainLayout.addWidget(domaintable)
        domainTab.setLayout(domainLayout)

        return domainTab

    def createButtonBox(self):

        applyButton = QPushButton("Apply Changes")
        applyButton.clicked.connect(self.mw.applyChanges)
        closeButton = QPushButton("Close")
        closeButton.clicked.connect(self.hide)

        buttonLayout = QHBoxLayout()
        buttonLayout.addStretch(1)
        buttonLayout.addWidget(applyButton)
        buttonLayout.addWidget(closeButton)

        self.buttonBox = QWidget()
        self.buttonBox.setLayout(buttonLayout)

    def updateDialogValues(self):

        self.updateMasking()
        self.updateMaskingColor()
        self.updateHighlighting()
        self.updateHighlightColor()
        self.updateAlpha()
        self.updateSeed()
        self.updateBackgroundColor()
        self.updateColorBy()

        self.updateDomainTabs()

    def updateMasking(self):
        masking = self.model.activeView.masking

        self.maskingCheck.setChecked(masking)
        self.maskColorButton.setDisabled(not masking)

        if masking:
            self.cellTable.showColumn(4)
            self.matTable.showColumn(4)
        else:
            self.cellTable.hideColumn(4)
            self.matTable.hideColumn(4)

    def updateMaskingColor(self):
        color = self.model.activeView.maskBackground
        self.maskColorButton.setStyleSheet("border-radius: 8px;"
                                           "background-color: rgb%s" %
                                           (str(color)))

    def updateHighlighting(self):
        highlighting = self.model.activeView.highlighting

        self.hlCheck.setChecked(highlighting)
        self.hlColorButton.setDisabled(not highlighting)
        self.alphaBox.setDisabled(not highlighting)
        self.seedBox.setDisabled(not highlighting)

        if highlighting:
            self.cellTable.showColumn(5)
            self.cellTable.hideColumn(2)
            self.cellTable.hideColumn(3)
            self.matTable.showColumn(5)
            self.matTable.hideColumn(2)
            self.matTable.hideColumn(3)
        else:
            self.cellTable.hideColumn(5)
            self.cellTable.showColumn(2)
            self.cellTable.showColumn(3)
            self.matTable.hideColumn(5)
            self.matTable.showColumn(2)
            self.matTable.showColumn(3)

    def updateHighlightColor(self):
        color = self.model.activeView.highlightBackground
        self.hlColorButton.setStyleSheet("border-radius: 8px;"
                                         "background-color: rgb%s" %
                                         (str(color)))

    def updateAlpha(self):
        self.alphaBox.setValue(self.model.activeView.highlightAlpha)

    def updateSeed(self):
        self.seedBox.setValue(self.model.activeView.highlightSeed)

    def updateBackgroundColor(self):
        color = self.model.activeView.plotBackground
        self.bgButton.setStyleSheet("border-radius: 8px;"
                                    "background-color: rgb%s" % (str(color)))

    def updateColorBy(self):
        self.colorbyBox.setCurrentText(self.model.activeView.colorby)

    def updateDomainTabs(self):
        self.cellTable.setModel(self.mw.cellsModel)
        self.matTable.setModel(self.mw.materialsModel)
Exemplo n.º 42
0
    def __init__(self, parent=None):
        QFrame.__init__(self, parent)
        self.setStyleSheet("""QFrame{ background-color:#43454f;}""")
        self.setFrameShape(QFrame.StyledPanel)
        self.setFrameShadow(QFrame.Raised)

        self.frame_nav = QFrame(self)
        self.frame_nav.setMinimumSize(QSize(220, 300))
        self.frame_nav.setStyleSheet("""QFrame{ background-color:#43454f;}""")
        self.frame_nav.setFrameShape(QFrame.StyledPanel)
        self.frame_nav.setFrameShadow(QFrame.Raised)

        self.gridLayout = QGridLayout(self)
        self.gridLayout.setContentsMargins(11, -1, 11, -1)
        self.gridLayout.addWidget(self.frame_nav, 3, 0, 1, 4)

        # set program img and name
        self.label_img = QLabel(self)
        self.label_img.setFixedSize(QSize(60, 60))
        self.label_img.setPixmap(QPixmap(os.path.join(path, 'img/icon.png')))
        # self.label_img.setPixmap(QPixmap("../img/icon.png"))
        self.label_img.setScaledContents(True)
        self.gridLayout.addWidget(self.label_img, 2, 1, 1, 1)

        self.label_name = QLabel("WebCheck        ", self)
        self.label_name.setStyleSheet(styles.label_icon_name)
        self.gridLayout.addWidget(self.label_name, 2, 2, 1, 1)

        self.spacer_name_l = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                         QSizePolicy.Minimum)
        self.spacer_name_r = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                         QSizePolicy.Minimum)
        self.spacer_name_t = QSpacerItem(20, 70, QSizePolicy.Minimum,
                                         QSizePolicy.Maximum)
        self.gridLayout.addItem(self.spacer_name_l, 2, 0, 1, 1)
        self.gridLayout.addItem(self.spacer_name_r, 2, 3, 1, 1)
        self.gridLayout.addItem(self.spacer_name_t, 1, 1, 1, 2)

        # set bottom layout for keeping gb in it
        self.gridLayout_b = QGridLayout(self.frame_nav)
        self.spacer_gb_l = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                       QSizePolicy.Minimum)
        self.spacer_gb_r = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                       QSizePolicy.Minimum)
        self.spacer_gb_t = QSpacerItem(0, 20, QSizePolicy.Minimum,
                                       QSizePolicy.Maximum)
        self.spacer_gb_b = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                       QSizePolicy.Expanding)
        self.gridLayout_b.addItem(self.spacer_gb_l, 1, 2, 1, 1)
        self.gridLayout_b.addItem(self.spacer_gb_r, 1, 0, 1, 1)
        self.gridLayout_b.addItem(self.spacer_gb_t, 0, 1, 1, 1)
        self.gridLayout_b.addItem(self.spacer_gb_b, 2, 1, 1, 1)

        # set gb and radio buttons
        self.groupBox = QGroupBox("", self.frame_nav)
        self.gridLayout_b.addWidget(self.groupBox, 1, 1, 1, 1)
        self.groupBox.setMinimumSize(QSize(220, 350))
        self.groupBox.setStyleSheet(
            """QGroupBox{background-image: url(ui/img/radioline.png);  border: none;}"""
        )
        self.verticalLayout_gb = QVBoxLayout(self.groupBox)

        self.radioButton_add = QRadioButton(" Add", self.groupBox)
        self.radioButton_add.setStyleSheet(styles.btn_radio)
        self.verticalLayout_gb.addWidget(self.radioButton_add)

        self.radioButton_monitored = QRadioButton(" Monitored", self.groupBox)
        self.radioButton_monitored.setStyleSheet(styles.btn_radio)
        self.verticalLayout_gb.addWidget(self.radioButton_monitored)

        self.radioButton_options = QRadioButton(" Options", self.groupBox)
        self.radioButton_options.setStyleSheet(styles.btn_radio)
        self.verticalLayout_gb.addWidget(self.radioButton_options)

        self.radioButton_about = QRadioButton(" About", self.groupBox)
        self.radioButton_about.setStyleSheet(styles.btn_radio)
        self.verticalLayout_gb.addWidget(self.radioButton_about)
Exemplo n.º 43
0
Arquivo: t.py Projeto: Yobmod/dmltests
class Form(QWidget):
    """"""

    def __init__(self, parent: QApplication = None, *,
                 title: str = "wooo", width: int = 400, height: int = 600, ) -> None:
        """Constructor"""
        super().__init__(parent)
        mixer.init()  # initializethe pygame mixer

        self.assets_path: str = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'assets')

        if parent is not None:
            self.parent = parent

        """
        self.parent.iconbitmap()
        """
        horiz_pos = 100  # from left of screen
        vertic_pos = 200  # from top of screen
        self.height = height
        self.width = width
        self.title = title

        self.setGeometry(horiz_pos, vertic_pos, self.width, self.height)      # QtCore.QRect(x, y, w, h)
        self.setWindowTitle(self.title)

        self.setWindowIcon(QtGui.QIcon(self.assets_path + '/icons/melody.ico'))
        self.init_vol: int = 70
        self.paused: bool = False
        self.muted: bool = False
        self.playing: bool = False
        self.current_song: Opt[str] = None
        self.selected_song_num: Opt[int] = None
        self.playlist: List[str] = []

        self._init_ui()
        self.show()

    def _init_ui(self) -> None:
        self.layout = QVBoxLayout()
        self._menubar()

        self._create_rightframe()
        self._create_middleframe()
        self._create_leftframe()
        self._create_bottomframe()

        self.edit = QLineEdit("Write my name here")
        self.layout.addWidget(self.edit)

        self.greet_button = QPushButton("Show Greetings")
        self.greet_button.clicked.connect(self.greetings)
        self.layout.addWidget(self.greet_button)

        self._statusbar()
        self.setLayout(self.layout)

    def _menubar(self) -> None:
        menubar = QMenuBar()
        self.layout.addWidget(menubar)

        fileMenu = menubar.addMenu('File')
        fileMenu.addAction('Open', self.browse_file)
        fileMenu.addSeparator()
        fileMenu.addAction('Exit', self.close)

        helpMenu = menubar.addMenu('Help')
        helpMenu.addSeparator()
        helpMenu.addAction('About Us', self.about_us)
        # toolbar = self.addToolBar('Exit')
        # toolbar.addAction(self.play_music)

    def _statusbar(self) -> None:
        self.statusbar = QStatusBar()
        self.layout.addWidget(self.statusbar)
        self.statusbar.showMessage('Welcome', timeout=10_000)
        # status_bar = statusbar_parent.addPermanentWidget(statusbar_parent, stretch=True)

    def _create_rightframe(self) -> None:
        self.rightframe = QVBoxLayout()
        self.layout.addLayout(self.rightframe)

        self.filelabel = QLabel(text='Lets make some noise!')
        self.rightframe.addWidget(self.filelabel)

        self.lengthlabel = QLabel(text='Total Length : --:--')
        self.rightframe.addWidget(self.lengthlabel)

        self.currenttimelabel = QLabel(text='Current Time : --:--')
        self.rightframe.addWidget(self.currenttimelabel)

    def _create_leftframe(self) -> None:
        self.leftframe = QVBoxLayout()
        self.layout.addLayout(self.leftframe)

        self.playlistbox = QListWidget(self)
        self.playlistbox.setToolTip('''PlayListBox:
                                    Select song from list to play.
                                    Use browse or delete buttons to change playlist''')
        self.leftframe.addWidget(self.playlistbox)

        self.browse_button = QPushButton("Browse")
        self.browse_button.clicked.connect(self.browse_file)
        self.leftframe.addWidget(self.browse_button)

        self.delete_button = QPushButton("Delete")
        self.delete_button.clicked.connect(self.del_song)
        self.leftframe.addWidget(self.delete_button)

    def _create_middleframe(self) -> None:
        self.middleframe = QVBoxLayout()
        self.layout.addLayout(self.middleframe)

        self.play_button = QPushButton("Play")
        self.play_button.clicked.connect(self.play_music)
        play_icon = QtGui.QIcon(QtGui.QPixmap(self.assets_path + '/icons/play.png'))
        # play_icon.addPixmap(QtGui.QPixmap(self.assets_path + '/icons/play.png'))
        self.play_button.setIcon(play_icon)
        # self.play_button.setIconSize(QtCore.QSize(100, 100))
        self.middleframe.addWidget(self.play_button)

        self.stop_button = QPushButton("Stop")
        self.stop_button.clicked.connect(self.stop_music)
        stop_icon = QtGui.QIcon(QtGui.QPixmap(self.assets_path + '/icons/stop.png'))
        self.stop_button.setIcon(stop_icon)
        # self.stop_button.setIconSize(QtCore.QSize(100, 100))
        self.middleframe.addWidget(self.stop_button)

        self.pause_button = QPushButton("Pause")
        self.pause_button.clicked.connect(self.pause_music)
        pause_icon = QtGui.QIcon(QtGui.QPixmap(self.assets_path + '/icons/pause.png'))
        self.pause_button.setIcon(pause_icon)
        # self.pause_button.setIconSize(QtCore.QSize(100, 100))
        self.middleframe.addWidget(self.pause_button)

    def _create_bottomframe(self) -> None:
        self.bottomframe = QVBoxLayout()
        self.layout.addLayout(self.bottomframe)

        self.volume_button = QPushButton("Mute")
        self.mute_icon = QtGui.QIcon(QtGui.QPixmap(self.assets_path + '/icons/mute.png'))
        self.volume_icon = QtGui.QIcon(QtGui.QPixmap(self.assets_path + '/icons/volume.png'))
        self.volume_button.setIcon(self.volume_icon)
        # self.volume_button.setIconSize(QtCore.QSize(100, 100))
        self.volume_button.clicked.connect(self.mute_music)
        self.bottomframe.addWidget(self.volume_button)

        self.rewind_button = QPushButton("Rewind")
        rewind_icon = QtGui.QIcon(QtGui.QPixmap(self.assets_path + '/icons/rewind.png'))
        self.rewind_button.setIcon(rewind_icon)
        # self.volume_button.setIconSize(QtCore.QSize(100, 100))
        self.play_button.clicked.connect(self.rewind_music)
        self.bottomframe.addWidget(self.rewind_button)

        self.vol_scale = QSlider(QtCore.Qt.Horizontal)
        self.vol_scale.setMinimum(0)
        self.vol_scale.setMaximum(100)
        # self.vol_scale.setTickPosition(QSlider.TicksBelow)
        # self.vol_scale.setTickInterval(5)
        self.vol_scale.setValue(self.init_vol)
        self.vol_scale.valueChanged.connect(self.set_vol)
        self.bottomframe.addWidget(self.vol_scale)
        mixer.music.set_volume(self.vol_scale.value())

        # exitAction = QtGui.QAction('Exit', self)
        # exitAction.setShortcut('Ctrl+Q')
        # exitAction.setStatusTip('Exit application')
        # exitAction.triggered.connect(self.close)

    def set_vol(self) -> None:
        self.vol_from_slider: int = self.vol_scale.value()
        volume_percent: float = self.vol_from_slider / 100
        mixer.music.set_volume(volume_percent)  # from 0 to 1

    def mute_music(self) -> None:
        if self.muted:  # Unmute the music
            mixer.music.set_volume(self.vol_pre_mute / 100)
            self.volume_button.setIcon(self.volume_icon)
            self.vol_scale.setValue(self.vol_pre_mute)  # (self.vol_from_slider)
            self.muted = False
        else:  # mute the music
            self.vol_pre_mute: int = self.vol_scale.value()
            mixer.music.set_volume(0)
            self.volume_button.setIcon(self.mute_icon)
            self.vol_scale.setValue(0)
            self.muted = True

    def greetings(self) -> None:
        text = self.edit.text()
        print('Contents of QLineEdit widget: {}'.format(text))
        self.statusbar.showMessage(text, timeout=2_000)

    def about_us(self) -> None:
        text = self.edit.text()
        print('Contents of QLineEdit widget: {}'.format(text))

    def browse_file(self) -> None:
        get_filename_path: Tuple[str, str] = QFileDialog.getOpenFileName(self,   # if cancelled, returns ("", "")
                                                                         "Open Sound File",
                                                                         self.assets_path,
                                                                         "Sound Files (*.wav *.mp3 *.ogg)")
        print(get_filename_path)
        filename_path = get_filename_path[0]
        if filename_path:
            self.add_to_playlist(filename_path)
            mixer.music.queue(filename_path)

    def add_to_playlist(self, filepath: str) -> None:
        filename = os.path.basename(filepath)
        index = 0
        # print(self.playlist)
        # QListWidgetItem(self.playlistbox).setText(filename)  # last_added =
        self.playlistbox.insertItem(index, filename)  # .addItems([filenames])
        self.playlist.insert(index, filepath)
        index += 1

    def del_song(self) -> None:
        self.get_selected_song_num()  # update self.selected_song_num
        if self.selected_song_num is not None:  # if a song is selected
            print(self.selected_song_num)
            if self.playlist[self.selected_song_num] == self.current_song:  # if song is currently playing
                self.stop_music()                                           # stop it
            self.playlistbox.takeItem(self.selected_song_num)   # remove the song from the box, note returns the song object
            self.playlist.pop(self.selected_song_num)        # and playlist
            # self.selected_song_num remains same, so will play/del next song?
            self.reset_song()
            self.statusbar.showMessage("Song removed from playlist", timeout=1_000)
            self.selected_song_num = None  # reset self.selected_song_num"""

    def get_selected_song_num(self) -> None:
        if self.playlistbox.count() > 0:
            selected_song_from_box = self.playlistbox.currentItem()  # get current item
            if selected_song_from_box:
                self.selected_song: str = selected_song_from_box.text()  # get items text
                self.selected_song_num: int = self.playlistbox.currentRow()
            else:
                self.statusbar.showMessage("Choose a file from the playlist", timeout=2_000)
        else:
            self.statusbar.showMessage("No files loaded to playlist", timeout=2_000)

    def stop_music(self) -> None:
        if self.playing:
            self.playing = False
            self.current_song = None
            mixer.music.stop()
            self.statusbar.showMessage("Music Stopped", timeout=5_000)

    def pause_music(self) -> None:
        if self.playing:
            self.paused = True
            mixer.music.pause()
            self.statusbar.showMessage("Music paused", timeout=0)

    def rewind_music(self) -> None:
        if self.playing:
            self.stop_music()
            time.sleep(0.5)
            self.play_music()
            self.statusbar.showMessage("Music Rewound to start", timeout=1_000)

    def reset_song(self) -> None:
        self.current_song = None
        self.filelabel.setText("")
        self.lengthlabel.setText('Total Length : --:00')
        self.currenttimelabel.setText("Current Time : --:--")
        # self.statusbar.showMessage("", timeout=0)

    def show_details(self, play_song: str) -> None:
        self.filelabel.setText("Playing" + ' - ' + os.path.basename(play_song))
        file_data = os.path.splitext(play_song)

        if file_data[1] == '.mp3':
            audio = MP3(play_song)
            total_length = audio.info.length
        elif file_data[1] == '.wav':
            a = mixer.Sound(play_song)
            total_length = a.get_length()
        else:
            try:
                a = mixer.Sound(play_song)
                total_length = a.get_length()
            except Exception as e:
                print(e)
        self.current_song_lenth = total_length
        mins, secs = divmod(total_length, 60)  # returns (time//60, remainder)
        mins = round(mins)
        secs = round(secs)
        timeformat = '{:02d}:{:02d}'.format(mins, secs)
        self.lengthlabel.setText("Total Length" + ' - ' + timeformat)

        self.t1 = threading.Thread(target=self.start_count, args=(total_length, ))
        self.t1.start()

    def start_count(self, total_time: int) -> None:
        """"""
        current_time = 0
        while current_time <= total_time and mixer.music.get_busy():  # music.get_busy() -> Returns False when stopped
            if self.paused:
                continue  # if paused, infinite loop (don't count)
            else:
                mins, secs = divmod(current_time, 60)
                mins = round(mins)
                secs = round(secs)
                timeformat = '{:02d}:{:02d}'.format(mins, secs)
                self.currenttimelabel.setText("Current Time" + ' - ' + timeformat)
                time.sleep(1)
                current_time += 1

    def play_music(self) -> None:
        '''if not playing: play, if playing and paused, unpause'''
        self.get_selected_song_num()  # update self.selected_song_num
        if self.selected_song_num is not None and self.playlist:
            play_it: Opt[str] = self.playlist[self.selected_song_num]
        else:
            play_it = None

        if not self.playing and play_it:  # if not yet playing, play selected song
            try:
                self.stop_music()
                time.sleep(0.5)
                mixer.music.load(play_it)
                mixer.music.play()
            except Exception as e:
                # messagebox.showerror('File not found, or unknown file type. Please check again.')
                if DEBUG: print(e)
            else:
                self.playing = True
                self.current_song = play_it
                self.show_details(play_it)
                self.statusbar.showMessage("Playing music" + ' - ' + os.path.basename(play_it))
        elif self.playing and self.paused:  # if paused, resume
            mixer.music.unpause()
            # self.statusbar.showMessage("Playing music" + ' - ' + os.path.basename(play_it))
            self.statusbar.showMessage("Music Resumed", timeout=1_000)
            self.paused = False
        elif self.playing and not self.paused:
            if play_it == self.current_song and play_it is not None:  # if already playing song, do nothing
                self.statusbar.showMessage("Playing music" + ' - ' + os.path.basename(play_it), timeout=0)  # TODO timout current song len
            else:           # if different song selected, retry
                self.playing = False
                self.play_music()

    def close(self) -> None:
        try:
            self.stop_music()
            QApplication.closeAllWindows()
        except Exception as e:
            sys.exit(1)
            if DEBUG: print(e)
        else:
            print('App closed')
Exemplo n.º 44
0
    def __init__(self, app, parent=None):
        super(MainWindow, self).__init__(parent)
        self.imagesDir = app.dir + '/images/'
        self.setWindowIcon(QIcon(self.imagesDir + 'icon.png'))
        self.path = ''

        self.settings = QSettings()
        self.lastDir = self.settings.value('lastDir', '')

        self.setMinimumWidth(540)

        self.supportedFormats = []
        for f in QImageReader.supportedImageFormats():
            self.supportedFormats.append(str(f.data(), encoding="utf-8"))

        self.fileWatcher = QFileSystemWatcher()
        self.fileWatcher.fileChanged.connect(self.fileChanged)

        # widgets
        self.showPixmapWidget = None

        self.tileWidthSpinBox = QSpinBox()
        self.tileWidthSpinBox.setValue(16)
        self.tileWidthSpinBox.setFixedWidth(50)
        self.tileWidthSpinBox.setMinimum(1)

        self.tileHeightSpinBox = QSpinBox()
        self.tileHeightSpinBox.setValue(16)
        self.tileHeightSpinBox.setFixedWidth(50)
        self.tileHeightSpinBox.setMinimum(1)

        self.paddingSpinBox = QSpinBox()
        self.paddingSpinBox.setFixedWidth(50)
        self.paddingSpinBox.setMinimum(1)

        self.transparentCheckbox = QCheckBox("Transparent")
        self.transparentCheckbox.setChecked(True)
        self.transparentCheckbox.stateChanged.connect(self.transparentChanged)

        self.backgroundColorEdit = ColorEdit()
        self.backgroundColorEdit.setEnabled(False)
        self.backgroundColorLabel = QLabel("Background color:")
        self.backgroundColorLabel.setEnabled(False)

        self.forcePotCheckBox = QCheckBox("Force PoT")
        self.forcePotCheckBox.setChecked(True)
        self.forcePotCheckBox.stateChanged.connect(self.forcePotChanged)

        self.reorderTilesCheckBox = QCheckBox("Reorder tiles")

        self.generateAndExportButton = QPushButton("Generate and export")
        self.generateAndExportButton.setFixedHeight(32)
        self.generateAndExportButton.clicked.connect(self.generateAndExportClicked)
        self.generateAndExportButton.setEnabled(False)

        self.pixmapWidget = PixmapWidget()
        self.pixmapWidget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.pixmapWidget.setPixmap(self.createDropTextPixmap())
        self.pixmapWidget.dropSignal.connect(self.fileDropped)
        self.pixmapWidget.setMinimumHeight(300)

        # load settings
        self.tileWidthSpinBox.setValue(int(self.settings.value('tileWidth', 16)))
        self.tileHeightSpinBox.setValue(int(self.settings.value('tileHeight', 16)))
        self.paddingSpinBox.setValue(int(self.settings.value('padding', 1)))
        self.forcePotCheckBox.setChecked(True if self.settings.value('forcePot', 'true') == 'true' else False)
        self.reorderTilesCheckBox.setChecked(True if self.settings.value('reorderTiles', 'false') == 'true' else False)
        self.transparentCheckbox.setChecked(True if self.settings.value('transparent', 'false') == 'true' else False)
        self.backgroundColorEdit.setColorText(str(self.settings.value('backgroundColor', '#FF00FF')))
        self.restoreGeometry(QByteArray(self.settings.value('MainWindow/geometry')))
        self.restoreState(QByteArray(self.settings.value('MainWindow/windowState')))

        # layout
        hl1 = QHBoxLayout()
        hl1.setContentsMargins(5, 5, 5, 5)
        hl1.addWidget(QLabel("Tile width:"))
        hl1.addSpacing(5)
        hl1.addWidget(self.tileWidthSpinBox)
        hl1.addSpacing(15)
        hl1.addWidget(QLabel("Tile height:"))
        hl1.addSpacing(5)
        hl1.addWidget(self.tileHeightSpinBox)
        hl1.addSpacing(15)
        hl1.addWidget(QLabel("Padding:"))
        hl1.addSpacing(5)
        hl1.addWidget(self.paddingSpinBox)
        hl1.addSpacing(15)
        hl1.addWidget(self.forcePotCheckBox)
        hl1.addSpacing(15)
        hl1.addWidget(self.reorderTilesCheckBox)
        hl1.addStretch()

        hl2 = QHBoxLayout()
        hl2.setContentsMargins(5, 5, 5, 5)
        hl2.addWidget(self.transparentCheckbox)
        hl2.addSpacing(15)
        hl2.addWidget(self.backgroundColorLabel)
        hl2.addSpacing(5)
        hl2.addWidget(self.backgroundColorEdit)
        hl2.addStretch()

        hl3 = QHBoxLayout()
        hl3.setContentsMargins(5, 5, 5, 5)
        hl3.addWidget(self.generateAndExportButton)

        vl = QVBoxLayout()
        vl.setContentsMargins(0, 0, 0, 0)
        vl.setSpacing(0)
        vl.addLayout(hl1)
        vl.addLayout(hl2)
        vl.addWidget(self.pixmapWidget)
        vl.addLayout(hl3)

        w = QWidget()
        w.setLayout(vl)
        self.setCentralWidget(w)

        self.setTitle()
Exemplo n.º 45
0
class ServingMachineStatistics(QWidget):
    def __init__(self):
        super().__init__()

        self.mainLayout = QVBoxLayout()

        self.dataLayout = QHBoxLayout()
        self.generatorLabel = QLabel("Generator")
        self.mLabel = QLabel("\u03BC")
        self.mLine = QLineEdit("10")
        self.sigmaLabel = QLabel("\u03C3")
        self.sigmaLine = QLineEdit("1")
        self.genBox = QFormLayout()
        self.genBox.addWidget(self.generatorLabel)
        self.genBox.addRow(self.mLabel, self.mLine)
        self.genBox.addRow(self.sigmaLabel, self.sigmaLine)

        self.processorLabel = QLabel("Processor")
        self.aLabel = QLabel("a")
        self.aLine = QLineEdit("5")
        self.bLabel = QLabel("b")
        self.bLine = QLineEdit("15")
        self.procBox = QFormLayout()
        self.procBox.addWidget(self.processorLabel)
        self.procBox.addRow(self.aLabel, self.aLine)
        self.procBox.addRow(self.bLabel, self.bLine)

        self.genBox.setSpacing(10)
        self.procBox.setSpacing(10)
        self.dataLayout.addLayout(self.genBox)
        self.dataLayout.addLayout(self.procBox)
        self.dataLayout.setSpacing(30)

        self.hLayout = QHBoxLayout()

        self.numLayout = QFormLayout()
        self.numLabel = QLabel("Number of requests")
        self.numLine = QLineEdit("10000")
        self.numLayout.addWidget(self.numLabel)
        self.numLayout.addWidget(self.numLine)

        self.deltLayout = QFormLayout()
        self.deltLabel = QLabel("\u0394t")
        self.deltLine = QLineEdit("1")
        self.deltLayout.addWidget(self.deltLabel)
        self.deltLayout.addWidget(self.deltLine)

        self.probLayout = QFormLayout()
        self.probLabel = QLabel("Probability of returning")
        self.probLine = QLineEdit("0")
        self.probLayout.addWidget(self.probLabel)
        self.probLayout.addWidget(self.probLine)


        self.numLayout.setSpacing(10)
        self.deltLayout.setSpacing(10)
        self.probLayout.setSpacing(10)

        self.hLayout.addLayout(self.numLayout)
        self.hLayout.addLayout(self.deltLayout)
        self.hLayout.addLayout(self.probLayout)
        self.hLayout.setSpacing(30)

        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)

        line1 = QFrame()
        line1.setFrameShape(QFrame.HLine)
        line1.setFrameShadow(QFrame.Sunken)

        self.answerLabel = QLabel("Optimal length of queue")
        self.dtLabel = QLabel("\u0394t")
        self.dtLine = QLabel()
        self.dtLine.setFrameShape(QFrame.WinPanel)
        self.dtLine.setFrameShadow(QFrame.Raised)
        self.eventLabel = QLabel("Events")
        self.eventLine = QLabel()
        self.eventLine.setFrameShape(QFrame.WinPanel)
        self.eventLine.setFrameShadow(QFrame.Raised)
        self.answerBox = QFormLayout()
        self.answerBox.addWidget(self.answerLabel)
        self.answerBox.addRow(self.dtLabel, self.dtLine)
        self.answerBox.addRow(self.eventLabel, self.eventLine)

        self.button = QPushButton("Calculate")
        self.button.clicked.connect(self.calculate)
        self.button.setMinimumSize(100,65)
        self.button.setMaximumSize(200, 65)
        self.buttonLayout = QVBoxLayout()
        self.buttonLayout.addWidget(self.button)
        self.buttonLayout.setAlignment(Qt.AlignBottom)

        self.answLayout = QHBoxLayout()
        self.answLayout.addLayout(self.answerBox)
        self.answLayout.addLayout(self.buttonLayout)
        #self.answLayout.setAlignment(Qt.AlignBottom)

        self.mainLayout.addLayout(self.dataLayout)
        self.mainLayout.addWidget(line)
        self.mainLayout.addLayout(self.hLayout)
        self.mainLayout.addWidget(line1)
        self.mainLayout.addLayout(self.answLayout)

        self.mainLayout.setAlignment(Qt.AlignVCenter)
        self.mainLayout.setSpacing(20)
        self.setLayout(self.mainLayout)

    def calculate(self):
        m = self.mLine.text()
        try:
            m = float(m)
            if m < 0:
                return
        except Exception as e:
            print(e)

        sigma = self.sigmaLine.text()
        try:
            sigma = float(sigma)
            if math.isclose(sigma, 0.0, rel_tol=1e-07, abs_tol=0.0):
                return
        except Exception as e:
            print(e)

        requestsCount = self.numLine.text()
        try:
            requestsCount = int(requestsCount)
            if requestsCount < 0:
                return

        except Exception as e:
            print(e)

        a = self.aLine.text()
        try:
            a = float(a)
            if a < 0:
                return
        except Exception as e:
            print(e)

        b = self.bLine.text()
        try:
            b = float(b)
            if b < 0:
                return
        except Exception as e:
            print(e)

        dt = self.deltLine.text()
        try:
            dt = float(dt)
            if dt < 0 or math.isclose(dt, 0.0, rel_tol=1e-07, abs_tol=0.0):
                return
        except Exception as e:
            print(e)

        pRet = self.probLine.text()
        try:
            pRet = float(pRet)
            if not -0.00000000001 < pRet <= 1.000000001:
                return
        except Exception as e:
            print(e)

        generator = Generator(m, sigma)
        processor = Processor(a, b)

        self.dtLine.setText(str(getDeltaQueue(generator, processor, requestsCount, dt, pRet)))
        self.eventLine.setText(str(getEventsQueue(generator, processor, requestsCount, pRet)))
Exemplo n.º 46
0
class QSettingsWindow(QDialog):
    def __init__(self, game: Game):
        super(QSettingsWindow, self).__init__()

        self.game = game
        self.pluginsPage = None
        self.pluginsOptionsPage = None

        self.setModal(True)
        self.setWindowTitle("Settings")
        self.setWindowIcon(CONST.ICONS["Settings"])
        self.setMinimumSize(600, 250)

        self.initUi()

    def initUi(self):
        self.layout = QGridLayout()

        self.categoryList = QListView()
        self.right_layout = QStackedLayout()

        self.categoryList.setMaximumWidth(175)

        self.categoryModel = QStandardItemModel(self.categoryList)

        self.categoryList.setIconSize(QSize(32, 32))

        self.initDifficultyLayout()
        difficulty = QStandardItem("Difficulty")
        difficulty.setIcon(CONST.ICONS["Missile"])
        difficulty.setEditable(False)
        difficulty.setSelectable(True)
        self.categoryModel.appendRow(difficulty)
        self.right_layout.addWidget(self.difficultyPage)

        self.initGeneratorLayout()
        generator = QStandardItem("Mission Generator")
        generator.setIcon(CONST.ICONS["Generator"])
        generator.setEditable(False)
        generator.setSelectable(True)
        self.categoryModel.appendRow(generator)
        self.right_layout.addWidget(self.generatorPage)

        self.initCheatLayout()
        cheat = QStandardItem("Cheat Menu")
        cheat.setIcon(CONST.ICONS["Cheat"])
        cheat.setEditable(False)
        cheat.setSelectable(True)
        self.categoryModel.appendRow(cheat)
        self.right_layout.addWidget(self.cheatPage)

        self.pluginsPage = PluginsPage()
        plugins = QStandardItem("LUA Plugins")
        plugins.setIcon(CONST.ICONS["Plugins"])
        plugins.setEditable(False)
        plugins.setSelectable(True)
        self.categoryModel.appendRow(plugins)
        self.right_layout.addWidget(self.pluginsPage)

        self.pluginsOptionsPage = PluginOptionsPage()
        pluginsOptions = QStandardItem("LUA Plugins Options")
        pluginsOptions.setIcon(CONST.ICONS["PluginsOptions"])
        pluginsOptions.setEditable(False)
        pluginsOptions.setSelectable(True)
        self.categoryModel.appendRow(pluginsOptions)
        self.right_layout.addWidget(self.pluginsOptionsPage)

        self.categoryList.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.categoryList.setModel(self.categoryModel)
        self.categoryList.selectionModel().setCurrentIndex(
            self.categoryList.indexAt(QPoint(1, 1)),
            QItemSelectionModel.Select)
        self.categoryList.selectionModel().selectionChanged.connect(
            self.onSelectionChanged)

        self.layout.addWidget(self.categoryList, 0, 0, 1, 1)
        self.layout.addLayout(self.right_layout, 0, 1, 5, 1)

        self.setLayout(self.layout)

    def init(self):
        pass

    def initDifficultyLayout(self):

        self.difficultyPage = QWidget()
        self.difficultyLayout = QGridLayout()
        self.difficultyLayout.setAlignment(Qt.AlignTop)
        self.difficultyPage.setLayout(self.difficultyLayout)

        self.playerCoalitionSkill = QComboBox()
        self.enemyCoalitionSkill = QComboBox()
        self.enemyAASkill = QComboBox()
        for skill in CONST.SKILL_OPTIONS:
            self.playerCoalitionSkill.addItem(skill)
            self.enemyCoalitionSkill.addItem(skill)
            self.enemyAASkill.addItem(skill)

        self.playerCoalitionSkill.setCurrentIndex(
            CONST.SKILL_OPTIONS.index(self.game.settings.player_skill))
        self.enemyCoalitionSkill.setCurrentIndex(
            CONST.SKILL_OPTIONS.index(self.game.settings.enemy_skill))
        self.enemyAASkill.setCurrentIndex(
            CONST.SKILL_OPTIONS.index(self.game.settings.enemy_vehicle_skill))

        self.playerCoalitionSkill.currentIndexChanged.connect(
            self.applySettings)
        self.enemyCoalitionSkill.currentIndexChanged.connect(
            self.applySettings)
        self.enemyAASkill.currentIndexChanged.connect(self.applySettings)

        self.difficultyLayout.addWidget(QLabel("Player coalition skill"), 0, 0)
        self.difficultyLayout.addWidget(self.playerCoalitionSkill, 0, 1,
                                        Qt.AlignRight)
        self.difficultyLayout.addWidget(QLabel("Enemy skill"), 1, 0)
        self.difficultyLayout.addWidget(self.enemyCoalitionSkill, 1, 1,
                                        Qt.AlignRight)
        self.difficultyLayout.addWidget(QLabel("Enemy AA and vehicles skill"),
                                        2, 0)
        self.difficultyLayout.addWidget(self.enemyAASkill, 2, 1, Qt.AlignRight)

        self.difficultyLabel = QComboBox()
        [self.difficultyLabel.addItem(t) for t in CONST.LABELS_OPTIONS]
        self.difficultyLabel.setCurrentIndex(
            CONST.LABELS_OPTIONS.index(self.game.settings.labels))
        self.difficultyLabel.currentIndexChanged.connect(self.applySettings)

        self.difficultyLayout.addWidget(QLabel("In Game Labels"), 3, 0)
        self.difficultyLayout.addWidget(self.difficultyLabel, 3, 1,
                                        Qt.AlignRight)

        self.noNightMission = QCheckBox()
        self.noNightMission.setChecked(self.game.settings.night_disabled)
        self.noNightMission.toggled.connect(self.applySettings)
        self.difficultyLayout.addWidget(QLabel("No night missions"), 4, 0)
        self.difficultyLayout.addWidget(self.noNightMission, 4, 1,
                                        Qt.AlignRight)

        self.mapVisibiitySelection = QComboBox()
        self.mapVisibiitySelection.addItem("All", ForcedOptions.Views.All)
        if self.game.settings.map_coalition_visibility == ForcedOptions.Views.All:
            self.mapVisibiitySelection.setCurrentIndex(0)
        self.mapVisibiitySelection.addItem("Fog of War",
                                           ForcedOptions.Views.Allies)
        if self.game.settings.map_coalition_visibility == ForcedOptions.Views.Allies:
            self.mapVisibiitySelection.setCurrentIndex(1)
        self.mapVisibiitySelection.addItem("Allies Only",
                                           ForcedOptions.Views.OnlyAllies)
        if self.game.settings.map_coalition_visibility == ForcedOptions.Views.OnlyAllies:
            self.mapVisibiitySelection.setCurrentIndex(2)
        self.mapVisibiitySelection.addItem("Own Aircraft Only",
                                           ForcedOptions.Views.MyAircraft)
        if self.game.settings.map_coalition_visibility == ForcedOptions.Views.MyAircraft:
            self.mapVisibiitySelection.setCurrentIndex(3)
        self.mapVisibiitySelection.addItem("Map Only",
                                           ForcedOptions.Views.OnlyMap)
        if self.game.settings.map_coalition_visibility == ForcedOptions.Views.OnlyMap:
            self.mapVisibiitySelection.setCurrentIndex(4)
        self.mapVisibiitySelection.currentIndexChanged.connect(
            self.applySettings)
        self.difficultyLayout.addWidget(QLabel("Map visibility options"), 5, 0)
        self.difficultyLayout.addWidget(self.mapVisibiitySelection, 5, 1,
                                        Qt.AlignRight)

        self.ext_views = QCheckBox()
        self.ext_views.setChecked(self.game.settings.external_views_allowed)
        self.ext_views.toggled.connect(self.applySettings)
        self.difficultyLayout.addWidget(QLabel("Allow external views"), 6, 0)
        self.difficultyLayout.addWidget(self.ext_views, 6, 1, Qt.AlignRight)

    def initGeneratorLayout(self):
        self.generatorPage = QWidget()
        self.generatorLayout = QVBoxLayout()
        self.generatorLayout.setAlignment(Qt.AlignTop)
        self.generatorPage.setLayout(self.generatorLayout)

        self.gameplay = QGroupBox("Gameplay")
        self.gameplayLayout = QGridLayout()
        self.gameplayLayout.setAlignment(Qt.AlignTop)
        self.gameplay.setLayout(self.gameplayLayout)

        self.supercarrier = QCheckBox()
        self.supercarrier.setChecked(self.game.settings.supercarrier)
        self.supercarrier.toggled.connect(self.applySettings)

        self.generate_marks = QCheckBox()
        self.generate_marks.setChecked(self.game.settings.generate_marks)
        self.generate_marks.toggled.connect(self.applySettings)

        self.never_delay_players = QCheckBox()
        self.never_delay_players.setChecked(
            self.game.settings.never_delay_player_flights)
        self.never_delay_players.toggled.connect(self.applySettings)
        self.never_delay_players.setToolTip(
            "When checked, player flights with a delayed start time will be "
            "spawned immediately. AI wingmen may begin startup immediately.")

        self.gameplayLayout.addWidget(QLabel("Use Supercarrier Module"), 0, 0)
        self.gameplayLayout.addWidget(self.supercarrier, 0, 1, Qt.AlignRight)
        self.gameplayLayout.addWidget(QLabel("Put Objective Markers on Map"),
                                      1, 0)
        self.gameplayLayout.addWidget(self.generate_marks, 1, 1, Qt.AlignRight)
        self.gameplayLayout.addWidget(QLabel("Never delay player flights"), 2,
                                      0)
        self.gameplayLayout.addWidget(self.never_delay_players, 2, 1,
                                      Qt.AlignRight)

        self.performance = QGroupBox("Performance")
        self.performanceLayout = QGridLayout()
        self.performanceLayout.setAlignment(Qt.AlignTop)
        self.performance.setLayout(self.performanceLayout)

        self.smoke = QCheckBox()
        self.smoke.setChecked(self.game.settings.perf_smoke_gen)
        self.smoke.toggled.connect(self.applySettings)

        self.red_alert = QCheckBox()
        self.red_alert.setChecked(self.game.settings.perf_red_alert_state)
        self.red_alert.toggled.connect(self.applySettings)

        self.arti = QCheckBox()
        self.arti.setChecked(self.game.settings.perf_artillery)
        self.arti.toggled.connect(self.applySettings)

        self.moving_units = QCheckBox()
        self.moving_units.setChecked(self.game.settings.perf_moving_units)
        self.moving_units.toggled.connect(self.applySettings)

        self.infantry = QCheckBox()
        self.infantry.setChecked(self.game.settings.perf_infantry)
        self.infantry.toggled.connect(self.applySettings)

        self.ai_parking_start = QCheckBox()
        self.ai_parking_start.setChecked(
            self.game.settings.perf_ai_parking_start)
        self.ai_parking_start.toggled.connect(self.applySettings)

        self.destroyed_units = QCheckBox()
        self.destroyed_units.setChecked(
            self.game.settings.perf_destroyed_units)
        self.destroyed_units.toggled.connect(self.applySettings)

        self.culling = QCheckBox()
        self.culling.setChecked(self.game.settings.perf_culling)
        self.culling.toggled.connect(self.applySettings)

        self.culling_distance = QSpinBox()
        self.culling_distance.setMinimum(50)
        self.culling_distance.setMaximum(10000)
        self.culling_distance.setValue(
            self.game.settings.perf_culling_distance)
        self.culling_distance.valueChanged.connect(self.applySettings)

        self.performanceLayout.addWidget(
            QLabel("Smoke visual effect on frontline"), 0, 0)
        self.performanceLayout.addWidget(self.smoke,
                                         0,
                                         1,
                                         alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(
            QLabel("SAM starts in RED alert mode"), 1, 0)
        self.performanceLayout.addWidget(self.red_alert,
                                         1,
                                         1,
                                         alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(QLabel("Artillery strikes"), 2, 0)
        self.performanceLayout.addWidget(self.arti,
                                         2,
                                         1,
                                         alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(QLabel("Moving ground units"), 3, 0)
        self.performanceLayout.addWidget(self.moving_units,
                                         3,
                                         1,
                                         alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(
            QLabel("Generate infantry squads along vehicles"), 4, 0)
        self.performanceLayout.addWidget(self.infantry,
                                         4,
                                         1,
                                         alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(
            QLabel(
                "AI planes parking start (AI starts in flight if disabled)"),
            5, 0)
        self.performanceLayout.addWidget(self.ai_parking_start,
                                         5,
                                         1,
                                         alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(
            QLabel("Include destroyed units carcass"), 6, 0)
        self.performanceLayout.addWidget(self.destroyed_units,
                                         6,
                                         1,
                                         alignment=Qt.AlignRight)

        self.performanceLayout.addWidget(QHorizontalSeparationLine(), 7, 0, 1,
                                         2)
        self.performanceLayout.addWidget(
            QLabel("Culling of distant units enabled"), 8, 0)
        self.performanceLayout.addWidget(self.culling,
                                         8,
                                         1,
                                         alignment=Qt.AlignRight)
        self.performanceLayout.addWidget(QLabel("Culling distance (km)"), 9, 0)
        self.performanceLayout.addWidget(self.culling_distance,
                                         9,
                                         1,
                                         alignment=Qt.AlignRight)

        self.generatorLayout.addWidget(self.gameplay)
        self.generatorLayout.addWidget(
            QLabel(
                "Disabling settings below may improve performance, but will impact the overall quality of the experience."
            ))
        self.generatorLayout.addWidget(self.performance)

    def initCheatLayout(self):

        self.cheatPage = QWidget()
        self.cheatLayout = QVBoxLayout()
        self.cheatPage.setLayout(self.cheatLayout)

        self.cheat_options = CheatSettingsBox(self.game, self.applySettings)
        self.cheatLayout.addWidget(self.cheat_options)

        self.moneyCheatBox = QGroupBox("Money Cheat")
        self.moneyCheatBox.setAlignment(Qt.AlignTop)
        self.moneyCheatBoxLayout = QGridLayout()
        self.moneyCheatBox.setLayout(self.moneyCheatBoxLayout)

        cheats_amounts = [25, 50, 100, 200, 500, 1000, -25, -50, -100, -200]
        for i, amount in enumerate(cheats_amounts):
            if amount > 0:
                btn = QPushButton("Cheat +" + str(amount) + "M")
                btn.setProperty("style", "btn-success")
            else:
                btn = QPushButton("Cheat " + str(amount) + "M")
                btn.setProperty("style", "btn-danger")
            btn.clicked.connect(self.cheatLambda(amount))
            self.moneyCheatBoxLayout.addWidget(btn, i / 2, i % 2)
        self.cheatLayout.addWidget(self.moneyCheatBox, stretch=1)

    def cheatLambda(self, amount):
        return lambda: self.cheatMoney(amount)

    def cheatMoney(self, amount):
        logging.info("CHEATING FOR AMOUNT : " + str(amount) + "M")
        self.game.budget += amount
        if amount > 0:
            self.game.informations.append(
                Information("CHEATER",
                            "You are a cheater and you should feel bad",
                            self.game.turn))
        else:
            self.game.informations.append(
                Information("CHEATER", "You are still a cheater !",
                            self.game.turn))
        GameUpdateSignal.get_instance().updateGame(self.game)

    def applySettings(self):
        self.game.settings.player_skill = CONST.SKILL_OPTIONS[
            self.playerCoalitionSkill.currentIndex()]
        self.game.settings.enemy_skill = CONST.SKILL_OPTIONS[
            self.enemyCoalitionSkill.currentIndex()]
        self.game.settings.enemy_vehicle_skill = CONST.SKILL_OPTIONS[
            self.enemyAASkill.currentIndex()]
        self.game.settings.labels = CONST.LABELS_OPTIONS[
            self.difficultyLabel.currentIndex()]
        self.game.settings.night_disabled = self.noNightMission.isChecked()
        self.game.settings.map_coalition_visibility = self.mapVisibiitySelection.currentData(
        )
        self.game.settings.external_views_allowed = self.ext_views.isChecked()
        self.game.settings.generate_marks = self.generate_marks.isChecked()
        self.game.settings.never_delay_player_flights = self.never_delay_players.isChecked(
        )

        self.game.settings.supercarrier = self.supercarrier.isChecked()

        self.game.settings.perf_red_alert_state = self.red_alert.isChecked()
        self.game.settings.perf_smoke_gen = self.smoke.isChecked()
        self.game.settings.perf_artillery = self.arti.isChecked()
        self.game.settings.perf_moving_units = self.moving_units.isChecked()
        self.game.settings.perf_infantry = self.infantry.isChecked()
        self.game.settings.perf_ai_parking_start = self.ai_parking_start.isChecked(
        )
        self.game.settings.perf_destroyed_units = self.destroyed_units.isChecked(
        )

        self.game.settings.perf_culling = self.culling.isChecked()
        self.game.settings.perf_culling_distance = int(
            self.culling_distance.value())

        self.game.settings.show_red_ato = self.cheat_options.show_red_ato

        GameUpdateSignal.get_instance().updateGame(self.game)

    def onSelectionChanged(self):
        index = self.categoryList.selectionModel().currentIndex().row()
        self.right_layout.setCurrentIndex(index)
Exemplo n.º 47
0
    def _setupUI(self):
        self.setWindowTitle("Export Attributes to USD")
        layout = QVBoxLayout()

        # This section contains the attributes tagged for export.
        label = QLabel()
        label.setText('Exported Attributes:')
        layout.addWidget(label)

        self.exportedAttrsModel = ExportedAttributesModel()
        self.exportedAttrsView = ExportedAttributesView()
        self.exportedAttrsView.verticalHeader().hide()
        self.exportedAttrsView.setModel(self.exportedAttrsModel)
        selectionModel = self.exportedAttrsView.selectionModel()
        selectionModel.selectionChanged.connect(
            self._onExportedAttrsSelectionChanged)
        self.exportedAttrsModel.dataChanged.connect(self._onModelDataChanged)
        layout.addWidget(self.exportedAttrsView)

        self.removeExportedAttrButton = QPushButton(
            "Remove Exported Attribute")
        self.removeExportedAttrButton.clicked.connect(
            self._onRemoveExportedAttrPressed)
        self.removeExportedAttrButton.setEnabled(False)
        layout.addWidget(self.removeExportedAttrButton)

        # This section contains the attributes available for export.
        label = QLabel()
        label.setText('Available Attributes:')
        layout.addWidget(label)

        self.userDefinedCheckBox = QCheckBox('User Defined')
        self.userDefinedCheckBox.setToolTip(
            'Show only user-defined (dynamic) attributes')
        self.userDefinedCheckBox.setChecked(True)
        self.userDefinedCheckBox.stateChanged.connect(self._syncUI)
        layout.addWidget(self.userDefinedCheckBox)

        self.addAttrsModel = AddAttributesModel()
        self.addAttrsView = AddAttributesView()
        self.addAttrsView.setModel(self.addAttrsModel)
        selectionModel = self.addAttrsView.selectionModel()
        selectionModel.selectionChanged.connect(
            self._onAddAttrsSelectionChanged)
        self.addAttrsModel.dataChanged.connect(self._onModelDataChanged)
        layout.addWidget(self.addAttrsView)

        self.addExportedAttrButton = QPushButton("Add Exported Attribute")
        self.addExportedAttrButton.clicked.connect(
            self._onAddExportedAttrPressed)
        self.addExportedAttrButton.setEnabled(False)
        layout.addWidget(self.addExportedAttrButton)

        self.setLayout(layout)
Exemplo n.º 48
0
    def __init__(self, mode, parentQWidget = None):
        QVBoxLayout.__init__(self)

        self.sig.connect(self.addThreadList)
        self.mode = mode

        self.sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)

        self.groupBoxSearch = QGroupBox()
        self.groupBoxSearch.setStyleSheet("QGroupBox {border: 1px solid gray; border-radius: 4px; };")
        vboxSearch = QVBoxLayout()
        self.searchTitle = QLabel("Search Messages")
        vboxSearch.addWidget(self.searchTitle)
        self.searchHLayout = QHBoxLayout()
        self.editTextSearch = QTextEdit('')
        self.editTextSearch.setFixedSize(200,30)
        self.buttonSearch = QPushButton('Search')
        self.buttonSearch.setFixedSize(100,30)
        self.buttonSearch.clicked.connect(self.searchMsg)
        vboxSearch.addWidget(self.editTextSearch)
        self.searchHLayout.addWidget(self.buttonSearch)
        self.searchCursor = QLabel()
        self.searchHLayout.addWidget(self.searchCursor)
        vboxSearch.addLayout(self.searchHLayout)
        self.browseHLayout = QHBoxLayout()
        self.buttonLookUp = QPushButton('\u21e7')  #Arrow up
        self.buttonLookUp.setFixedWidth(100)
        self.buttonLookUp.clicked.connect(self.moveToPrev)
        self.buttonLookDown = QPushButton('\u21e9') #Arrow down
        self.buttonLookDown.setFixedWidth(100)
        self.buttonLookDown.clicked.connect(self.moveToNext)
        self.browseHLayout.addWidget(self.buttonLookUp)
        self.browseHLayout.addWidget(self.buttonLookDown)
        vboxSearch.addLayout(self.browseHLayout)
        self.groupBoxSearch.setLayout(vboxSearch)
        self.addWidget(self.groupBoxSearch)
        self.groupBoxSearch.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))

        self.buttonHiddenLifelines = QPushButton('Show hidden life-lines')
        self.buttonHiddenLifelines.setFixedWidth(200)
        self.buttonHiddenLifelines.clicked.connect(self.showHiddenLifelines)
        self.addWidget(self.buttonHiddenLifelines)

        self.buttonHiddenMessages = QPushButton('Show hidden Messages')
        self.buttonHiddenMessages.setFixedWidth(200)
        self.buttonHiddenMessages.clicked.connect(self.showHiddenMessages)
        self.addWidget(self.buttonHiddenMessages)

        if const.mode_interactive == mode:
            self.buttonCapture = QPushButton('Capture')
            self.buttonCapture.setFixedWidth(200)
            self.buttonCapture.clicked.connect(self.notifyCapture)
            self.addWidget(self.buttonCapture)
        self.msgRcv = []
        self.msgInfo = QLabel("Message Info.")
        self.groupBoxMessageInfo = QGroupBox()
        self.groupBoxMessageInfo.setStyleSheet("QGroupBox {border: 1px solid gray; border-radius: 9px; margin-top: 0.5em} QGroupBox::title {subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px;")
        vbox = QVBoxLayout()
        vbox.addWidget(self.msgInfo)
        self.tableTime = QTableWidget(3,2)
        self.tableTime.setHorizontalHeaderLabels(['-','time'])
        self.tableTime.setColumnWidth(0,80)
        self.tableTime.setColumnWidth(1,150)
        vwidth = self.tableTime.verticalHeader().length()
        hwidth = self.tableTime.horizontalHeader().height()
        fwidth = self.tableTime.frameWidth() * 2
        self.tableTime.setFixedHeight(vwidth + hwidth + fwidth)
        self.tableTime.horizontalHeader().setStretchLastSection(True)
        self.tableTime.setItem(0,0,QTableWidgetItem('begin'))
        self.tableTime.setItem(0,1,QTableWidgetItem(' - '))
        self.tableTime.setItem(1,0,QTableWidgetItem('end'))
        self.tableTime.setItem(1,1,QTableWidgetItem(' - '))
        self.tableTime.setItem(2,0,QTableWidgetItem('duration'))
        self.tableTime.setItem(2,1,QTableWidgetItem(' - '))
        vbox.addWidget(self.tableTime)

        self.titleArg = QLabel('Argument List')
        vbox.addWidget(self.titleArg)

        max_arg_num = 10
        self.tableArgs = QTableWidget(max_arg_num,2)
        self.tableArgs.setHorizontalHeaderLabels(['type','value'])
        for idx in range(0,max_arg_num):
            self.tableArgs.setItem(idx,0,QTableWidgetItem())
            self.tableArgs.setItem(idx,1,QTableWidgetItem())
        self.tableArgs.horizontalHeader().setStretchLastSection(True)
        vbox.addWidget(self.tableArgs)

        self.titleArg = QLabel('Return Value List')
        vbox.addWidget(self.titleArg)

        max_ret_num = 4
        self.tableRet = QTableWidget(max_ret_num,2)
        self.tableRet.setHorizontalHeaderLabels(['type','value'])
        for idx in range(0,max_ret_num):
            self.tableRet.setItem(idx,0,QTableWidgetItem())
            self.tableRet.setItem(idx,1,QTableWidgetItem())
        self.tableRet.horizontalHeader().setStretchLastSection(True)
        vwidth = self.tableRet.verticalHeader().length()
        hwidth = self.tableRet.horizontalHeader().height()
        fwidth = self.tableRet.frameWidth() * 2
        self.tableRet.setFixedHeight(vwidth + hwidth + fwidth)
        vbox.addWidget(self.tableRet)

        self.buttonSrcView = QPushButton('view code')
        self.buttonSrcView.setFixedWidth(200)
        self.buttonSrcView.clicked.connect(self.openSourceViewer)
        self.buttonHide = QPushButton('Hide')
        self.buttonHide.setFixedWidth(200)
        self.buttonHide.clicked.connect(self.notifyHide)
        self.buttonHideAllMsg = QPushButton('Hide All')
        self.buttonHideAllMsg.setFixedWidth(200)
        self.buttonHideAllMsg.clicked.connect(self.hideAllMsgNamedAsSelected)
        self.groupBoxMessageInfo.setLayout(vbox)
        self.checkHideCircular = QCheckBox('Hide Circular Messages')
        self.checkHideCircular.setCheckState(QtCore.Qt.Unchecked)
        self.checkHideCircular.stateChanged.connect(self.changeHideCircularMessage)
        self.addWidget(self.checkHideCircular)
        self.addWidget(self.groupBoxMessageInfo)
        self.groupBoxMessageInfo.setSizePolicy(self.sizePolicy)
Exemplo n.º 49
0
    def __init__(self, parent, db_mngr, *db_maps):
        """Initialize class.

        Args:
            parent (DataStoreForm)
            db_mngr (SpineDBManager)
            db_maps (DiffDatabaseMapping): the dbs to select items from
        """
        super().__init__(parent)
        self.db_mngr = db_mngr
        self.db_maps = db_maps
        top_widget = QWidget()
        top_layout = QHBoxLayout(top_widget)
        db_maps_group_box = QGroupBox("Databases", top_widget)
        db_maps_layout = QVBoxLayout(db_maps_group_box)
        db_maps_layout.setContentsMargins(self._MARGIN, self._MARGIN, self._MARGIN, self._MARGIN)
        self.db_map_check_boxes = {db_map: QCheckBox(db_map.codename, db_maps_group_box) for db_map in self.db_maps}
        for check_box in self.db_map_check_boxes.values():
            check_box.stateChanged.connect(lambda _: QTimer.singleShot(0, self._set_item_check_box_enabled))
            check_box.setChecked(True)
            db_maps_layout.addWidget(check_box)
        items_group_box = QGroupBox("Items", top_widget)
        items_layout = QVBoxLayout(items_group_box)
        items_layout.setContentsMargins(self._MARGIN, self._MARGIN, self._MARGIN, self._MARGIN)
        self.item_check_boxes = {item_type: QCheckBox(item_type, items_group_box) for item_type in self._ITEM_TYPES}
        for check_box in self.item_check_boxes.values():
            check_box.stateChanged.connect(lambda _: QTimer.singleShot(0, self._set_item_check_box_states_in_cascade))
            items_layout.addWidget(check_box)
        top_layout.addWidget(db_maps_group_box)
        top_layout.addWidget(items_group_box)
        button_box = QDialogButtonBox(self)
        button_box.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok)
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        layout = QVBoxLayout(self)
        layout.addWidget(top_widget)
        layout.addWidget(button_box)
        layout.setContentsMargins(self._MARGIN, self._MARGIN, self._MARGIN, self._MARGIN)
        self.setAttribute(Qt.WA_DeleteOnClose)
Exemplo n.º 50
0
class ToolBox(QVBoxLayout):

    sig = QtCore.Signal(object)
    listThread = None
    groupBoxThreadInfo = None
    threadvbox = None
    mode = None

    def __init__(self, mode, parentQWidget = None):
        QVBoxLayout.__init__(self)

        self.sig.connect(self.addThreadList)
        self.mode = mode

        self.sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)

        self.groupBoxSearch = QGroupBox()
        self.groupBoxSearch.setStyleSheet("QGroupBox {border: 1px solid gray; border-radius: 4px; };")
        vboxSearch = QVBoxLayout()
        self.searchTitle = QLabel("Search Messages")
        vboxSearch.addWidget(self.searchTitle)
        self.searchHLayout = QHBoxLayout()
        self.editTextSearch = QTextEdit('')
        self.editTextSearch.setFixedSize(200,30)
        self.buttonSearch = QPushButton('Search')
        self.buttonSearch.setFixedSize(100,30)
        self.buttonSearch.clicked.connect(self.searchMsg)
        vboxSearch.addWidget(self.editTextSearch)
        self.searchHLayout.addWidget(self.buttonSearch)
        self.searchCursor = QLabel()
        self.searchHLayout.addWidget(self.searchCursor)
        vboxSearch.addLayout(self.searchHLayout)
        self.browseHLayout = QHBoxLayout()
        self.buttonLookUp = QPushButton('\u21e7')  #Arrow up
        self.buttonLookUp.setFixedWidth(100)
        self.buttonLookUp.clicked.connect(self.moveToPrev)
        self.buttonLookDown = QPushButton('\u21e9') #Arrow down
        self.buttonLookDown.setFixedWidth(100)
        self.buttonLookDown.clicked.connect(self.moveToNext)
        self.browseHLayout.addWidget(self.buttonLookUp)
        self.browseHLayout.addWidget(self.buttonLookDown)
        vboxSearch.addLayout(self.browseHLayout)
        self.groupBoxSearch.setLayout(vboxSearch)
        self.addWidget(self.groupBoxSearch)
        self.groupBoxSearch.setSizePolicy(QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed))

        self.buttonHiddenLifelines = QPushButton('Show hidden life-lines')
        self.buttonHiddenLifelines.setFixedWidth(200)
        self.buttonHiddenLifelines.clicked.connect(self.showHiddenLifelines)
        self.addWidget(self.buttonHiddenLifelines)

        self.buttonHiddenMessages = QPushButton('Show hidden Messages')
        self.buttonHiddenMessages.setFixedWidth(200)
        self.buttonHiddenMessages.clicked.connect(self.showHiddenMessages)
        self.addWidget(self.buttonHiddenMessages)

        if const.mode_interactive == mode:
            self.buttonCapture = QPushButton('Capture')
            self.buttonCapture.setFixedWidth(200)
            self.buttonCapture.clicked.connect(self.notifyCapture)
            self.addWidget(self.buttonCapture)
        self.msgRcv = []
        self.msgInfo = QLabel("Message Info.")
        self.groupBoxMessageInfo = QGroupBox()
        self.groupBoxMessageInfo.setStyleSheet("QGroupBox {border: 1px solid gray; border-radius: 9px; margin-top: 0.5em} QGroupBox::title {subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px;")
        vbox = QVBoxLayout()
        vbox.addWidget(self.msgInfo)
        self.tableTime = QTableWidget(3,2)
        self.tableTime.setHorizontalHeaderLabels(['-','time'])
        self.tableTime.setColumnWidth(0,80)
        self.tableTime.setColumnWidth(1,150)
        vwidth = self.tableTime.verticalHeader().length()
        hwidth = self.tableTime.horizontalHeader().height()
        fwidth = self.tableTime.frameWidth() * 2
        self.tableTime.setFixedHeight(vwidth + hwidth + fwidth)
        self.tableTime.horizontalHeader().setStretchLastSection(True)
        self.tableTime.setItem(0,0,QTableWidgetItem('begin'))
        self.tableTime.setItem(0,1,QTableWidgetItem(' - '))
        self.tableTime.setItem(1,0,QTableWidgetItem('end'))
        self.tableTime.setItem(1,1,QTableWidgetItem(' - '))
        self.tableTime.setItem(2,0,QTableWidgetItem('duration'))
        self.tableTime.setItem(2,1,QTableWidgetItem(' - '))
        vbox.addWidget(self.tableTime)

        self.titleArg = QLabel('Argument List')
        vbox.addWidget(self.titleArg)

        max_arg_num = 10
        self.tableArgs = QTableWidget(max_arg_num,2)
        self.tableArgs.setHorizontalHeaderLabels(['type','value'])
        for idx in range(0,max_arg_num):
            self.tableArgs.setItem(idx,0,QTableWidgetItem())
            self.tableArgs.setItem(idx,1,QTableWidgetItem())
        self.tableArgs.horizontalHeader().setStretchLastSection(True)
        vbox.addWidget(self.tableArgs)

        self.titleArg = QLabel('Return Value List')
        vbox.addWidget(self.titleArg)

        max_ret_num = 4
        self.tableRet = QTableWidget(max_ret_num,2)
        self.tableRet.setHorizontalHeaderLabels(['type','value'])
        for idx in range(0,max_ret_num):
            self.tableRet.setItem(idx,0,QTableWidgetItem())
            self.tableRet.setItem(idx,1,QTableWidgetItem())
        self.tableRet.horizontalHeader().setStretchLastSection(True)
        vwidth = self.tableRet.verticalHeader().length()
        hwidth = self.tableRet.horizontalHeader().height()
        fwidth = self.tableRet.frameWidth() * 2
        self.tableRet.setFixedHeight(vwidth + hwidth + fwidth)
        vbox.addWidget(self.tableRet)

        self.buttonSrcView = QPushButton('view code')
        self.buttonSrcView.setFixedWidth(200)
        self.buttonSrcView.clicked.connect(self.openSourceViewer)
        self.buttonHide = QPushButton('Hide')
        self.buttonHide.setFixedWidth(200)
        self.buttonHide.clicked.connect(self.notifyHide)
        self.buttonHideAllMsg = QPushButton('Hide All')
        self.buttonHideAllMsg.setFixedWidth(200)
        self.buttonHideAllMsg.clicked.connect(self.hideAllMsgNamedAsSelected)
        self.groupBoxMessageInfo.setLayout(vbox)
        self.checkHideCircular = QCheckBox('Hide Circular Messages')
        self.checkHideCircular.setCheckState(QtCore.Qt.Unchecked)
        self.checkHideCircular.stateChanged.connect(self.changeHideCircularMessage)
        self.addWidget(self.checkHideCircular)
        self.addWidget(self.groupBoxMessageInfo)
        self.groupBoxMessageInfo.setSizePolicy(self.sizePolicy)

    def reset(self):
        for idx in reversed(range(0,self.listThread.count())):
            self.listThread.takeItem(idx)

    def setMsgInfoMessage(self,msg):
        self.strMessage = msg

    def changeHideCircularMessage(self,state):
        if state == QtCore.Qt.Unchecked:
            self.diagramView.hideCircularChanged(False)
        elif state == QtCore.Qt.Checked:
            self.diagramView.hideCircularChanged(True)
    
    def setMsgInfoModule(self,module):
        self.strModule = module

    def updateSearchStatus(self,curr,number):
        self.searchCursor.setText("%d/%d" % (curr,number))

    def connectSourceViewer(self,viewer):
        self.srcViewer = viewer

    def openSourceViewer(self):
        self.srcViewer.openViewer(self.strModule,self.strMessage)

    def setMessageInfoTime(self,begin,end,duration):
        self.tableTime.item(0,1).setText(begin)
        self.tableTime.item(1,1).setText(end)
        self.tableTime.item(2,1).setText(duration + ' msec')

    def setMessageInfoArg(self,listParam,listArg):
        # Clear the contents in the table
        max_arg_num = 10
        for idx in range(0,max_arg_num):
            self.tableArgs.item(idx,0).setText('')
            self.tableArgs.item(idx,1).setText('')

        if listArg:
            for idx, text in enumerate(listArg):
                self.tableArgs.item(idx,1).setText(text)
            for idx, text in enumerate(listParam):
                self.tableArgs.item(idx,0).setText(text)
        else:
            for idx in range(0,self.tableArgs.rowCount()):
                self.tableArgs.item(idx,1).setText('')
                self.tableArgs.item(idx,0).setText('')

    def setMessageInfoRet(self,listRet):
        if listRet:
            for idx, text in enumerate(listRet):
                self.tableRet.item(idx,1).setText(text)
        else:
            for idx in range(0,self.tableRet.rowCount()):
                self.tableRet.item(idx,1).setText('')
                self.tableRet.item(idx,0).setText('')

    def notifyInteractiveStateChanged(self,state):
        if const.mode_interactive != self.mode:
            return

        if const.STATE_INTERACTIVE_CAPTURING == state:
            self.buttonCapture.setEnabled(True)
            self.buttonCapture.setText('Stop Capture')
        if const.STATE_INTERACTIVE_PROCESSING == state:
            self.buttonCapture.setEnabled(False)
        if const.STATE_INTERACTIVE_IDLE == state:
            self.buttonCapture.setEnabled(True)
            self.buttonCapture.setText('Capture')
        if const.STATE_INTERACTIVE_RESET == state:
            self.buttonCapture.setEnabled(True)
            self.buttonCapture.setText('Capture')
        elif const.STATE_INTERACTIVE_ACTIVE == state:
            self.buttonCapture.setEnabled(True)
            self.buttonCapture.setText('Capture')

    def setMessageInfo(self,info):
        self.msgInfo.setText(info)

    def setAvailable(self,threads):
        self.sig.emit(threads)

    def toggleThreadDisplay(self,item):
        print(self.listThread.currentRow())
        #if item.isSelected():
        #    print(item.text() + "  is selected")
        #else:
        #    print(item.text() + "  is not selected")
        self.diagramView.showThread(self.listThread.currentRow(),item.isSelected())

    def hideAllMsgNamedAsSelected(self):
        self.diagramView.hideAllMessageSelected()

    def addThreadList(self,threads):

        if not self.groupBoxThreadInfo:
            self.groupBoxThreadInfo = QGroupBox()
            self.threadInfo = QLabel("Thread Info.")
            self.groupBoxThreadInfo.setStyleSheet("QGroupBox {border: 1px solid gray; border-radius: 9px; margin-top: 0.5em} QGroupBox::title {subcontrol-origin: margin; left: 10px; padding: 0 3px 0 3px;")

        if not self.threadvbox:
            self.threadvbox = QVBoxLayout()

        if not self.listThread:
            self.listThread = QListWidget()
            
        self.listThread.setFixedWidth(200)
        self.listThread.setSelectionMode(QAbstractItemView.MultiSelection)
        QtCore.QObject.connect(self.listThread, QtCore.SIGNAL("itemClicked(QListWidgetItem *)"), self.toggleThreadDisplay)
        self.threadvbox.addWidget(self.threadInfo)
        self.threadvbox.addWidget(self.listThread)
        self.groupBoxThreadInfo.setLayout(self.threadvbox)
        self.addWidget(self.groupBoxThreadInfo)
        self.groupBoxThreadInfo.setSizePolicy(self.sizePolicy)

        for id in threads:
            item = QListWidgetItem(id)
            self.listThread.addItem(item)

    def connectController(self,controller):
        self.controller = controller
        self.connect(controller,QtCore.SIGNAL('setAvailable()'),self.setAvailable)
       
    def connectDiagramView(self,view):
        self.diagramView = view
 
    def disconnectMsgRcv(self,receiver):
        print("Implement this method !!! disconnectMsgRcv")

    def connectMsgRcv(self,receiver):
        self.msgRcv.append(receiver)

    def notifyHide(self):
        for rcv in self.msgRcv:
            rcv.activateHide(True)

    def showHiddenLifelines(self):
        response, selected_items = HiddenDialog.HiddenDialog.getSelectedItems(self.diagramView.getHiddenLifeLines())
        if response:
            self.diagramView.showLifelines(selected_items)

    def showHiddenMessages(self):
        response, selected_items = HiddenMessageDialog.HiddenMessageDialog.getSelectedItems(self.diagramView.getHiddenMessages(),self.diagramView.getHiddenLifeLines())
        if response:
            if selected_items[3] in self.diagramView.getHiddenLifeLines():
                confirmation = ShowLifeLineDialog.ShowLifeLineDialog.confirmToShowLifeLine(selected_items[3])
                if confirmation:
                    self.diagramView.showLifelines([selected_items[3]])
                    self.diagramView.showMessages(selected_items)
            else:
                self.diagramView.showMessages(selected_items)

    def notifyCapture(self):
        for rcv in self.msgRcv:
            rcv.activateCapture(True)
    
    def moveToPrev(self):
        for rcv in self.msgRcv:
            rcv.moveToPrev()
        
    def moveToNext(self):
        for rcv in self.msgRcv:
            rcv.moveToNext()

    def searchMsg(self):
        str = self.editTextSearch.toPlainText()
        for rcv in self.msgRcv:
            rcv.searchMessage(str)
Exemplo n.º 51
0
class MainWindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.setupUi(self)

        # Setup numbers.
        for n in range(0, 10):
            getattr(self, 'pushButton_n%s' % n).pressed.connect(lambda v=n: self.input_number(v))

        # Setup operations.
        self.pushButton_add.pressed.connect(lambda: self.operation(operator.add))
        self.pushButton_sub.pressed.connect(lambda: self.operation(operator.sub))
        self.pushButton_mul.pressed.connect(lambda: self.operation(operator.mul))
        self.pushButton_div.pressed.connect(lambda: self.operation(operator.truediv))  # operator.div for Python2.7

        self.pushButton_pc.pressed.connect(self.operation_pc)
        self.pushButton_eq.pressed.connect(self.equals)

        # Setup actions
        self.actionReset.triggered.connect(self.reset)
        self.pushButton_ac.pressed.connect(self.reset)

        self.actionExit.triggered.connect(self.close)

        self.pushButton_m.pressed.connect(self.memory_store)
        self.pushButton_mr.pressed.connect(self.memory_recall)

        self.memory = 0
        self.reset()

        self.show()

    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(484, 433)
        self.centralWidget = QWidget(MainWindow)
        sizePolicy = QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.centralWidget.sizePolicy().hasHeightForWidth())
        self.centralWidget.setSizePolicy(sizePolicy)
        self.centralWidget.setObjectName("centralWidget")
        self.verticalLayout_2 = QVBoxLayout(self.centralWidget)
        self.verticalLayout_2.setContentsMargins(11, 11, 11, 11)
        self.verticalLayout_2.setSpacing(6)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.verticalLayout = QVBoxLayout()
        self.verticalLayout.setSpacing(6)
        self.verticalLayout.setObjectName("verticalLayout")
        self.lcdNumber = QLCDNumber(self.centralWidget)
        self.lcdNumber.setDigitCount(10)
        self.lcdNumber.setObjectName("lcdNumber")
        self.verticalLayout.addWidget(self.lcdNumber)
        self.gridLayout = QGridLayout()
        self.gridLayout.setSpacing(6)
        self.gridLayout.setObjectName("gridLayout")
        self.pushButton_n4 = QPushButton(self.centralWidget)
        self.pushButton_n4.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_n4.setFont(font)
        self.pushButton_n4.setStyleSheet("QPushButton {\n"
"color: #1976D2;\n"
"}")
        self.pushButton_n4.setObjectName("pushButton_n4")
        self.gridLayout.addWidget(self.pushButton_n4, 3, 0, 1, 1)
        self.pushButton_n1 = QPushButton(self.centralWidget)
        self.pushButton_n1.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_n1.setFont(font)
        self.pushButton_n1.setStyleSheet("QPushButton {\n"
"color: #1976D2;\n"
"}")
        self.pushButton_n1.setObjectName("pushButton_n1")
        self.gridLayout.addWidget(self.pushButton_n1, 4, 0, 1, 1)
        self.pushButton_n8 = QPushButton(self.centralWidget)
        self.pushButton_n8.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_n8.setFont(font)
        self.pushButton_n8.setStyleSheet("QPushButton {\n"
"color: #1976D2;\n"
"}")
        self.pushButton_n8.setObjectName("pushButton_n8")
        self.gridLayout.addWidget(self.pushButton_n8, 2, 1, 1, 1)
        self.pushButton_mul = QPushButton(self.centralWidget)
        self.pushButton_mul.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(False)
        font.setWeight(50)
        self.pushButton_mul.setFont(font)
        self.pushButton_mul.setObjectName("pushButton_mul")
        self.gridLayout.addWidget(self.pushButton_mul, 2, 3, 1, 1)
        self.pushButton_n7 = QPushButton(self.centralWidget)
        self.pushButton_n7.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_n7.setFont(font)
        self.pushButton_n7.setStyleSheet("QPushButton {\n"
"color: #1976D2;\n"
"}")
        self.pushButton_n7.setObjectName("pushButton_n7")
        self.gridLayout.addWidget(self.pushButton_n7, 2, 0, 1, 1)
        self.pushButton_n6 = QPushButton(self.centralWidget)
        self.pushButton_n6.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_n6.setFont(font)
        self.pushButton_n6.setStyleSheet("QPushButton {\n"
"color: #1976D2;\n"
"}")
        self.pushButton_n6.setObjectName("pushButton_n6")
        self.gridLayout.addWidget(self.pushButton_n6, 3, 2, 1, 1)
        self.pushButton_n5 = QPushButton(self.centralWidget)
        self.pushButton_n5.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_n5.setFont(font)
        self.pushButton_n5.setStyleSheet("QPushButton {\n"
"color: #1976D2;\n"
"}")
        self.pushButton_n5.setObjectName("pushButton_n5")
        self.gridLayout.addWidget(self.pushButton_n5, 3, 1, 1, 1)
        self.pushButton_n0 = QPushButton(self.centralWidget)
        self.pushButton_n0.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_n0.setFont(font)
        self.pushButton_n0.setStyleSheet("QPushButton {\n"
"color: #1976D2;\n"
"}")
        self.pushButton_n0.setObjectName("pushButton_n0")
        self.gridLayout.addWidget(self.pushButton_n0, 5, 0, 1, 1)
        self.pushButton_n2 = QPushButton(self.centralWidget)
        self.pushButton_n2.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_n2.setFont(font)
        self.pushButton_n2.setStyleSheet("QPushButton {\n"
"color: #1976D2;\n"
"}")
        self.pushButton_n2.setObjectName("pushButton_n2")
        self.gridLayout.addWidget(self.pushButton_n2, 4, 1, 1, 1)
        self.pushButton_n9 = QPushButton(self.centralWidget)
        self.pushButton_n9.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_n9.setFont(font)
        self.pushButton_n9.setStyleSheet("QPushButton {\n"
"color: #1976D2;\n"
"}")
        self.pushButton_n9.setObjectName("pushButton_n9")
        self.gridLayout.addWidget(self.pushButton_n9, 2, 2, 1, 1)
        self.pushButton_n3 = QPushButton(self.centralWidget)
        self.pushButton_n3.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_n3.setFont(font)
        self.pushButton_n3.setStyleSheet("QPushButton {\n"
"color: #1976D2;\n"
"}")
        self.pushButton_n3.setObjectName("pushButton_n3")
        self.gridLayout.addWidget(self.pushButton_n3, 4, 2, 1, 1)
        self.pushButton_div = QPushButton(self.centralWidget)
        self.pushButton_div.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(False)
        font.setWeight(50)
        self.pushButton_div.setFont(font)
        self.pushButton_div.setObjectName("pushButton_div")
        self.gridLayout.addWidget(self.pushButton_div, 1, 3, 1, 1)
        self.pushButton_sub = QPushButton(self.centralWidget)
        self.pushButton_sub.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(False)
        font.setWeight(50)
        self.pushButton_sub.setFont(font)
        self.pushButton_sub.setObjectName("pushButton_sub")
        self.gridLayout.addWidget(self.pushButton_sub, 3, 3, 1, 1)
        self.pushButton_add = QPushButton(self.centralWidget)
        self.pushButton_add.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(False)
        font.setWeight(50)
        self.pushButton_add.setFont(font)
        self.pushButton_add.setObjectName("pushButton_add")
        self.gridLayout.addWidget(self.pushButton_add, 4, 3, 1, 1)
        self.pushButton_ac = QPushButton(self.centralWidget)
        self.pushButton_ac.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(False)
        font.setWeight(50)
        self.pushButton_ac.setFont(font)
        self.pushButton_ac.setStyleSheet("QPushButton {\n"
"    color: #f44336;\n"
"}")
        self.pushButton_ac.setObjectName("pushButton_ac")
        self.gridLayout.addWidget(self.pushButton_ac, 1, 0, 1, 1)
        self.pushButton_mr = QPushButton(self.centralWidget)
        self.pushButton_mr.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(False)
        font.setWeight(50)
        self.pushButton_mr.setFont(font)
        self.pushButton_mr.setStyleSheet("QPushButton {\n"
"   color: #FFC107;\n"
"}")
        self.pushButton_mr.setObjectName("pushButton_mr")
        self.gridLayout.addWidget(self.pushButton_mr, 1, 2, 1, 1)
        self.pushButton_m = QPushButton(self.centralWidget)
        self.pushButton_m.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(False)
        font.setWeight(50)
        self.pushButton_m.setFont(font)
        self.pushButton_m.setStyleSheet("QPushButton {\n"
"   color: #FFC107;\n"
"}")
        self.pushButton_m.setObjectName("pushButton_m")
        self.gridLayout.addWidget(self.pushButton_m, 1, 1, 1, 1)
        self.pushButton_pc = QPushButton(self.centralWidget)
        self.pushButton_pc.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(False)
        font.setWeight(50)
        self.pushButton_pc.setFont(font)
        self.pushButton_pc.setObjectName("pushButton_pc")
        self.gridLayout.addWidget(self.pushButton_pc, 5, 1, 1, 1)
        self.pushButton_eq = QPushButton(self.centralWidget)
        self.pushButton_eq.setMinimumSize(QSize(0, 50))
        font = QFont()
        font.setPointSize(27)
        font.setBold(True)
        font.setWeight(75)
        self.pushButton_eq.setFont(font)
        self.pushButton_eq.setStyleSheet("QPushButton {\n"
"color: #4CAF50;\n"
"}")
        self.pushButton_eq.setObjectName("pushButton_eq")
        self.gridLayout.addWidget(self.pushButton_eq, 5, 2, 1, 2)
        self.verticalLayout.addLayout(self.gridLayout)
        self.verticalLayout_2.addLayout(self.verticalLayout)
        MainWindow.setCentralWidget(self.centralWidget)
        self.menuBar = QMenuBar(MainWindow)
        self.menuBar.setGeometry(QRect(0, 0, 484, 22))
        self.menuBar.setObjectName("menuBar")
        self.menuFile = QMenu(self.menuBar)
        self.menuFile.setObjectName("menuFile")
        MainWindow.setMenuBar(self.menuBar)
        self.statusBar = QStatusBar(MainWindow)
        self.statusBar.setObjectName("statusBar")
        MainWindow.setStatusBar(self.statusBar)
        self.actionExit = QAction(MainWindow)
        self.actionExit.setObjectName("actionExit")
        self.actionReset = QAction(MainWindow)
        self.actionReset.setObjectName("actionReset")
        self.menuFile.addAction(self.actionReset)
        self.menuFile.addAction(self.actionExit)
        self.menuBar.addAction(self.menuFile.menuAction())

        self.retranslateUi(MainWindow)
        QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Calculon"))
        self.pushButton_n4.setText(_translate("MainWindow", "4"))
        self.pushButton_n4.setShortcut(_translate("MainWindow", "4"))
        self.pushButton_n1.setText(_translate("MainWindow", "1"))
        self.pushButton_n1.setShortcut(_translate("MainWindow", "1"))
        self.pushButton_n8.setText(_translate("MainWindow", "8"))
        self.pushButton_n8.setShortcut(_translate("MainWindow", "8"))
        self.pushButton_mul.setText(_translate("MainWindow", "x"))
        self.pushButton_mul.setShortcut(_translate("MainWindow", "*"))
        self.pushButton_n7.setText(_translate("MainWindow", "7"))
        self.pushButton_n7.setShortcut(_translate("MainWindow", "7"))
        self.pushButton_n6.setText(_translate("MainWindow", "6"))
        self.pushButton_n6.setShortcut(_translate("MainWindow", "6"))
        self.pushButton_n5.setText(_translate("MainWindow", "5"))
        self.pushButton_n5.setShortcut(_translate("MainWindow", "5"))
        self.pushButton_n0.setText(_translate("MainWindow", "0"))
        self.pushButton_n0.setShortcut(_translate("MainWindow", "0"))
        self.pushButton_n2.setText(_translate("MainWindow", "2"))
        self.pushButton_n2.setShortcut(_translate("MainWindow", "2"))
        self.pushButton_n9.setText(_translate("MainWindow", "9"))
        self.pushButton_n9.setShortcut(_translate("MainWindow", "9"))
        self.pushButton_n3.setText(_translate("MainWindow", "3"))
        self.pushButton_n3.setShortcut(_translate("MainWindow", "3"))
        self.pushButton_div.setText(_translate("MainWindow", "÷"))
        self.pushButton_div.setShortcut(_translate("MainWindow", "/"))
        self.pushButton_sub.setText(_translate("MainWindow", "-"))
        self.pushButton_sub.setShortcut(_translate("MainWindow", "-"))
        self.pushButton_add.setText(_translate("MainWindow", "+"))
        self.pushButton_add.setShortcut(_translate("MainWindow", "+"))
        self.pushButton_ac.setText(_translate("MainWindow", "AC"))
        self.pushButton_ac.setShortcut(_translate("MainWindow", "Esc"))
        self.pushButton_mr.setText(_translate("MainWindow", "MR"))
        self.pushButton_mr.setShortcut(_translate("MainWindow", "R"))
        self.pushButton_m.setText(_translate("MainWindow", "M"))
        self.pushButton_m.setShortcut(_translate("MainWindow", "M"))
        self.pushButton_pc.setText(_translate("MainWindow", "%"))
        self.pushButton_pc.setShortcut(_translate("MainWindow", "%"))
        self.pushButton_eq.setText(_translate("MainWindow", "="))
        self.pushButton_eq.setShortcut(_translate("MainWindow", "Return"))
        self.menuFile.setTitle(_translate("MainWindow", "File"))
        self.actionExit.setText(_translate("MainWindow", "Exit"))
        self.actionExit.setShortcut(_translate("MainWindow", "Ctrl+Q"))
        self.actionReset.setText(_translate("MainWindow", "Reset"))
        self.actionReset.setShortcut(_translate("MainWindow", "Ctrl+R"))


    def display(self):
        self.lcdNumber.display(self.stack[-1])

    def reset(self):
        self.state = READY
        self.stack = [0]
        self.last_operation = None
        self.current_op = None
        self.display()

    def memory_store(self):
        self.memory = self.lcdNumber.value()

    def memory_recall(self):
        self.state = INPUT
        self.stack[-1] = self.memory
        self.display()

    def input_number(self, v):
        if self.state == READY:
            self.state = INPUT
            self.stack[-1] = v
        else:
            self.stack[-1] = self.stack[-1] * 10 + v

        self.display()

    def operation(self, op):
        if self.current_op:  # Complete the current operation
            self.equals()

        self.stack.append(0)
        self.state = INPUT
        self.current_op = op

    def operation_pc(self):
        self.state = INPUT
        self.stack[-1] *= 0.01
        self.display()

    def equals(self):
        # Support to allow '=' to repeat previous operation
        # if no further input has been added.
        if self.state == READY and self.last_operation:
            s, self.current_op = self.last_operation
            self.stack.append(s)

        if self.current_op:
            self.last_operation = self.stack[-1], self.current_op

            try:
                self.stack = [self.current_op(*self.stack)]
            except Exception:
                self.lcdNumber.display('Err')
                self.stack = [0]
            else:
                self.current_op = None
                self.state = READY
                self.display()