コード例 #1
0
ファイル: myclusterui.py プロジェクト: zenotech/MyClusterUI
 def create_spinbox(self, prefix, suffix, option, default=NoDefault,
                    min_=None, max_=None, step=None, tip=None):
     if prefix:
         plabel = QLabel(prefix)
     else:
         plabel = None
     if suffix:
         slabel = QLabel(suffix)
     else:
         slabel = None
     spinbox = QSpinBox()
     if min_ is not None:
         spinbox.setMinimum(min_)
     if max_ is not None:
         spinbox.setMaximum(max_)
     if step is not None:
         spinbox.setSingleStep(step)
     if tip is not None:
         spinbox.setToolTip(tip)
     self.spinboxes[option] = spinbox
     layout = QHBoxLayout()
     for subwidget in (plabel, spinbox, slabel):
         if subwidget is not None:
             layout.addWidget(subwidget)
     layout.addStretch(1)
     layout.setContentsMargins(0, 0, 0, 0)
     widget = QWidget(self)
     widget.setLayout(layout)
     return widget
コード例 #2
0
class DoubleInt(QDialog):
    def __init__(self, cmd, parent=None, text_left='left', text_right='right',
                default1=0, default2=0):
        # cmd is a command which this dialog will call upon OKing.
        # The arguments are cmd(i1, i2), the two chosen ints.
        super(DoubleInt, self).__init__(parent)
        self.tr = text_right
        self.tl = text_left
        self.i1 = 0
        self.i2 = 0
        self.default1 = default1
        self.default2 = default2
        self.cmd = cmd
        self.initUI()

    def initUI(self):
        mainlay = QVBoxLayout()
        btns = QHBoxLayout()
        mainui = QGridLayout()

        mainlay.addLayout(mainui)
        mainlay.addLayout(btns)

        ok = QPushButton('OK')
        ok.clicked.connect(self.ok)
        cancel = QPushButton('Cancel')
        cancel.clicked.connect(self.close)

        btns.addStretch()
        btns.addWidget(ok)
        btns.addWidget(cancel)

        text1 = QLabel(self.tl)
        text2 = QLabel(self.tr)
        self.int1 = QSpinBox()
        self.int1.setMaximum(2048)
        self.int1.setMinimum(128)
        self.int1.setValue(self.default1)
        self.int2 = QSpinBox()
        self.int2.setMaximum(2048)
        self.int2.setMinimum(128)
        self.int2.setValue(self.default2)
        mainui.addWidget(text1, 0, 0)
        mainui.addWidget(text2, 0, 1)
        mainui.addWidget(self.int1, 1, 0)
        mainui.addWidget(self.int2, 1, 1)

        self.setLayout(mainlay)
        self.setGeometry(340, 340, 200, 100)
        self.setWindowTitle('MSH Suite - Double Integer')
        self.show()

    def ok(self):
        self.i1 = int(self.int1.text())
        self.i2 = int(self.int2.text())
        self.cmd(self.i1, self.i2)
        self.close()
コード例 #3
0
class StackSizeCompound(QGroupBox):
  def __init__(self, parent=None):
    super(StackSizeCompound, self).__init__(parent)
    self.setTitle("Stack size")
    self.spinbox_stacksize = QSpinBox()
    self.spinbox_stacksize.setMaximum(9999)
    self.spinbox_stacksize.setMinimumWidth(100)
    layout = QHBoxLayout()
    layout.addWidget(self.spinbox_stacksize)
    self.setLayout(layout)
コード例 #4
0
class AddWindow(QDialog):
    def __init__(self, parent=None):
        super(AddWindow, self).__init__(parent)
        self.setGeometry(QtCore.QRect(110, 40, 171, 160))

    def initUi(self):
        self.grid = QGridLayout()
        self.grid.addWidget(QLabel("Connection name"), 0, 0)
        self.grid.addWidget(QLabel("Username"), 2, 0)
        self.grid.addWidget(QLabel("Password"), 4, 0)
        self.grid.addWidget(QLabel("Hostname"), 6, 0)
        self.grid.addWidget(QLabel("Port"), 8, 0)
        self.connectionNameInput =  QLineEdit(self)
        self.grid.addWidget(self.connectionNameInput, 1, 0)
        self.userNameInput =  QLineEdit(self)
        self.grid.addWidget(self.userNameInput, 3, 0)
        self.passwordInput =  QLineEdit(self)
        self.grid.addWidget(self.passwordInput, 5, 0)
        self.hostnameInput =  QLineEdit(self)
        self.grid.addWidget(self.hostnameInput, 7, 0)
        self.portSpinBox =  QSpinBox(self)
        self.portSpinBox.setMinimum(1)
        self.portSpinBox.setMaximum(65535)
        self.portSpinBox.setValue(22)
        self.grid.addWidget(self.portSpinBox, 9, 0)
        self.addButton = QPushButton("Accept")
        self.grid.addWidget(self.addButton, 10, 0)
        self.setLayout(self.grid)

        self.addButton.clicked.connect(self.clickedAddButton)

        self.show()

    @Slot()
    def clickedAddButton(self):
        dataRep = DataRepository()
        host = self.hostnameInput.text()
        port = self.portSpinBox.value()
        pwd = self.passwordInput.text()
        login = self.userNameInput.text()
        name = self.connectionNameInput.text()
        dataRep.addConnection({
            'host':host,
            'port':port,
            'pwd':pwd,
            'login':login,
            'name':name
        })
        self.accept()
        self.close()

    def closeEvent(self, event):
            event.accept()
コード例 #5
0
class SliderWidget(QWidget):
	"""
	SliderWidget
	"""
	valueChanged = Signal(int)

	def __init__(self):
		super(SliderWidget, self).__init__()

		self.label = QLabel()
		self.slider = QSlider(Qt.Horizontal)
		self.spinbox = QSpinBox()

		self.slider.valueChanged.connect(self.changedValue)
		self.spinbox.valueChanged.connect(self.changedValue)

		layout = QGridLayout()
		layout.setContentsMargins(0, 0, 0, 0)
		layout.setVerticalSpacing(0)
		layout.addWidget(self.label, 0, 0)
		layout.addWidget(self.slider, 0, 1)
		layout.addWidget(self.spinbox, 0, 2)
		self.setLayout(layout)

	def setName(self, name):
		"""
		Set the name for the slider
		"""
		self.label.setText(name)

	def setRange(self, range):
		"""
		Set the range for the value
		"""
		self.slider.setMinimum(range[0])
		self.spinbox.setMinimum(range[0])
		self.slider.setMaximum(range[1])
		self.spinbox.setMaximum(range[1])

	def setValue(self, value):
		"""
		Set the value for the slider and the spinbox
		"""
		self.slider.setValue(value)
		self.spinbox.setValue(value)

	def value(self):
		return self.slider.value()

	@Slot(int)
	def changedValue(self, value):
		self.setValue(value)
		self.valueChanged.emit(value)
コード例 #6
0
class SliderWidget(QWidget):
    """
	SliderWidget
	"""
    valueChanged = Signal(int)

    def __init__(self):
        super(SliderWidget, self).__init__()

        self.label = QLabel()
        self.slider = QSlider(Qt.Horizontal)
        self.spinbox = QSpinBox()

        self.slider.valueChanged.connect(self.changedValue)
        self.spinbox.valueChanged.connect(self.changedValue)

        layout = QGridLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setVerticalSpacing(0)
        layout.addWidget(self.label, 0, 0)
        layout.addWidget(self.slider, 0, 1)
        layout.addWidget(self.spinbox, 0, 2)
        self.setLayout(layout)

    def setName(self, name):
        """
		Set the name for the slider
		"""
        self.label.setText(name)

    def setRange(self, range):
        """
		Set the range for the value
		"""
        self.slider.setMinimum(range[0])
        self.spinbox.setMinimum(range[0])
        self.slider.setMaximum(range[1])
        self.spinbox.setMaximum(range[1])

    def setValue(self, value):
        """
		Set the value for the slider and the spinbox
		"""
        self.slider.setValue(value)
        self.spinbox.setValue(value)

    def value(self):
        return self.slider.value()

    @Slot(int)
    def changedValue(self, value):
        self.setValue(value)
        self.valueChanged.emit(value)
コード例 #7
0
class DoFPCompound(QGroupBox):
  def __init__(self, parent=None):
    super(DoFPCompound, self).__init__(parent)
    self.setTitle("doFP")
    self.button_execute = QPushButton("Execute ...")
    self.spinbox_iterations = QSpinBox()
    self.spinbox_iterations.setMaximum(9999)
    self.spinbox_iterations.setValue(200)
    self.spinbox_iterations.setToolTip("No. iterations")
    layout = QHBoxLayout()
    layout.addWidget(self.spinbox_iterations)
    layout.addWidget(self.button_execute)
    self.setLayout(layout)
コード例 #8
0
class DialogGetConfigNumber(QDialog):
    """
    classdocs
    """
    def __init__(self, current_tab_text=None, parent=None):
        """
        Constructor
        """
        super(DialogGetConfigNumber, self).__init__(parent)
        ok_button = QPushButton("&OK")
        cancel_button = QPushButton("Cancel")
        button_layout = QHBoxLayout()
        button_layout.addStretch()
        button_layout.addWidget(ok_button)
        button_layout.addWidget(cancel_button)

        layout = QGridLayout()

        current_row = 0
        label_start = QLabel("config number :")
        self.hsb_start = QSpinBox()
        self.hsb_start.setMinimum(1)
        self.hsb_start.setMaximum(4)
        self.hsb_start.setValue(1)
        layout.addWidget(label_start, current_row, 0)
        layout.addWidget(self.hsb_start, current_row, 1, 1, 1)

        # current_row += 1
        # label_finish = QLabel("ending address :")
        # self.hsb_finish = HexSpinBox()
        # self.hsb_finish.setMinimum(0x00)
        # self.hsb_finish.setMaximum(0x7F)
        # self.hsb_finish.setValue(0x7F)
        # layout.addWidget(label_finish, current_row, 0)
        # layout.addWidget(self.hsb_finish, current_row, 1, 1, 1)
        #
        # current_row += 1
        # label_bank = QLabel("otp bank :")
        # self.spin_box_bank_sel = QSpinBox()
        # self.spin_box_bank_sel.setMinimum(0)
        # self.spin_box_bank_sel.setMaximum(1)
        # layout.addWidget(label_bank, current_row, 0)
        # layout.addWidget(self.spin_box_bank_sel, current_row, 1, 1, 1)
        current_row += 1
        layout.addLayout(button_layout, current_row, 0, 1, 2)
        self.setLayout(layout)
        self.connect(ok_button, SIGNAL("clicked()"), self, SLOT("accept()"))
        self.connect(cancel_button, SIGNAL("clicked()"), self, SLOT("reject()"))
        self.setWindowTitle("set OTP write range / bank")
コード例 #9
0
class CreateSamplesRow():
	def __init__(self):
		self.plate			= QLineEdit()
		self.parents		= QSpinBox()
		self.samples		= QSpinBox()
		self.loadedBy		= QComboBox()
		self.parents.setMaximum(8)
		self.parents.setValue(2)
		self.samples.setMaximum(96)
		self.samples.setValue(94)
		self.loadedBy.addItems(['Column','Row'])
	def getPlate(self):			return self.plate.text()
	def getParents(self):		return self.parents.value()
	def getSamples(self):		return self.samples.value()
	def getLoadedBy(self):		return self.loadedBy.currentText()
コード例 #10
0
    def get_frame(self):
        # Info stuff.
        self.infos = {}
        infogrp = QGroupBox('Scene Info')
        grdlay = QGridLayout()
        grdlay.addWidget(QLabel('<b>Name</b>'), 0, 0)
        namebox = QLineEdit()
        self.infos['name'] = namebox
        namebox.setText(self.info.name)

        rangebox1 = QSpinBox()
        rangebox1.setMinimum(0)
        rangebox1.setMaximum(1000)
        self.infos['rangestart'] = rangebox1
        rangebox1.setValue(self.info.frame_range[0])

        rangebox2 = QSpinBox()
        rangebox2.setMinimum(0)
        rangebox2.setMaximum(1000)
        self.infos['rangeend'] = rangebox2
        rangebox2.setValue(self.info.frame_range[1])

        fpsbox = QDoubleSpinBox()
        self.infos['fps'] = fpsbox
        fpsbox.setValue(self.info.fps)

        bbox_btn = QPushButton('Bounding Box')
        bbox_btn.clicked.connect(self.edit_bbox)
        grdlay.addWidget(namebox, 0, 1)
        grdlay.addWidget(QLabel('<b>StartFrame</b>'), 1, 0)
        grdlay.addWidget(rangebox1, 1, 1)
        grdlay.addWidget(QLabel('<b>EndFrame</b>'), 1, 2)
        grdlay.addWidget(fpsbox, 0, 3)
        grdlay.addWidget(rangebox2, 1, 3)
        grdlay.addWidget(QLabel('<b>FPS</b>'), 0, 2)

        grdlay.addWidget(bbox_btn, 2, 0)

        grplay = QVBoxLayout()
        grplay.addLayout(grdlay)
        #grplay.addStretch()
        infogrp.setLayout(grplay)

        return infogrp
コード例 #11
0
ファイル: scuttle_table.py プロジェクト: RedOrion/MontyLacuna
    def add_ships(self, ships: dict):
        """ Adds ships from a dict to the table.

        Arguments:
            ships (dict): ``ship type (str) => quantity``

        This does *not* clear any existing entries before adding more ships. 
        If you want to pass an exhaustive dict, be sure to call ``reset`` first.

        You generally want ``add_ships_for`` instead of this.
        """
        row = 0
        delete_buttons = {}
        for type in sorted(ships.keys()):
            ### Image
            lbl_icon = QLabel()
            img_ship = QPixmap(":/" + type + ".png").scaled(
                self.img_w, self.img_w, Qt.KeepAspectRatio)
            lbl_icon.setPixmap(img_ship)
            ### Type and Quantity
            itm_type = QTableWidgetItem(type)
            itm_num_avail = QTableWidgetItem("{:,}".format(ships[type]))
            ### Num to delete spinner
            del_spinner = QSpinBox()
            del_spinner.setMinimum(0)
            del_spinner.setMaximum(ships[type])
            ### Do Eet button
            btn_go = QPushButton("Go")

            ### functools.partial locks the arg's current value to the method.
            ### A regular Python lambda would be late-binding, so all button
            ### clicks would indicate the same (last) row.
            btn_go.clicked.connect(functools.partial(self.scuttle, row))

            self.widget.insertRow(row)
            self.widget.setCellWidget(row, 0, lbl_icon)
            self.widget.setItem(row, 1, itm_type)
            self.widget.setItem(row, 2, itm_num_avail)
            self.widget.setCellWidget(row, 3, del_spinner)
            self.widget.setCellWidget(row, 4, btn_go)
            row += 1
        self.resize()
コード例 #12
0
ファイル: myclusterui.py プロジェクト: Python3pkg/MyClusterUI
 def create_spinbox(self,
                    prefix,
                    suffix,
                    option,
                    default=NoDefault,
                    min_=None,
                    max_=None,
                    step=None,
                    tip=None):
     if prefix:
         plabel = QLabel(prefix)
     else:
         plabel = None
     if suffix:
         slabel = QLabel(suffix)
     else:
         slabel = None
     spinbox = QSpinBox()
     if min_ is not None:
         spinbox.setMinimum(min_)
     if max_ is not None:
         spinbox.setMaximum(max_)
     if step is not None:
         spinbox.setSingleStep(step)
     if tip is not None:
         spinbox.setToolTip(tip)
     self.spinboxes[option] = spinbox
     layout = QHBoxLayout()
     for subwidget in (plabel, spinbox, slabel):
         if subwidget is not None:
             layout.addWidget(subwidget)
     layout.addStretch(1)
     layout.setContentsMargins(0, 0, 0, 0)
     widget = QWidget(self)
     widget.setLayout(layout)
     return widget
コード例 #13
0
ファイル: main.py プロジェクト: elliottruzicka/Brain-Cypher
class MainWindow(QMainWindow):  # Sets up the main window
    def resize_window(self):  # Function for resizing the window
        self.resize(self.minimumSizeHint())

    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        # Set window Icon
        self.setWindowTitle(__appname__)
        iconImage = QImage(iconByteArray)
        iconPixmap = QPixmap(iconImage)
        self.setWindowIcon(QIcon(iconPixmap))

        # Set up private key format widgets
        privateKeyFormatLayout = QHBoxLayout()
        privateKeyFormatLabel = QLabel('Select Key Format: ')
        self.privateKeyTypeCombobox = QComboBox()
        self.privateKeyTypeCombobox.addItems(privateKeyFormats)
        self.privateKeyLengthLabel = QLabel('0')
        privateKeyFormatLayout.addWidget(privateKeyFormatLabel)
        privateKeyFormatLayout.addWidget(self.privateKeyTypeCombobox)
        privateKeyFormatLayout.addWidget(self.privateKeyLengthLabel)

        # Set up private key text widgets
        privateKeyLayout = QVBoxLayout()
        privateKeyButtonsLayout = QHBoxLayout()
        generatePrivateKeyButton = QPushButton('Generate Key')
        generatePrivateKeyButton.clicked.connect(self.get_private_key)
        self.copyPrivateKeyButton = QPushButton('Copy Key')
        self.copyPrivateKeyButton.setDisabled(True)
        self.copyPrivateKeyButton.clicked.connect(self.copy_private_key)
        privateKeyButtonsLayout.addWidget(generatePrivateKeyButton)
        privateKeyButtonsLayout.addWidget(self.copyPrivateKeyButton)
        self.privateKeyEdit = GrowingTextEdit()
        self.privateKeyEdit.setFont(QFont('Courier'))
        self.privateKeyEdit.textChanged.connect(
            self.private_key_or_code_changed)
        privateKeyLayout.addLayout(privateKeyButtonsLayout)
        privateKeyLayout.addWidget(self.privateKeyEdit)

        # Set up cypher code widgets
        codeLayout = QHBoxLayout()
        codeLabel = QLabel('Select Cypher Code: ')
        self.codeSelect = QSpinBox()
        self.codeSelect.setValue(10)
        self.codeSelect.setMinimum(2)
        self.codeSelect.setDisabled(True)
        self.codeSelect.valueChanged.connect(self.private_key_or_code_changed)
        codeLayout.addWidget(codeLabel)
        codeLayout.addWidget(self.codeSelect)

        # Set up cypher text widgets
        cypherLayout = QVBoxLayout()
        cypherButtonsLayout = QHBoxLayout()
        cardButtonsLayout = QHBoxLayout()
        self.generateCypherButton = QPushButton('Generate Cypher')
        self.generateCypherButton.clicked.connect(self.get_cypher)
        self.generateCypherButton.setDisabled(True)
        self.copyCypherButton = QPushButton('Copy Cypher')
        self.copyCypherButton.setDisabled(True)
        self.copyCypherButton.clicked.connect(self.copy_cypher)
        cypherButtonsLayout.addWidget(self.generateCypherButton)
        cypherButtonsLayout.addWidget(self.copyCypherButton)
        self.cypherEdit = GrowingTextEdit()
        self.cypherEdit.setFont(QFont('Courier'))
        self.cypherEdit.setReadOnly(True)
        self.cypherEdit.setVisible(False)
        self.cypherEdit.textChanged.connect(self.resize_window)
        self.cypherPreviewLabel = QLabel('-CYPHER PREVIEW-')
        self.cypherPreviewLabel.setAlignment(Qt.AlignCenter)
        self.cypherPreviewLabel.setVisible(False)
        self.cypherPreview = GrowingTextEdit()
        self.cypherPreview.setFont(QFont('Courier'))
        self.cypherPreview.setAlignment(Qt.AlignHCenter)
        self.cypherPreview.setWordWrapMode(QTextOption.NoWrap)
        self.cypherPreview.setReadOnly(True)
        self.cypherPreview.setVisible(False)
        self.cypherCardsPrintButton = QPushButton('Print Cypher Cards')
        self.cypherCardsPrintButton.setVisible(False)
        self.cypherCardsPrintButton.clicked.connect(partial(self.cards, True))
        self.cypherCardsCopyButton = QPushButton('Copy Cypher Cards')
        self.cypherCardsCopyButton.setVisible(False)
        self.cypherCardsCopyButton.clicked.connect(partial(self.cards, False))
        cardButtonsLayout.addWidget(self.cypherCardsPrintButton)
        cardButtonsLayout.addWidget(self.cypherCardsCopyButton)
        cypherLayout.addLayout(cypherButtonsLayout)
        cypherLayout.addWidget(self.cypherEdit)
        cypherLayout.addWidget(self.cypherPreviewLabel)
        cypherLayout.addWidget(self.cypherPreview)
        cypherLayout.addLayout(cardButtonsLayout)

        # Set up donation widgets
        donationsLayout = QVBoxLayout()
        separater = QFrame()
        separater.setFrameShape(QFrame.HLine)
        self.donationButton = QPushButton('Donate')
        self.donationButton.setVisible(False)
        self.donationButton.clicked.connect(self.donate)
        self.copyEthAddressButton = QPushButton('ETH: Copy Address')
        self.copyEthAddressButton.clicked.connect(
            self.copy_eth_donation_address)
        self.copyEthAddressButton.setVisible(False)
        self.copyBtcAddressButton = QPushButton('BTC: Copy Address')
        self.copyBtcAddressButton.clicked.connect(
            self.copy_btc_donation_address)
        self.copyBtcAddressButton.setVisible(False)
        donationsLayout.addWidget(separater)
        donationsLayout.addWidget(self.donationButton)
        donationsLayout.addWidget(self.copyEthAddressButton)
        donationsLayout.addWidget(self.copyBtcAddressButton)

        # Add all widgets and sub-layouts to the master layout
        self.master_layout = QVBoxLayout()
        self.master_layout.addLayout(privateKeyFormatLayout)
        self.master_layout.addLayout(privateKeyLayout)
        self.master_layout.addLayout(codeLayout)
        self.master_layout.addLayout(cypherLayout)
        self.master_layout.addLayout(donationsLayout)
        self.master_widget = QWidget()
        self.master_widget.setLayout(self.master_layout)
        self.setCentralWidget(self.master_widget)

        # Start and connect the window resizing thread
        self.worker = Worker()
        self.worker.updateWindowSize.connect(self.resize_window)

    def copy_private_key(
            self):  # Copies the private key text to the system clipboard
        clip.setText(self.privateKeyEdit.toPlainText())
        self.copyPrivateKeyButton.setText('Key Copied')
        app.processEvents()
        sleep(2)
        self.copyPrivateKeyButton.setText('Copy Key')

    def copy_cypher(self):  # Copies the cypher text to the system clipboard
        clip.setText(self.cypherEdit.toPlainText())
        self.copyCypherButton.setText('Cypher Copied')
        app.processEvents()
        sleep(2)
        self.copyCypherButton.setText('Copy Cypher')

    def copy_eth_donation_address(
            self):  # Copies the ETH donation address to the system clipboard
        clip.setText(ethDonationAddress)
        self.copyEthAddressButton.setText('ETH: Address Copied\nThanks!')
        app.processEvents()
        sleep(2)
        self.copyEthAddressButton.setText('ETH: Copy Address')

    def copy_btc_donation_address(
            self):  # Copies the BTC donation address to the system clipboard
        clip.setText(btcDonationAddress)
        self.copyBtcAddressButton.setText('BTC: Address Copied\nThanks!')
        app.processEvents()
        sleep(2)
        self.copyBtcAddressButton.setText('BTC: Copy Address')

    def get_private_key(
        self
    ):  # Generates a key of the desired format using two instances of the SystemRandom function
        privateKey = generate_private_key.start(
            self.privateKeyTypeCombobox.currentText())
        self.privateKeyEdit.setText(privateKey)
        self.private_key_or_code_changed()
        self.copyPrivateKeyButton.setDisabled(False)

    def private_key_or_code_changed(
        self
    ):  # Changes visibility and ability of some widgets based on user input
        self.privateKeyLengthLabel.setText(
            str(len(self.privateKeyEdit.toPlainText())))
        self.copyCypherButton.setDisabled(True)
        self.cypherEdit.setText('')
        self.cypherPreview.setText('')
        self.cypherEdit.setVisible(False)
        self.cypherPreviewLabel.setVisible(False)
        self.cypherPreview.setVisible(False)
        if len(self.privateKeyEdit.toPlainText()) <= 2:
            self.copyPrivateKeyButton.setDisabled(True)
            self.generateCypherButton.setDisabled(True)
            self.codeSelect.setDisabled(True)
        else:
            self.codeSelect.setMaximum(
                len(self.privateKeyEdit.toPlainText()) - 1)
            self.copyPrivateKeyButton.setDisabled(False)
            self.generateCypherButton.setDisabled(False)
            self.codeSelect.setDisabled(False)
        self.cypherCardsPrintButton.setDisabled(True)
        self.cypherCardsPrintButton.setVisible(False)
        self.cypherCardsCopyButton.setDisabled(True)
        self.cypherCardsCopyButton.setVisible(False)
        self.worker.start()

    def get_cypher(
        self
    ):  # Converts the raw key into a cypher based on the codeSelect value
        if not 1 >= len(self.privateKeyEdit.toPlainText()) >= int(
                self.privateKeyLengthLabel.text()):
            self.generateCypherButton.setDisabled(False)
            cypherRows, cypherSeed = create_cypher.start(
                self.privateKeyEdit.toPlainText(), self.codeSelect.value())
            self.copyCypherButton.setDisabled(False)
            self.cypherEdit.setVisible(True)
            self.cypherEdit.setText(cypherSeed)
            self.cypherPreviewLabel.setVisible(True)
            self.cypherPreview.setVisible(True)
            previewText = ''
            for i in cypherRows:
                previewText += i + '\n'
            self.cypherPreview.setText(previewText)
            self.worker.start()
            self.cypherCardsPrintButton.setDisabled(False)
            self.cypherCardsPrintButton.setVisible(True)
            self.cypherCardsCopyButton.setDisabled(False)
            self.cypherCardsCopyButton.setVisible(True)
            self.donationButton.setVisible(True)
        else:
            self.generateCypherButton.setDisabled(True)

    def cards(self, print):  # Creates and prints the output.txt file
        cardList = split_cypher_into_pairs.start(self.cypherEdit.toPlainText())
        printString = format_cards.start(cardList)
        if print:
            self.cypherCardsPrintButton.setText('Printing')
            app.processEvents()
            cards_output.start(printString)
            self.cypherCardsPrintButton.setText('Print Cypher Cards')
        else:
            clip.setText(printString)
            self.cypherCardsCopyButton.setText('Cards Copied')
            app.processEvents()
            sleep(2)
            self.cypherCardsCopyButton.setText('Copy Cypher Cards')

    def donate(self):  # Adjusts the visibility of the donation buttons
        if self.donationButton.text() == 'Donate':
            self.copyEthAddressButton.setVisible(True)
            self.copyBtcAddressButton.setVisible(True)
            self.donationButton.setText('Hide')
        elif self.donationButton.text() == 'Hide':
            self.copyEthAddressButton.setVisible(False)
            self.copyBtcAddressButton.setVisible(False)
            self.donationButton.setText('Donate')
        self.worker.start()

    def cleanup(self):  # Clears the clipboard of any copied text
        clip.setText('')
コード例 #14
0
    def init_UI(self):
        lay = QGridLayout()
        lay.addWidget(QLabel('<b>Position</b>'), 0, 0, 1, 4)

        posx = QDoubleSpinBox()
        posx.setValue(self.v.x)
        self.controls['posx'] = posx

        posy = QDoubleSpinBox()
        posy.setValue(self.v.y)
        self.controls['posy'] = posy

        posz = QDoubleSpinBox()
        posz.setValue(self.v.z)
        self.controls['posz'] = posz

        lay.addWidget(posx, 1, 0)
        lay.addWidget(posy, 1, 1)
        lay.addWidget(posz, 1, 2)

        lay.addWidget(QLabel('<b>Normal</b>'), 2, 0, 1, 4)

        norx = QDoubleSpinBox()
        norx.setValue(self.v.nx)
        self.controls['norx'] = norx

        nory = QDoubleSpinBox()
        nory.setValue(self.v.ny)
        self.controls['nory'] = nory

        norz = QDoubleSpinBox()
        norz.setValue(self.v.nz)
        self.controls['norz'] = norz

        lay.addWidget(norx, 3, 0)
        lay.addWidget(nory, 3, 1)
        lay.addWidget(norz, 3, 2)

        lay.addWidget(QLabel('<b>Texture Coordinates</b>'), 4, 0, 1, 4)

        u = QDoubleSpinBox()
        u.setValue(self.v.u)
        self.controls['u'] = u

        v = QDoubleSpinBox()
        v.setValue(self.v.v)
        self.controls['v'] = v

        lay.addWidget(u, 5, 0)
        lay.addWidget(v, 5, 1)

        lay.addWidget(QLabel('<b>Color</b>'), 6, 0, 1, 4)

        red = QSpinBox()
        red.setMinimum(0)
        red.setMaximum(255)
        red.setValue(self.v.color.red)
        self.controls['red'] = red

        green = QSpinBox()
        green.setMinimum(0)
        green.setMaximum(255)
        green.setValue(self.v.color.green)
        self.controls['green'] = green

        blue = QSpinBox()
        blue.setMinimum(0)
        blue.setMaximum(255)
        blue.setValue(self.v.color.blue)
        self.controls['blue'] = blue

        alpha = QSpinBox()
        alpha.setMinimum(0)
        alpha.setMaximum(255)
        alpha.setValue(self.v.color.alpha)
        self.controls['alpha'] = alpha

        lay.addWidget(red, 7, 0)
        lay.addWidget(green, 7, 1)
        lay.addWidget(blue, 7, 2)
        lay.addWidget(alpha, 7, 3)

        grp = QGroupBox('Vertex')
        grp.setLayout(lay)

        btns = QVBoxLayout()
        save = QPushButton('Save')
        save.clicked.connect(self.save)

        cancel = QPushButton('Cancel')
        cancel.clicked.connect(self.close)

        btns.addStretch()
        btns.addWidget(save)
        btns.addWidget(cancel)

        mainlay = QHBoxLayout()
        mainlay.addWidget(grp)
        mainlay.addLayout(btns)

        self.setLayout(mainlay)
        self.setGeometry(340, 340, 300, 250)
        self.setWindowTitle('MSH Suite - Vertex Editor')
        self.show()
コード例 #15
0
    def initUI(self):
        grp = QGroupBox('Transform')
        grplay = QGridLayout()
        # Translation
        grplay.addWidget(QLabel('<b>Translation</b>'), 0, 0)

        trax = QDoubleSpinBox()
        trax.setMinimum(-10000)
        trax.setMaximum(10000)
        trax.setValue(self.tran.translation[0])
        self.controls['trax'] = trax
        grplay.addWidget(trax, 0, 1)

        tray = QDoubleSpinBox()
        tray.setMinimum(-10000)
        tray.setMaximum(10000)
        tray.setValue(self.tran.translation[1])
        self.controls['tray'] = tray
        grplay.addWidget(tray, 0, 2)

        traz = QDoubleSpinBox()
        traz.setMinimum(-10000)
        traz.setMaximum(10000)
        traz.setValue(self.tran.translation[2])
        self.controls['traz'] = traz
        grplay.addWidget(traz, 0, 3)

        # Rotation.
        grplay.addWidget(QLabel('<b>Rotation</b>'), 1, 0)

        rotx = QSpinBox()
        rotx.setMinimum(-10000)
        rotx.setMaximum(10000)
        #rotx.setText(str(self.tran.euler_angles()[0]))
        traz.setValue(self.tran.euler_angles()[0])
        self.controls['rotx'] = rotx
        grplay.addWidget(rotx, 1, 1)

        roty = QSpinBox()
        roty.setMinimum(-10000)
        roty.setMaximum(10000)
        #roty.setText(str(self.tran.euler_angles()[1]))
        traz.setValue(self.tran.euler_angles()[1])
        self.controls['roty'] = roty
        grplay.addWidget(roty, 1, 2)

        rotz = QSpinBox()
        rotz.setMinimum(-10000)
        rotz.setMaximum(10000)
        #rotz.setText(str(self.tran.euler_angles()[2]))
        traz.setValue(self.tran.euler_angles()[2])
        self.controls['rotz'] = rotz
        grplay.addWidget(rotz, 1, 3)

        # Scale.
        grplay.addWidget(QLabel('<b>Scale</b>'), 2, 0)

        sclx = QDoubleSpinBox()
        sclx.setMinimum(-10000)
        sclx.setMaximum(10000)
        sclx.setValue(self.tran.scale[0])
        self.controls['sclx'] = sclx
        grplay.addWidget(sclx, 2, 1)

        scly = QDoubleSpinBox()
        scly.setMinimum(-10000)
        scly.setMaximum(10000)
        scly.setValue(self.tran.scale[1])
        self.controls['scly'] = scly
        grplay.addWidget(scly, 2, 2)

        sclz = QDoubleSpinBox()
        sclz.setMinimum(-10000)
        sclz.setMaximum(10000)
        sclz.setValue(self.tran.scale[2])
        self.controls['sclz'] = sclz
        grplay.addWidget(sclz, 2, 3)

        grp.setLayout(grplay)
        # Buttons.
        save_btn = QPushButton('Save')
        save_btn.clicked.connect(self.save)
        cancel_btn = QPushButton('Cancel')
        cancel_btn.clicked.connect(self.close)
        btns = QHBoxLayout()
        btns.addStretch()
        btns.addWidget(save_btn)
        btns.addWidget(cancel_btn)

        # Main Layout.
        mainlay = QVBoxLayout()
        mainlay.addWidget(grp)
        mainlay.addLayout(btns)
        mainlay.addStretch()

        self.setLayout(mainlay)
        self.setGeometry(340, 340, 400, 100)
        self.setWindowTitle('MSH Suite - Edit BBox')
        self.show()
コード例 #16
0
class ImageViewer(QWidget):
    def __init__(self, filename=None, name=None, parent=None):
        super(ImageViewer, self).__init__(parent)
        self.imageRaw = np.zeros((200, 200, 200))
        self.imageRGB = np.zeros((200, 200, 200, 3))
        self.viewRange = [[100, 100], [100, 100], [100, 100]]
        self.zoomFactors = [3.0, 3.0, 3.0]
        self.iMin = 0
        self.iMax = 1000
        self.ijk = [0, 0, 0]

        self.name = 'untitled'
        self.initHbRL()
        self.mouseCursorCross = False

        ## Upper buttons
        self.upperRow = QHBoxLayout()
        self.drawRightHb = QPushButton('RightHb', self)
        self.drawLeftHb = QPushButton('LeftHb', self)
        self.drawRightHb.setCheckable(True)
        self.drawLeftHb.setCheckable(True)
        self.upperRow.addWidget(self.drawRightHb)
        self.upperRow.addWidget(self.drawLeftHb)
        QtCore.QObject.connect(self.drawRightHb, QtCore.SIGNAL('clicked()'),
                               self.clickRightHb)
        QtCore.QObject.connect(self.drawLeftHb, QtCore.SIGNAL('clicked()'),
                               self.clickLeftHb)

        ## View Layout
        self.scenes = [
            MyGraphicsScene(self, 0),
            MyGraphicsScene(self, 1),
            MyGraphicsScene(self, 2)
        ]
        self.views = [
            QGraphicsView(self.scenes[0]),
            QGraphicsView(self.scenes[1]),
            QGraphicsView(self.scenes[2])
        ]
        self.sceneItems = [None, None, None]

        #Scene 4
        view4 = QGridLayout()
        labelX = QLabel('X: ')
        labelY = QLabel('Y: ')
        labelZ = QLabel('Z: ')
        self.spin = [QSpinBox(), QSpinBox(), QSpinBox()]
        labelMinIntensity = QLabel('Min: ')
        labelMaxIntensity = QLabel('Max: ')
        labelZoom = QLabel('Zoom: ')
        self.spinMin = QSpinBox()
        self.spinMax = QSpinBox()
        self.spinZoom = QSpinBox()
        self.spinMin.setMaximum(10000)
        self.spinMax.setMaximum(10000)
        self.spinMin.setValue(self.iMin)
        self.spinMax.setValue(self.iMax)
        self.spinZoom.setValue(self.zoomFactors[0])
        self.spinMin.setKeyboardTracking(False)
        self.spinMin.valueChanged.connect(self.setIntensity)
        self.spinMax.setKeyboardTracking(False)
        self.spinMax.valueChanged.connect(self.setIntensityMax)
        self.spinZoom.valueChanged.connect(self.setZoomFactor)
        self.spinZoom.setKeyboardTracking(False)
        labelAreaR = QLabel('Right: ')
        labelAreaL = QLabel('Left: ')
        self.labelAreaValueR = QLabel()
        self.labelAreaValueL = QLabel()

        view4.addWidget(labelX, 0, 0, 2, 1)
        view4.addWidget(labelY, 1, 0, 2, 1)
        view4.addWidget(labelZ, 2, 0, 2, 1)
        view4.addWidget(labelMinIntensity, 4, 0, 2, 1)
        view4.addWidget(labelMaxIntensity, 5, 0, 2, 1)
        view4.addWidget(labelZoom, 6, 0, 2, 1)
        view4.addWidget(labelAreaR, 7, 0)
        view4.addWidget(labelAreaL, 7, 2)
        view4.addWidget(self.spin[0], 0, 2, 2, 1)
        view4.addWidget(self.spin[1], 1, 2, 2, 1)
        view4.addWidget(self.spin[2], 2, 2, 2, 1)
        view4.addWidget(self.spinMin, 4, 2, 2, 1)
        view4.addWidget(self.spinMax, 5, 2, 2, 1)
        view4.addWidget(self.spinZoom, 6, 2, 2, 1)
        view4.addWidget(self.labelAreaValueR, 7, 1)
        view4.addWidget(self.labelAreaValueL, 7, 3)

        self.viewLayout = QGridLayout()
        self.viewLayout.addWidget(self.views[0], 0, 0)
        self.viewLayout.addWidget(self.views[1], 0, 1)
        self.viewLayout.addWidget(self.views[2], 1, 0)
        self.viewLayout.addLayout(view4, 1, 1)

        ## Lower
        self.lowerRow = QHBoxLayout()
        calculateButtonDown = QPushButton('calculateVolume', self)
        saveButtonDown = QPushButton('SaveHb', self)
        loadButtonDown = QPushButton('loadHb', self)
        savepngButtonDown = QPushButton('Save PNG', self)
        self.lowerRow.addWidget(calculateButtonDown)
        self.lowerRow.addWidget(saveButtonDown)
        self.lowerRow.addWidget(loadButtonDown)
        self.lowerRow.addWidget(savepngButtonDown)
        QtCore.QObject.connect(calculateButtonDown, QtCore.SIGNAL('clicked()'),
                               self.getHbAreas)
        QtCore.QObject.connect(saveButtonDown, QtCore.SIGNAL('clicked()'),
                               self.saveHb)
        QtCore.QObject.connect(loadButtonDown, QtCore.SIGNAL('clicked()'),
                               self.loadHb)
        QtCore.QObject.connect(savepngButtonDown, QtCore.SIGNAL('clicked()'),
                               self.saveCoronalSlice)

        ## Layout
        self.mainLayout = QVBoxLayout()
        self.mainLayout.addLayout(self.upperRow)
        self.mainLayout.addLayout(self.viewLayout)
        self.mainLayout.addLayout(self.lowerRow)

        self.setLayout(self.mainLayout)
        self.setWindowTitle("Image Viewer")
        self.resize(600, 700)
        self.show()

        if filename:
            self.loadNifti1(filename, name=name)

    def loadNifti1(self, filename, name=None):
        self.loadImage = LoadImage()
        self.loadImage.readNifti1(filename)
        if name is None:
            name = filename[:]
            if name[-7:] == '.nii.gz':
                name = name[:-7]
            elif name[-4:] == '.nii':
                name = name[:-4]

            for ch in ['/', '.', '~']:
                pos = name.find(ch)
                while pos > -1:
                    name = '%s_%s' % (name[:pos], name[pos + 1:])
                    pos = name.find(ch)

        self.name = name
        self.imageRaw = self.loadImage.data

        self.spinMin.setMaximum(int(self.imageRaw.max() * 1.2))
        self.spinMax.setMaximum(int(self.imageRaw.max() * 1.2))
        #self.iMin = int(max(0, self.imageRaw.min()*1.2))
        self.iMin = 0
        self.iMax = int(self.imageRaw.max() * 0.8)

        self.spinMin.setValue(self.iMin)
        self.spinMax.setValue(self.iMax)

        self.imageRGB = convertImageRGB(
            resetIntensity(self.imageRaw, iMin=self.iMin, iMax=self.iMax))
        self.setIJK()
        self.drawBaseImage()
        self.setSceneIJK()
        self.showSpinValue()

        self.setMouseCursor(True)

    def showSpinValue(self):
        self.spin[0].setMaximum(self.imageRaw.shape[0])
        self.spin[1].setMaximum(self.imageRaw.shape[1])
        self.spin[2].setMaximum(self.imageRaw.shape[2])
        self.spin[0].setKeyboardTracking(False)
        self.spin[1].setKeyboardTracking(False)
        self.spin[2].setKeyboardTracking(False)
        self.spin[0].setValue(self.ijk[0])
        self.spin[1].setValue(self.ijk[1])
        self.spin[2].setValue(self.ijk[2])
        self.spin[0].valueChanged.connect(self.resetI)
        self.spin[1].valueChanged.connect(self.resetJ)
        self.spin[2].valueChanged.connect(self.resetK)

    def resetI(self, i):
        self.ijk[0] = i
        self.drawBaseImage([0])

    def resetJ(self, j):
        self.ijk[1] = j
        self.drawBaseImage([1])
        self.labelAreaValueR.clear()
        self.labelAreaValueL.clear()

    def resetK(self, k):
        self.ijk[2] = k
        self.drawBaseImage([2])

    def initHbRL(self):
        self.hbRight = {
            'name': 'HbRight',
            'color': 'red',
            'images': [],
            'points': []
        }
        self.hbLeft = {
            'name': 'HbLeft',
            'color': 'blue',
            'images': [],
            'points': []
        }

    def clickRightHb(self):
        if self.drawLeftHb.isChecked():
            self.drawLeftHb.setChecked(False)

    def clickLeftHb(self):
        if self.drawRightHb.isChecked():
            self.drawRightHb.setChecked(False)

    def saveHb(self, filename=None):
        if filename is None:
            filename = '%s_lawson_hb.csv' % self.name
        writeHb(filename, self.hbRight, self.hbLeft)
        with open(filename, 'a') as fout:
            volumes = self.getHbAreas()
            fout.write('%s,%s\n' % (volumes[0], volumes[1]))

        png_filename = filename[:-4]

    def saveCoronalSlice(self, filename=None):
        viewIndex = 1
        if filename is None:
            filename = '%s_lawson_hb' % self.name
        filename += str('%03d.png' % self.ijk[viewIndex])
        self.scenes[viewIndex].savePng(filename, 'PNG')

    def loadHb(self, filename=None):
        if filename is None:
            filename = '%s_lawson_hb.csv' % self.name
        self.initHbRL()
        readHb(filename, self.hbRight, self.hbLeft)

    def setMouseCursor(self, cross=False):
        if cross != self.mouseCursorCross:
            self.mouseCursorCross = cross
            if cross:
                #self.setCursor(QCursor(QtCore.Qt.CrossCursor))
                self.setCursor(QtCore.Qt.CrossCursor)
            else:
                #self.setCursor(QCursor(QtCore.Qt.ArrowCursor))
                self.setCursor(QtCore.Qt.ArrowCursor)

    def getZoomFactors(self):
        return self.zoomFactors

    def magZoomFactors(self, ratio):
        self.setZoomFactors([value + ratio for value in self.zoomFactors])
        self.spinZoom.setValue(self.zoomFactors[0])

    def setZoomFactors(self, zoomFactors):
        sceneRects = self.saveScene()
        self.zoomFactors = zoomFactors
        self.drawBaseImage()
        self.restoreScene(sceneRects)

    def setZoomFactor(self, zoomFactor):
        self.setZoomFactors([zoomFactor, zoomFactor, zoomFactor])

    def getIntensity(self):
        return self.iMin, self.iMax

    def setIntensityMax(self, iMax):
        self.setIntensity(iMax=iMax)

    def setIntensity(self, iMin=None, iMax=None):
        if iMin:
            self.iMin = iMin
        if iMax:
            self.iMax = iMax
        self.imageRGB = convertImageRGB(
            resetIntensity(self.imageRaw, iMin=self.iMin, iMax=self.iMax))
        self.drawBaseImage()

    def mousePressEventLeft(self, viewIndex, x, y):
        if viewIndex == 1:
            if self.drawRightHb.isChecked():
                hbDict = self.hbRight
                labelAreaValue = self.labelAreaValueR
            elif self.drawLeftHb.isChecked():
                hbDict = self.hbLeft
                labelAreaValue = self.labelAreaValueL
            else:
                self.resetIJK(viewIndex, x, y)
                return

            if not hbDict.has_key(self.ijk[viewIndex]):
                hbDict[self.ijk[viewIndex]] = HbRegionDraw()

            if hbDict[self.ijk[viewIndex]].insert == 4:
                for item in hbDict['images']:  # lines
                    self.scenes[viewIndex].removeItem(item)
                hbDict['images'] = []
                item = hbDict['points'].pop(0)  # last point
                self.scenes[viewIndex].removeItem(item)

            i, j = self.point2fijk(viewIndex, x, y)
            if not hbDict[self.ijk[viewIndex]].push((i, j)):
                item = hbDict['points'].pop(0)  # last point
                self.scenes[viewIndex].removeItem(item)
                #self.scenes[viewIndex].removeItem(self.scenes[viewIndex].items()[0])

            x_round, y_round = self.ij2point(viewIndex, i, j)
            hbDict['points'].insert(
                0, self.scenes[viewIndex].addEllipse(
                    x_round - 1,
                    y_round - 1,
                    2,
                    2,
                    pen=QPen(QColor(hbDict['color']))))

            if hbDict[self.ijk[viewIndex]].insert >= 4:
                area = hbDict[self.ijk[viewIndex]].calculate_area(
                    hbDict['name'])
                print ' %s %s: %s' % (self.ijk[viewIndex], hbDict['name'],
                                      area)
                self.drawHb(hbDict)
                #labelAreaValue.setText('%s: %3.2f' % (self.ijk[viewIndex], area))
                labelAreaValue.setText('%3.2f' % (area))
        else:
            self.resetIJK(viewIndex, x, y)

    def mousePressEventRight(self, viewIndex, x, y):
        if viewIndex == 1:
            if self.drawRightHb.isChecked():
                hbDict = self.hbRight
            elif self.drawLeftHb.isChecked():
                hbDict = self.hbLeft
            else:
                return

            if not hbDict.has_key(self.ijk[viewIndex]):
                return

            if hbDict[self.ijk[viewIndex]].insert == 4:
                for item in hbDict['images']:  # lines
                    self.scenes[viewIndex].removeItem(item)
                hbDict['images'] = []
                #for item in self.scenes[viewIndex].items()[:3]:     # lines
                #    self.scenes[viewIndex].removeItem(item)

            if hbDict[self.ijk[viewIndex]].pop():
                item = hbDict['points'].pop(0)  # last point
                self.scenes[viewIndex].removeItem(item)
                #self.scenes[viewIndex].removeItem(self.scenes[viewIndex].items()[0])

    def moveIJK(self, viewIndex, dx):
        self.ijk[viewIndex] += dx
        self.spin[viewIndex].setValue(self.ijk[viewIndex])
        self.drawBaseImage([viewIndex])
        self.labelAreaValueR.clear()
        self.labelAreaValueL.clear()

    def point2fijk(self, viewIndex, x, y):
        indexTable = [[1, 2], [0, 2], [0, 1]]
        xIndex = indexTable[viewIndex][0]
        yIndex = indexTable[viewIndex][1]
        ijkX = float(x) / self.zoomFactors[viewIndex]
        ijkY = self.imageRGB.shape[yIndex] - 1 - float(
            y) / self.zoomFactors[viewIndex]
        ijkX = np.round(ijkX * 2) / 2
        ijkY = np.round(ijkY * 2) / 2
        return (ijkX, ijkY)

    def point2fijk_flt(self, viewIndex, x, y):
        indexTable = [[1, 2], [0, 2], [0, 1]]
        xIndex = indexTable[viewIndex][0]
        yIndex = indexTable[viewIndex][1]
        ijkX = float(x) / self.zoomFactors[viewIndex]
        ijkY = self.imageRGB.shape[yIndex] - 1 - float(
            y) / self.zoomFactors[viewIndex]
        return (ijkX, ijkY)

    def point2ijk(self, viewIndex, x, y):
        indexTable = [[1, 2], [0, 2], [0, 1]]
        xIndex = indexTable[viewIndex][0]
        yIndex = indexTable[viewIndex][1]
        ijkX = int(x / self.zoomFactors[viewIndex])
        ijkY = self.imageRGB.shape[yIndex] - 1 - int(
            y / self.zoomFactors[viewIndex])
        return (ijkX, ijkY)

    def ij2point(self, viewIndex, i, j):
        indexTable = [[1, 2], [0, 2], [0, 1]]
        xIndex = indexTable[viewIndex][0]
        yIndex = indexTable[viewIndex][1]
        pointX = i * self.zoomFactors[viewIndex]
        pointY = (self.imageRGB.shape[yIndex] - 1 -
                  j) * self.zoomFactors[viewIndex]
        return (pointX, pointY)

    def resetIJK(self, viewIndex, x, y):
        indexTable = [[1, 2], [0, 2], [0, 1]]
        xIndex = indexTable[viewIndex][0]
        yIndex = indexTable[viewIndex][1]
        self.ijk[xIndex] = int(x / self.zoomFactors[viewIndex])
        self.ijk[yIndex] = self.imageRGB.shape[yIndex] - 1 - int(
            y / self.zoomFactors[viewIndex])
        self.spin[xIndex].setValue(self.ijk[xIndex])
        self.spin[yIndex].setValue(self.ijk[yIndex])
        self.drawBaseImage(indexTable[viewIndex])
        self.labelAreaValueR.clear()
        self.labelAreaValueL.clear()

    def saveScene(self):
        sceneRects = [0, 0, 0]
        for i in range(3):
            size = self.views[i].size().toTuple()
            x, y, _, _ = self.scenes[i].sceneRect().getRect()
            x += (size[0] - 10) / 2.0
            y += (size[1] - 10) / 2.0
            x /= self.zoomFactors[i]
            y /= self.zoomFactors[i]
            sceneRects[i] = [x, y]
        return sceneRects

    def restoreScene(self, sceneRects):
        for i in range(3):
            size = self.views[i].size().toTuple()
            x = sceneRects[i][0] * self.zoomFactors[i]
            y = sceneRects[i][1] * self.zoomFactors[i]
            self.scenes[i].setSceneRect(x - (size[0] - 10) / 2,
                                        y - (size[0] - 10) / 2, size[0] - 10,
                                        size[1] - 10)

    def setSceneIJK(self, viewIndex=(0, 1, 2)):
        for i in viewIndex:
            size = self.views[i].size().toTuple()

            xyCenter = [
                self.ijk[tmp] * self.zoomFactors[i] for tmp in range(3)
                if tmp is not i
            ]

            self.scenes[i].setSceneRect(xyCenter[0] - size[0] / 2.0,
                                        xyCenter[1] - size[1] / 2.0,
                                        size[0] - 10, size[1] - 10)

    def setIJK(self, ijk='center'):
        if ijk == 'center':
            self.ijk = [
                self.imageRGB.shape[0] / 2, self.imageRGB.shape[1] / 2,
                self.imageRGB.shape[2] / 2
            ]
        else:
            self.ijk = ijk
        self.spin[0].setValue(self.ijk[0])
        self.spin[1].setValue(self.ijk[1])
        self.spin[2].setValue(self.ijk[2])

    def get2D(self, plane):
        if plane == 0:
            return np.rot90(self.imageRGB[self.ijk[0], :, :, :])
        elif plane == 1:
            return np.rot90(self.imageRGB[:, self.ijk[1], :, :])
        elif plane == 2:
            return np.rot90(self.imageRGB[:, :, self.ijk[2], :])

    def drawBaseImage(self, viewIndex=(0, 1, 2), eraseOthers=True):
        for i in viewIndex:
            imageArray3d = self.get2D(i)
            height, width, bytesPerComponent = imageArray3d.shape
            imageArray = imageArray3d.flatten()
            bytesPerLine = bytesPerComponent * width
            image = QImage(imageArray, width, height, bytesPerLine,
                           QImage.Format_RGB888)
            #image = image.scaled( int(width*self.zoomFactors[i]), int(height*self.zoomFactors[i]), Qt.KeepAspectRatio, Qt.SmoothTransformation)
            image = image.scaled(int(width * self.zoomFactors[i]),
                                 int(height * self.zoomFactors[i]),
                                 QtCore.Qt.KeepAspectRatio)

            if self.sceneItems[i] is not None:
                #self.scenes[i].removeItem(self.sceneItems[i])
                self.sceneItems[i].setPixmap(QPixmap.fromImage(image))
                if False:
                    items = self.scenes[i].items()
                    for item in items:
                        self.scenes[i].removeItem(item)

                    self.sceneItems[i] = self.scenes[i].addPixmap(
                        QPixmap.fromImage(image))
                    for item in items[1:]:
                        self.scenes[i].additem(item)

                    del items

            else:
                self.sceneItems[i] = self.scenes[i].addPixmap(
                    QPixmap.fromImage(image))

            if eraseOthers:
                for item in self.scenes[i].items():
                    if item != self.sceneItems[i]:
                        self.scenes[i].removeItem(item)

            # TODO: where to put this
            self.drawHbPts(self.hbRight)
            self.drawHb(self.hbRight)
            self.drawHbPts(self.hbLeft)
            self.drawHb(self.hbLeft)

    def drawHbPts(self, hbDict):
        viewIndex = 1
        if not hbDict.has_key(self.ijk[viewIndex]):
            return
        pts = [
            self.ij2point(viewIndex, i, j)
            for (i, j) in hbDict[self.ijk[viewIndex]].get_points()
        ]
        for i in range(hbDict[self.ijk[viewIndex]].insert):
            hbDict['points'].insert(
                0, self.scenes[viewIndex].addEllipse(
                    pts[i][0] - 1,
                    pts[i][1] - 1,
                    2,
                    2,
                    pen=QPen(QColor(hbDict['color']))))

    def drawHb(self, hbDict):
        viewIndex = 1
        if not hbDict.has_key(self.ijk[viewIndex]):
            return
        if hbDict[self.ijk[viewIndex]].insert < 4:
            return

        a, b, c, d = [
            self.ij2point(viewIndex, i, j)
            for (i, j) in hbDict[self.ijk[viewIndex]].get_points()
        ]

        cp = hbDict[self.ijk[viewIndex]].cp
        cp = self.ij2point(viewIndex, cp[0], cp[1])

        vA = (a[0] - cp[0], a[1] - cp[1])
        vB = (b[0] - cp[0], b[1] - cp[1])
        vD = (d[0] - cp[0], d[1] - cp[1])

        arcAD = QPainterPath()
        arcDB = QPainterPath()

        if hbDict['name'] == 'HbRight':
            sign = 1
            startAngle = 0
        else:
            sign = -1
            startAngle = 180

        angleADlad = sign * angleBw2Vectors(vA, vD)
        angleAD = 180 / np.pi * angleADlad

        if vD[0] * vD[0] + vD[1] * vD[1] >= vA[0] * vA[0] + vA[1] * vA[1]:
            rotD = (np.sqrt(vD[0] * vD[0] + vD[1] * vD[1]), 0)
            coefA = rotD[0]

            rotA = rotateVector(vA, angleADlad)
            coefB = np.sqrt(coefA * coefA /
                            (coefA * coefA - rotA[0] * rotA[0]) * rotA[1] *
                            rotA[1])
            eccentricAnomalyAD = -180 / np.pi * np.arctan(
                coefA / coefB * np.tan(angleADlad))
            arcAD.moveTo(cp[0] + sign * coefA, cp[1])
            arcAD.arcTo(cp[0] - coefA, cp[1] - coefB, 2 * coefA, 2 * coefB,
                        startAngle, eccentricAnomalyAD)
        else:
            rotA = (np.sqrt(vA[0] * vA[0] + vA[1] * vA[1]), 0)
            coefA = rotA[0]

            angleDAlad = sign * angleBw2Vectors(vD, vA)
            angleDA = 180 / np.pi * angleDAlad

            rotD = vD
            coefB = np.sqrt(coefA * coefA /
                            (coefA * coefA - rotD[0] * rotD[0]) * rotD[1] *
                            rotD[1])
            eccentricAnomalyDA = 180 / np.pi * np.arctan(
                coefA / coefB * np.tan(angleDAlad))
            arcAD.moveTo(cp[0] + sign * coefA, cp[1])
            arcAD.arcTo(cp[0] - coefA, cp[1] - coefB, 2 * coefA, 2 * coefB,
                        startAngle, eccentricAnomalyDA)
            angleAD = 0.0

        if vD[0] * vD[0] + vD[1] * vD[1] >= vB[0] * vB[0] + vB[1] * vB[1]:
            rotD = (np.sqrt(vD[0] * vD[0] + vD[1] * vD[1]), 0)
            coefA = rotD[0]

            angleBDlad = sign * angleBw2Vectors(vD, vB)
            angleBD = 180 / np.pi * angleBDlad

            rotB = rotateVector(vB, angleADlad)
            coefB = np.sqrt(coefA * coefA /
                            (coefA * coefA - rotB[0] * rotB[0]) * rotB[1] *
                            rotB[1])
            eccentricAnomalyDB = 180 / np.pi * np.arctan(
                coefA / coefB * np.tan(angleBDlad))
            arcDB.moveTo(cp[0] + sign * coefA, cp[1])
            arcDB.arcTo(cp[0] - coefA, cp[1] - coefB, 2 * coefA, 2 * coefB,
                        startAngle, eccentricAnomalyDB)

            angleAB = 180 / np.pi * sign * angleBw2Vectors(vA, vD)
        else:
            rotB = (np.sqrt(vB[0] * vB[0] + vB[1] * vB[1]), 0)
            coefA = rotB[0]

            angleABlad = sign * angleBw2Vectors(vA, vB)
            angleAB = 180 / np.pi * angleABlad

            angleDBlad = sign * angleBw2Vectors(vD, vB)
            angleDB = 180 / np.pi * angleDBlad

            rotD = rotateVector(vD, angleABlad)
            coefB = np.sqrt(coefA * coefA /
                            (coefA * coefA - rotD[0] * rotD[0]) * rotD[1] *
                            rotD[1])
            eccentricAnomalyDB = -180 / np.pi * np.arctan(
                coefA / coefB * np.tan(angleDBlad))
            arcDB.moveTo(cp[0] + sign * coefA, cp[1])
            arcDB.arcTo(cp[0] - coefA, cp[1] - coefB, 2 * coefA, 2 * coefB,
                        startAngle, eccentricAnomalyDB)

        imgAC = self.scenes[viewIndex].addLine(a[0],
                                               a[1],
                                               cp[0],
                                               cp[1],
                                               pen=QPen(QColor(
                                                   hbDict['color'])))
        imgBC = self.scenes[viewIndex].addLine(b[0],
                                               b[1],
                                               c[0],
                                               c[1],
                                               pen=QPen(QColor(
                                                   hbDict['color'])))
        imgAD = self.scenes[viewIndex].addPath(arcAD,
                                               pen=QPen(QColor(
                                                   hbDict['color'])))
        imgAD.setTransform(QTransform().translate(
            cp[0], cp[1]).rotate(-angleAD).translate(-cp[0], -cp[1]))
        imgDB = self.scenes[viewIndex].addPath(arcDB,
                                               pen=QPen(QColor(
                                                   hbDict['color'])))
        imgDB.setTransform(QTransform().translate(
            cp[0], cp[1]).rotate(-angleAB).translate(-cp[0], -cp[1]))
        hbDict['images'] = [imgAD, imgDB, imgBC, imgAC]

    def getHbAreas(self):
        volumes = []
        for hbDict in [self.hbRight, self.hbLeft]:
            keys = hbDict.keys()
            if not keys:
                volumes.append(0.0)
                continue

            print 'Calculate %s Volume...' % hbDict['name']
            unit = self.loadImage.zooms[0] * self.loadImage.zooms[
                1] * self.loadImage.zooms[2]
            volume = 0.0
            keys.sort()
            for key in keys:
                if type(key) == type(''):
                    continue
                area = hbDict[key].area
                print ' %s: %s (voxel)' % (key, area)
                volume += area
            volume *= unit
            print 'volume = %s (mm^3)' % volume
            volumes.append(volume)
        return volumes
コード例 #17
0
    def initUI(self):
        grp = QGroupBox('Material')
        grplay = QGridLayout()

        name = QLineEdit()
        name.setText(self.mat.name)
        self.controls['name'] = name

        tex0 = QLineEdit()
        tex0.setText(self.mat.tex0)
        self.controls['tex0'] = tex0

        tex1 = QLineEdit()
        tex1.setText(self.mat.tex1)
        self.controls['tex1'] = tex1

        tex2 = QLineEdit()
        tex2.setText(self.mat.tex2)
        self.controls['tex2'] = tex2

        tex3 = QLineEdit()
        tex3.setText(self.mat.tex3)
        self.controls['tex3'] = tex3

        flags = QGroupBox('Flags')
        fllay = QGridLayout()

        for ind, flag in enumerate(self.mat.flags):
            fllay.addWidget(QLabel(self.pretty_flags[flag[0]]), ind, 0)
            box = QCheckBox()
            fllay.addWidget(box, ind, 1)
            if flag[1]:
                box.toggle()
            self.controls[flag[0]] = box

        fllay.addWidget(QLabel('<b>RenderType</b>'), 8, 0)
        numbox = QComboBox()
        numbox.addItems(self.render_types)
        numbox.setCurrentIndex(self.mat.render_type)
        fllay.addWidget(numbox)
        self.controls['render_type'] = numbox

        fllay.addWidget(QLabel('<b>Data0</b>'), 9, 0)
        d0 = QSpinBox()
        d0.setValue(self.mat.data0)
        d0.setMinimum(0)
        d0.setMaximum(255)
        fllay.addWidget(d0)
        self.controls['data0'] = d0

        fllay.addWidget(QLabel('<b>Data1</b>'), 10, 0)
        d1 = QSpinBox()
        d1.setValue(self.mat.data1)
        d1.setMinimum(0)
        d1.setMaximum(255)
        fllay.addWidget(d1)
        self.controls['data1'] = d1

        flags.setLayout(fllay)

        colors = QGroupBox('Colors')
        collay = QGridLayout()

        self.add_color('<b>Diffuse</b>', self.mat.diff_color, collay, 3)
        self.add_color('<b>Specular</b>', self.mat.spec_color, collay, 4)
        self.add_color('<b>Ambient</b>', self.mat.ambt_color, collay, 5)

        colors.setLayout(collay)

        grplay.addWidget(QLabel('<b>Name</b>'), 0, 0)
        grplay.addWidget(name, 0, 1)

        grplay.addWidget(QLabel('<b>Texture0</b>'), 1, 0)
        grplay.addWidget(tex0, 1, 1)
        grplay.addWidget(QLabel('<b>Texture1</b>'), 1, 2)
        grplay.addWidget(tex1, 1, 3)

        grplay.addWidget(QLabel('<b>Texture2</b>'), 2, 0)
        grplay.addWidget(tex2, 2, 1)
        grplay.addWidget(QLabel('<b>Texture3</b>'), 2, 2)
        grplay.addWidget(tex3, 2, 3)

        grplay.addWidget(QLabel('<b>Gloss</b>'), 3, 0)
        gloss = QDoubleSpinBox()
        gloss.setValue(self.mat.gloss)
        grplay.addWidget(gloss, 3, 1)
        self.controls['gloss'] = gloss

        grplay.addWidget(colors, 4, 0, 1, 5)
        grplay.addWidget(flags, 5, 0, 1, 3)

        grp.setLayout(grplay)

        btns = QHBoxLayout()

        save = QPushButton('Save')
        save.clicked.connect(self.save)
        cancel = QPushButton('Cancel')
        cancel.clicked.connect(self.close)

        btns.addStretch()
        btns.addWidget(save)
        btns.addWidget(cancel)

        mainlay = QVBoxLayout()
        mainlay.addWidget(grp)
        mainlay.addLayout(btns)

        self.setLayout(mainlay)
        self.setGeometry(340, 340, 440, 200)
        self.setWindowTitle('MSH Suite - {0}'.format(self.mat.name))
        self.show()
コード例 #18
0
ファイル: PushupForm.py プロジェクト: davcri/Pushup-app
class PushupForm(QDialog):
    '''
    classdocs
    '''
    pushupCreated = Signal(Pushup_Model)

    def __init__(self, athlete):
        '''
        Constructor
        '''
        QDialog.__init__(self)

        self.setWindowTitle("Pushup form")
        self.athlete = athlete
        self.pushupForm = QFormLayout()
        self.createGUI()

    def createGUI(self):
        self.series = QSpinBox()
        self.series.setMinimum(1)

        self.repetitions = QSpinBox()
        self.repetitions.setMaximum(512)

        self.avgHeartRateToggle = QCheckBox()
        self.avgHeartRateToggle.toggled.connect(self._toggleHeartRateSpinBox)

        self.avgHeartRate = QSpinBox()
        self.avgHeartRate.setMinimum(30)
        self.avgHeartRate.setMaximum(250)
        self.avgHeartRate.setValue(120)
        self.avgHeartRate.setDisabled(True)

        self.dateSelector_widget = QCalendarWidget()
        self.dateSelector_widget.setMaximumDate(QDate.currentDate())

        self.addButton = QPushButton("Add pushup")
        self.addButton.setMaximumWidth(90)
        self.addButton.clicked.connect(self._createPushup)

        self.cancelButton = QPushButton("Cancel")
        self.cancelButton.setMaximumWidth(90)
        self.cancelButton.clicked.connect(self.reject)

        self.pushupForm.addRow("Series", self.series)
        self.pushupForm.addRow("Repetitions", self.repetitions)
        self.pushupForm.addRow("Store average heart rate ? ",
                               self.avgHeartRateToggle)
        self.pushupForm.addRow("Average Heart Rate", self.avgHeartRate)
        self.pushupForm.addRow("Exercise Date", self.dateSelector_widget)

        btnsLayout = QVBoxLayout()
        btnsLayout.addWidget(self.addButton)
        btnsLayout.addWidget(self.cancelButton)
        btnsLayout.setAlignment(Qt.AlignRight)

        layoutWrapper = QVBoxLayout()
        layoutWrapper.addLayout(self.pushupForm)
        layoutWrapper.addLayout(btnsLayout)

        self.setLayout(layoutWrapper)

    def _createPushup(self):
        exerciseDate = self.dateSelector_widget.selectedDate()
        exerciseDate = self.qDate_to_date(exerciseDate)

        if self.avgHeartRateToggle.isChecked():
            heartRate = self.avgHeartRate.value()
        else:
            heartRate = None

        pushup = Pushup_Model(self.athlete._name, exerciseDate, heartRate,
                              self.series.value(), self.repetitions.value())

        self.pushupCreated.emit(pushup)
        self.accept()

    def _toggleHeartRateSpinBox(self):
        if self.avgHeartRateToggle.isChecked():
            self.avgHeartRate.setDisabled(False)
        else:
            self.avgHeartRate.setDisabled(True)

    def qDate_to_date(self, qDate):
        return date(qDate.year(), qDate.month(), qDate.day())
コード例 #19
0
class OptionsContainer(QWidget):
    def __init__(self,main_window):
        QWidget.__init__(self)
        self.main_window = main_window
        self.layout = QGridLayout()
        self.setLayout(self.layout)
        
        self.lr = numpy.zeros(2)
        
        self.fps = QSpinBox()
        self.fps.setValue(25)
        self.fps.setMinimum(1)
        self.fps.setMaximum(1000)
        self.layout.addWidget(QLabel("FPS:"),10,10)
        self.layout.addWidget(self.fps,10,11)
        
        self.capture_area_group = QButtonGroup()
        self.capture_area_fs = QRadioButton("Full Screen")
        self.connect(self.capture_area_fs, SIGNAL("clicked()"),self.capture_area_change)
        self.capture_area_fs.setChecked(True)
        self.capture_area_sa = QRadioButton("Selected Area")
        self.connect(self.capture_area_sa, SIGNAL("clicked()"),self.capture_area_change)
        self.capture_area_group.addButton(self.capture_area_fs)
        self.capture_area_group.addButton(self.capture_area_sa)
        self.capture_area_group.setExclusive(True)
        
        self.layout.addWidget(self.capture_area_fs,12,10)
        self.layout.addWidget(self.capture_area_sa,12,11)
        
        self.sa_group = QGroupBox()
        self.sa_grid = QGridLayout()
        self.sa_group.setLayout(self.sa_grid)
        
        
        self.sa_ul_bt = QPushButton("Select Upper Left")
        self.connect(self.sa_ul_bt, SIGNAL("clicked()"), self.select_ul)
        self.sa_lr_bt = QPushButton("Select Lower Right")
        self.connect(self.sa_lr_bt, SIGNAL("clicked()"), self.select_lr)

        self.sa_x = QSpinBox()
        self.sa_y = QSpinBox()
        self.sa_w = QSpinBox()
        self.sa_h = QSpinBox()
        for sb in [self.sa_h,self.sa_w,self.sa_x,self.sa_y]:
            sb.setMaximum(999999)
            sb.setMinimum(0)
        
        self.sa_grid.addWidget(self.sa_ul_bt,14,10,1,1)
        self.sa_grid.addWidget(self.sa_lr_bt,15,10,1,1)
        self.sa_grid.addWidget(QLabel("x"),14,11,1,1)
        self.sa_grid.addWidget(self.sa_x,14,12,1,1)
        self.sa_grid.addWidget(QLabel("y"),15,11,1,1)
        self.sa_grid.addWidget(self.sa_y,15,12,1,1)
        self.sa_grid.addWidget(QLabel("w"),16,11,1,1)
        self.sa_grid.addWidget(self.sa_w,16,12,1,1)
        self.sa_grid.addWidget(QLabel("h"),17,11,1,1)
        self.sa_grid.addWidget(self.sa_h,17,12,1,1)
        
        self.sa_show_bt = QPushButton("Show Area")
        self.sa_show_bt.setCheckable(True)
        self.connect(self.sa_show_bt, SIGNAL("clicked()"), self.show_selected_area)

        
        self.sa_grid.addWidget(self.sa_show_bt,18,10,1,10)
        
        self.sa_group.hide()
        
        self.layout.addWidget(self.sa_group,14,10,1,10)
        
        self.capture_delay = QSpinBox()
        self.capture_delay.setMinimum(0)
        self.capture_delay.setMaximum(10000)
        
        self.layout.addWidget(QLabel("Capture Delay"),18,10,1,1)
        self.layout.addWidget(self.capture_delay,18,11,1,1)
        
        self.capture_bt = QPushButton("Capture")
        self.stop_capture_bt = QPushButton("Stop")
        self.stop_capture_bt.hide()
        self.layout.addWidget(self.capture_bt,20,10,1,10)
        self.layout.addWidget(self.stop_capture_bt,30,10,1,10)
        
        self.ffmpeg_flags = QLineEdit()
        self.ffmpeg_flags.setText("-qscale 0 -vcodec mpeg4")
        self.layout.addWidget(QLabel("FFMPEG Flags:"),40,10)
        self.layout.addWidget(self.ffmpeg_flags,50,10,1,10)
        
        self.encode_bt = QPushButton("Encode Video")
        self.layout.addWidget(self.encode_bt,60,10,1,10)
        
        self.open_dir_bt = QPushButton("Open Directory")
        self.layout.addWidget(self.open_dir_bt,80,10,1,10)
        
        self.connect(self.open_dir_bt, SIGNAL("clicked()"),self.open_cwd)
    
        self.selected_area = SelectedArea()
    
    def show_selected_area(self):
        x = self.sa_x.value()
        y = self.sa_y.value()
        w = self.sa_w.value()
        h = self.sa_h.value()
        
        self.selected_area.setGeometry(x,y,w,h)
        self.selected_area.activateWindow()
        self.selected_area.raise_()
        if(self.sa_show_bt.isChecked()):
            self.selected_area.show()
        else:self.selected_area.hide()
        
    def select_ul(self):
        print "select_ul"
        self.clicked  = False
        self.tw = TransWindow()
        self.tw.mouse_press = False
        self.tw.show()
        
        self.connect(self.tw, SIGNAL("mouse_press()"),self.set_ul)
        
    def select_lr(self):
        print "select_lr"
        self.clicked  = False
        self.tw = TransWindow()
        self.tw.mouse_press = False
        self.tw.show()
        
        self.connect(self.tw, SIGNAL("mouse_press()"),self.set_lr)
    
    def set_ul(self):
        self.sa_x.setValue( self.tw.pos[0])       
        self.sa_y.setValue( self.tw.pos[1])
        self.sa_w.setValue( self.lr[0] - self.sa_x.value())       
        self.sa_h.setValue( self.lr[1] - self.sa_y.value())
        self.show_selected_area()
        
    
    def set_lr(self):
        self.lr = numpy.array([self.tw.pos[0],self.tw.pos[1]])
        self.sa_w.setValue( self.tw.pos[0] - self.sa_x.value())       
        self.sa_h.setValue( self.tw.pos[1] - self.sa_y.value())     
        self.show_selected_area()
        
    
    def capture_area_change(self):
        print "capture_area_change"
        if(self.capture_area_fs.isChecked()):
            self.sa_group.hide()
        else:
            self.sa_group.show()
            
        self.adjustSize()
        self.main_window.adjustSize()
    
    def open_cwd(self):
        #will need to detect os and change accordingly
        os.system("open {}".format(os.getcwd()))
コード例 #20
0
ファイル: options.py プロジェクト: jnoortheen/nigandu
class optdlg(QDialog):
	def __init__(self, parent=None):
		super(optdlg, self).__init__(parent)
		self.setFixedSize(484, 399)
		appicom = QIcon(":/icons/njnlogo.png")
		self.setWindowIcon(appicom)
		self.setWindowTitle("Nigandu English to Tamil Dictionary | OPTIONS")

		self.buttonBox = QDialogButtonBox(self)
		self.buttonBox.setEnabled(True)
		self.buttonBox.setGeometry(QRect(350, 20, 121, 200))

		self.buttonBox.setOrientation(Qt.Vertical)
		self.buttonBox.setStandardButtons(QDialogButtonBox.Apply|QDialogButtonBox.Cancel|QDialogButtonBox.Ok)
		self.buttonBox.setCenterButtons(True)
		self.restorebtn = QPushButton(self)
		self.restorebtn.setGeometry(QRect(354, 360, 121, 23))
		self.restorebtn.setText("&RestoreDefults")

		self.fontbox = QGroupBox(self)
		self.fontbox.setGeometry(QRect(10, 10, 331, 141))
		self.spinBox = QSpinBox(self.fontbox)
		self.spinBox.setGeometry(QRect(100, 20, 81, 21))
		self.spinBox.setMinimum(10)
		self.spinBox.setMaximum(24)
		self.label = QLabel(self.fontbox)
		self.label.setGeometry(QRect(20, 20, 71, 21))
		self.label.setText("Font Size:")
		self.fontbox.setTitle("Font")
		self.samplefontbox = QGroupBox(self)
		self.samplefontbox.setGeometry(QRect(20, 50, 291, 91))
		self.samplefontbox.setTitle("Sample Text")
		self.sampletxt = QLabel(self.samplefontbox)
		self.sampletxt.setGeometry(QRect(20, 20, 251, 61))
		self.sampletxt.setText("AaBbCcDdEeFfGgHhIiJjKkLlYyZz")

		self.clipbox = QGroupBox(self)
		self.clipbox.setGeometry(QRect(10, 160, 331, 61))
		self.clipbox.setTitle("ClipBoard Options")
		self.checkclip = QCheckBox(self.clipbox)
		self.checkclip.setGeometry(QRect(20, 20, 301, 31))
		self.checkclip.setText("Allow copy from clipboard on start-up")


		self.histbox = QGroupBox(self)
		self.histbox.setGeometry(QRect(10, 230, 331, 91))
		self.histbox.setTitle("History")
		self.checkshowhistdock = QCheckBox(self.histbox)
		self.checkshowhistdock.setGeometry(QRect(20, 60, 301, 17))

		self.checkshowhistdock.setText("Show History Dock on the right side")
		self.checkdelhist = QCheckBox(self.histbox)
		self.checkdelhist.setGeometry(QRect(20, 30, 301, 17))
		self.checkdelhist.setText("Clear all the past history records")

		self.bkmbox = QGroupBox(self)
		self.bkmbox.setGeometry(QRect(10, 330, 331, 61))
		self.bkmbox.setTitle("Book Marks")
		self.checkshowbkmdock = QCheckBox(self.bkmbox)
		self.checkshowbkmdock.setGeometry(QRect(20, 30, 301, 17))
		self.checkshowbkmdock.setText("Show Book Marks Dock on the right side.")

		self.spinBox.valueChanged[int].connect(self.setsampletxt)
		self.restorebtn.clicked.connect(self.setdeafults)
		self.buttonBox.rejected.connect(self.close)


	def setdeafults(self):
		self.spinBox.setValue(13)
		self.checkshowhistdock.setChecked(True)
		self.checkshowbkmdock.setChecked(True)
		self.checkclip.setChecked(True)
		self.checkdelhist.setChecked(False)

	def setsampletxt(self, i):
		font = QFont()
		font.setPixelSize(i)
		self.sampletxt.setFont(font)
コード例 #21
0
ファイル: editor.py プロジェクト: MrFrangipane/frangitron-dmx
class MainWindow(QWidget):
    def __init__(self, fixtures_folder, parent=None):
        QWidget.__init__(self, parent)
        self.current_fixture = None
        self.fixtures_folder = fixtures_folder
        self.setWindowTitle("Frangitron DMX program editor")

        self.text = QPlainTextEdit()
        font = QFont("Monospace")
        font.setStyleHint(QFont.TypeWriter)
        font.setPixelSize(16)
        self.text.setFont(font)
        self.text.setStyleSheet(
            "color: white; background-color: rgb(30, 30, 30)")

        self.combo_fixture = QComboBox()

        self.frame_programs = QWidget()
        self.checkboxes_programs = list()
        self.layout_programs = QGridLayout(self.frame_programs)

        self.spinner_offset = QSpinBox()
        self.spinner_offset.setMinimum(1)
        self.spinner_offset.setMaximum(512)
        self.spinner_offset.setValue(1)
        self.spinner_offset.valueChanged.connect(self.address_changed)

        self.doc = QPlainTextEdit()
        self.doc.setReadOnly(True)
        self.doc.setFont(font)

        self.status = QLabel()

        layout = QGridLayout(self)
        layout.addWidget(self.combo_fixture, 0, 1)
        layout.addWidget(self.spinner_offset, 0, 2)
        layout.addWidget(self.frame_programs, 1, 1)
        layout.addWidget(self.text, 0, 0, 3, 1)
        layout.addWidget(self.doc, 2, 1, 1, 2)
        layout.addWidget(self.status, 3, 0, 1, 3)
        layout.setColumnStretch(0, 60)
        layout.setColumnStretch(1, 40)

        self.resize(1280, 800)

        self.streamer = Streamer(self.fixtures_folder)

        self.combo_fixture.addItems(sorted(self.streamer.fixtures))
        self.combo_fixture.currentIndexChanged.connect(self.fixture_changed)

        self.timer = QTimer()
        self.timer.timeout.connect(self.tick)
        self.timer.start(500.0 / FRAMERATE)
        self.should_reload = True

        self.fixture_changed()

    def selected_programs(self):
        return [
            chk.text() for chk in self.checkboxes_programs if chk.isChecked()
        ]

    def update_programs(self):
        selected_programs = self.selected_programs()

        for checkbox_program in self.checkboxes_programs:
            self.layout_programs.removeWidget(checkbox_program)
            checkbox_program.deleteLater()
        self.checkboxes_programs = list()

        for i, program_name in enumerate(
                sorted(self.current_fixture.programs.keys())):
            column = i // 4
            row = i % 4

            new_checkbox = QCheckBox(program_name)
            new_checkbox.setChecked(program_name in selected_programs)

            self.layout_programs.addWidget(new_checkbox, row, column)
            self.checkboxes_programs.append(new_checkbox)

    def address_changed(self):
        self.current_fixture.address = self.spinner_offset.value()
        self.doc.setPlainText(self.current_fixture.doc())
        self.update_programs()

    def fixture_changed(self):
        self.current_fixture = self.streamer.fixtures[
            self.combo_fixture.currentText()]
        self.address_changed()
        self.streamer.reset_expressions()
        with open(self.current_fixture.programs_filepath, 'r') as f_programs:
            self.text.setPlainText(f_programs.read())

    def tick(self):
        if self.should_reload:
            self.current_fixture.reload_programs()
            self.update_programs()
            self.streamer.reset_state()
            program = PROGRAM.replace('__fixture__', self.current_fixture.name)
            program = program.replace('__address__',
                                      str(self.current_fixture.address))
            program = program.replace(
                '__programs__', ", ".join([
                    '"{}"'.format(prog) for prog in self.selected_programs()
                ]))
            self.streamer.load(programs_source=program)
            self.streamer.program_clicked("1")

        else:
            state = self.streamer.state

            if state:
                self.status.setStyleSheet(
                    "background-color: green; color: white; padding: 5px")
                self.status.setText(state.context)
            else:
                self.status.setStyleSheet(
                    "background-color: red; color: white; padding: 5px")
                self.status.setText("{} : {}".format(state.context,
                                                     state.exception))

            if self.current_fixture is None: return

            with open(self.current_fixture.programs_filepath,
                      'w') as f_programs:
                f_programs.write(self.text.toPlainText())

        self.should_reload = not self.should_reload

    def closeEvent(self, event):
        self.timer.stop()
        self.streamer.load(programs_source="")
        self.streamer.program_clicked("1")
        sleep(2.0 / float(FRAMERATE))
        self.streamer.stop()
        event.accept()
コード例 #22
0
ファイル: PushupForm.py プロジェクト: davcri/Pushup-app
class PushupForm(QDialog):
    '''
    classdocs
    '''
    pushupCreated = Signal(Pushup_Model)
    
    def __init__(self, athlete):
        '''
        Constructor
        '''
        QDialog.__init__(self)
        
        self.setWindowTitle("Pushup form")
        self.athlete = athlete
        self.pushupForm = QFormLayout()
        self.createGUI()
        
    def createGUI(self):
        self.series = QSpinBox()
        self.series.setMinimum(1)
        
        self.repetitions = QSpinBox()
        self.repetitions.setMaximum(512)
        
        self.avgHeartRateToggle = QCheckBox()
        self.avgHeartRateToggle.toggled.connect(self._toggleHeartRateSpinBox)
        
        self.avgHeartRate = QSpinBox()
        self.avgHeartRate.setMinimum(30)
        self.avgHeartRate.setMaximum(250)
        self.avgHeartRate.setValue(120)
        self.avgHeartRate.setDisabled(True)
        
        self.dateSelector_widget = QCalendarWidget()
        self.dateSelector_widget.setMaximumDate(QDate.currentDate())
        
        self.addButton = QPushButton("Add pushup")
        self.addButton.setMaximumWidth(90)
        self.addButton.clicked.connect(self._createPushup)
        
        self.cancelButton = QPushButton("Cancel")
        self.cancelButton.setMaximumWidth(90)
        self.cancelButton.clicked.connect(self.reject)
        
        self.pushupForm.addRow("Series", self.series)
        self.pushupForm.addRow("Repetitions", self.repetitions)
        self.pushupForm.addRow("Store average heart rate ? ", self.avgHeartRateToggle)
        self.pushupForm.addRow("Average Heart Rate", self.avgHeartRate)
        self.pushupForm.addRow("Exercise Date", self.dateSelector_widget)
        
        btnsLayout = QVBoxLayout()
        btnsLayout.addWidget(self.addButton)
        btnsLayout.addWidget(self.cancelButton)        
        btnsLayout.setAlignment(Qt.AlignRight)
        
        layoutWrapper = QVBoxLayout()
        layoutWrapper.addLayout(self.pushupForm)
        layoutWrapper.addLayout(btnsLayout)
        
        self.setLayout(layoutWrapper)        
        
    def _createPushup(self):        
        exerciseDate = self.dateSelector_widget.selectedDate()
        exerciseDate = self.qDate_to_date(exerciseDate)
        
        if self.avgHeartRateToggle.isChecked():
            heartRate = self.avgHeartRate.value()
        else:
            heartRate = None
            
        pushup = Pushup_Model(self.athlete._name, 
                              exerciseDate, 
                              heartRate, 
                              self.series.value(),
                              self.repetitions.value())

        self.pushupCreated.emit(pushup)
        self.accept()       
    
    def _toggleHeartRateSpinBox(self):
        if self.avgHeartRateToggle.isChecked():
            self.avgHeartRate.setDisabled(False)
        else:
            self.avgHeartRate.setDisabled(True)
        
    def qDate_to_date(self, qDate):        
        return date(qDate.year(), qDate.month(),qDate.day())
        
コード例 #23
0
class DoFPParametersDialog(QDialog):
  
  AFTER_CONSTRUCTION_ALLFRAC = 1
  AFTER_CONSTRUCTION_RANGESTRING = 2
  AFTER_CONSTRUCTION_TOTOP = 3
  
  def __init__(self, rangeConstructor=1.0,  boardCombo=None, title="Enter first range arguments", parent=None):
    super(DoFPParametersDialog, self).__init__(parent)
    self._after_method = 2
    self._board_combo = boardCombo
    label_constructor = QLabel("Constructor argument <b>(initFrac)</b>")
    self._spinbox_constructor = QSpinBox()
    self._spinbox_constructor.setMaximum(9999)
    self._spinbox_constructor.setValue(rangeConstructor)
    label_after_construction = QLabel("After construction method")
    self._radiogroup_methods = HorizontalRadioGroup(["setRangeString()", "setAllFracs()", "setToTop()"])
    self._radiogroup_methods.radio_checked.connect(self._updateLayout)
    self._radiogroup_methods._radios[0].setChecked(True) # dunno why it's not checked by default
    label_method_args = QLabel("Method arguments")
    self._widget_method_args = SetRangeStringCompound()
    button_ok = QPushButton("Ok")
    button_ok.clicked.connect(self.accept)
    button_cancel = QPushButton("Cancel")
    button_cancel.clicked.connect(self.reject)
    layout = QGridLayout()
    row = 0; col = 0;
    layout.addWidget(label_constructor, row, col)
    col += 1
    layout.addWidget(self._spinbox_constructor, row, col)
    row += 1; col = 0;
    layout.addWidget(label_after_construction, row, col)
    col += 1
    layout.addWidget(self._radiogroup_methods)
    row += 1; col = 0;
    layout.addWidget(label_method_args, row, col)
    col += 1
    self._update_pos = (row, col)
    layout.addWidget(self._widget_method_args, row, col)
    row += 1; col = 0
    layout.addWidget(button_ok, row, col)
    col += 1
    layout.addWidget(button_cancel, row, col)
    self.setLayout(layout)
    self.setWindowTitle(title)
    
  def _updateLayout(self, radioString):
    self._widget_method_args.setParent(None)
    self.layout().removeWidget(self._widget_method_args)
    if radioString == "setRangeString()":
      self._after_method = self.AFTER_CONSTRUCTION_RANGESTRING
      self._widget_method_args = SetRangeStringCompound()
    elif radioString == "setAllFracs()":
      self._after_method = self.AFTER_CONSTRUCTION_ALLFRAC
      self._widget_method_args = SetAllFracsSpinBox()
    elif radioString == "setToTop()":
      self._after_method = self.AFTER_CONSTRUCTION_TOTOP
      self._widget_method_args = SetToTopCompound(self._board_combo)
    self.layout().update()
    self.layout().addWidget(self._widget_method_args, self._update_pos[0], self._update_pos[1])
    
  def getRange(self):
    # construct a range object and return it
    r = Range(self._spinbox_constructor.value())
    if self._after_method == self.AFTER_CONSTRUCTION_ALLFRAC:
      r.setAllFracs(self._widget_method_args.value())
    elif self._after_method == self.AFTER_CONSTRUCTION_RANGESTRING:
      r.setRangeString(self._widget_method_args.lineedit_string.text(), 
                       self._widget_method_args.spinbox_value.value())
    elif self._after_method == self.AFTER_CONSTRUCTION_TOTOP:
      r.setToTop(self._widget_method_args.spinbox_fraction.value(), 
                 self._board_combo.boards()[self._widget_method_args.combobox_board.currentIndex()])
    return r
コード例 #24
0
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):

        lbMinWidth = 65
        # leMinWidth = 200

        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(400, 310)

        # self.centralwidget = QWidget(MainWindow)
        self.mainSplitter = QSplitter(Qt.Horizontal, MainWindow)
        self.mainSplitter.setObjectName("centralwidget")
        self.mainSplitter.setProperty("childrenCollapsible", False)
        MainWindow.setCentralWidget(self.mainSplitter)

        self.leftSplitter = QSplitter(Qt.Vertical, self.mainSplitter)
        self.leftSplitter.setProperty("childrenCollapsible", False)
        ##### login_gbox
        self.login_gbox = QGroupBox(self.leftSplitter)
        self.login_gbox.setFlat(True)
        self.login_gbox.setObjectName("login_gbox")

        login_gbox_layout = QVBoxLayout(self.login_gbox)
        login_gbox_csf_layout = QHBoxLayout()
        login_gbox_account_layout = QHBoxLayout()
        login_gbox_connect_layout = QHBoxLayout()
        login_gbox_layout.addLayout(login_gbox_csf_layout)
        login_gbox_layout.addLayout(login_gbox_account_layout)
        login_gbox_layout.addLayout(login_gbox_connect_layout)

        self.lb_client_secrets_file_path = QLabel(self.login_gbox)
        self.lb_client_secrets_file_path.setObjectName("lb_client_secrets_file_path")
        self.lb_client_secrets_file_path.setMinimumWidth(lbMinWidth)

        self.client_secrets_file_path_le = QLineEdit(self.login_gbox)
        self.client_secrets_file_path_le.setObjectName("client_secrets_file_path_le")

        self.client_secret_file_path_tBtn = QToolButton(self.login_gbox)
        self.client_secret_file_path_tBtn.setObjectName("client_secret_file_path_tBtn")

        login_gbox_csf_layout.addWidget(self.lb_client_secrets_file_path)
        login_gbox_csf_layout.addWidget(self.client_secrets_file_path_le)
        login_gbox_csf_layout.addWidget(self.client_secret_file_path_tBtn)

        self.lb_account = QLabel(self.login_gbox)
        self.lb_account.setMaximumWidth(lbMinWidth)
        self.lb_account.setObjectName("lb_account")

        self.remove_account_btn = QToolButton(self.login_gbox)
        self.remove_account_btn.setObjectName("remove_account_btn")
        self.remove_account_btn.setMinimumWidth(20)
        self.remove_account_btn.setEnabled(False)

        self.add_account_btn = QToolButton(self.login_gbox)
        self.add_account_btn.setObjectName("add_account_btn")
        self.add_account_btn.setMinimumWidth(20)

        self.accounts_cb = QComboBox(self.login_gbox)
        self.accounts_cb.setObjectName("accounts_cb")

        login_gbox_account_layout.addWidget(self.lb_account)
        login_gbox_account_layout.addWidget(self.remove_account_btn)
        login_gbox_account_layout.addWidget(self.add_account_btn)
        login_gbox_account_layout.addWidget(self.accounts_cb)

        self.lb_decryption_key = QLabel(self.login_gbox)
        self.lb_decryption_key.setObjectName("lb_decryption_key")
        self.lb_decryption_key.setMinimumWidth(lbMinWidth)
        self.lb_decryption_key.hide()

        self.decryption_key_le = QLineEdit(self.login_gbox)
        self.decryption_key_le.setEchoMode(QLineEdit.Password)
        self.decryption_key_le.setObjectName("decryption_key_le")
        self.decryption_key_le.hide()

        self.connect_btn = QPushButton(self.login_gbox)
        self.connect_btn.setEnabled(False)
        self.connect_btn.setObjectName("connect_btn")

        login_gbox_connect_layout.addWidget(self.lb_decryption_key)
        login_gbox_connect_layout.addWidget(self.decryption_key_le)
        login_gbox_connect_layout.addWidget(self.connect_btn)

        #### search_gbox
        self.search_gbox = QGroupBox(self.leftSplitter)
        self.search_gbox.setFlat(True)
        self.search_gbox.setObjectName("search_gbox")
        self.search_gbox.hide()

        search_gbox_layout = QVBoxLayout(self.search_gbox)
        search_gbox_mailbox_layout = QVBoxLayout()
        search_gbox_date_layout = QHBoxLayout()
        search_gbox_from_layout = QHBoxLayout()
        search_gbox_to_layout = QHBoxLayout()
        search_gbox_subject_layout = QHBoxLayout()
        search_gbox_threads_layout = QHBoxLayout()
        search_gbox_paramaters_layout = QHBoxLayout()

        search_gbox_layout.addLayout(search_gbox_mailbox_layout)
        search_gbox_layout.addLayout(search_gbox_date_layout)
        search_gbox_layout.addLayout(search_gbox_from_layout)
        search_gbox_layout.addLayout(search_gbox_to_layout)
        search_gbox_layout.addLayout(search_gbox_subject_layout)
        search_gbox_layout.addLayout(search_gbox_threads_layout)
        search_gbox_layout.addLayout(search_gbox_paramaters_layout)

        self.lb_select_mailbox = QLabel(self.search_gbox)
        self.lb_select_mailbox.setObjectName("lb_select_mailbox")
        self.mailboxes_lw = QListWidget(self.search_gbox)
        self.mailboxes_lw.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.mailboxes_lw.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.mailboxes_lw.setObjectName("mailboxes_lw")
        search_gbox_mailbox_layout.addWidget(self.lb_select_mailbox)
        search_gbox_mailbox_layout.addWidget(self.mailboxes_lw)

        self.after_date_cb = QCheckBox(self.search_gbox)
        self.after_date_cb.setObjectName("after_date_cb")
        self.after_date_cb.setMinimumWidth(lbMinWidth)
        self.after_date_cb.setMaximumWidth(lbMinWidth)
        self.after_date_edit = QDateEdit(self.search_gbox)
        self.after_date_edit.setCalendarPopup(True)
        self.after_date_edit.setObjectName("after_date_edit")
        self.after_date_edit.setDate(QDate.currentDate().addDays(-365))
        self.after_date_edit.setMaximumDate(QDate.currentDate())
        self.after_date_edit.setEnabled(False)
        self.before_date_cb = QCheckBox(self.search_gbox)
        self.before_date_cb.setObjectName("before_date_cb")
        self.before_date_cb.setMinimumWidth(70)
        self.before_date_cb.setMaximumWidth(70)
        self.before_date_edit = QDateEdit(self.search_gbox)
        self.before_date_edit.setCalendarPopup(True)
        self.before_date_edit.setObjectName("before_date_edit")
        self.before_date_edit.setDate(QDate.currentDate())
        self.before_date_edit.setMaximumDate(QDate.currentDate())
        self.before_date_edit.setEnabled(False)
        search_gbox_date_layout.addWidget(self.after_date_cb)
        search_gbox_date_layout.addWidget(self.after_date_edit)
        search_gbox_date_layout.addWidget(self.before_date_cb)
        search_gbox_date_layout.addWidget(self.before_date_edit)

        self.lb_from = QLabel(self.search_gbox)
        self.lb_from.setObjectName("lb_from")
        self.lb_from.setMinimumWidth(lbMinWidth)
        self.from_le = QLineEdit(self.search_gbox)
        self.from_le.setObjectName("from_le")
        search_gbox_from_layout.addWidget(self.lb_from)
        search_gbox_from_layout.addWidget(self.from_le)

        self.lb_to = QLabel(self.search_gbox)
        self.lb_to.setObjectName("lb_to")
        self.lb_to.setMinimumWidth(lbMinWidth)
        self.to_le = QLineEdit(self.search_gbox)
        self.to_le.setObjectName("to_le")
        search_gbox_to_layout.addWidget(self.lb_to)
        search_gbox_to_layout.addWidget(self.to_le)

        self.lb_subject = QLabel(self.search_gbox)
        self.lb_subject.setObjectName("lb_subject")
        self.lb_subject.setMinimumWidth(lbMinWidth)
        self.subject_le = QLineEdit(self.search_gbox)
        self.subject_le.setObjectName("subject_le")
        search_gbox_subject_layout.addWidget(self.lb_subject)
        search_gbox_subject_layout.addWidget(self.subject_le)

        self.lb_threads = QLabel(self.search_gbox)
        self.lb_threads.setObjectName("lb_threads")
        self.lb_threads.setMaximumWidth(lbMinWidth)
        self.thread_count_sb = QSpinBox(self.search_gbox)
        self.thread_count_sb.setMinimum(1)
        self.thread_count_sb.setMaximum(10)
        self.thread_count_sb.setObjectName("thread_count_sb")
        self.html_radio = QRadioButton(self.search_gbox)
        self.html_radio.setObjectName("html_radio")
        self.text_radio = QRadioButton(self.search_gbox)
        self.text_radio.setObjectName("text_radio")
        self.extactTypeButtonGroup = QButtonGroup(self)
        self.extactTypeButtonGroup.addButton(self.html_radio)
        self.extactTypeButtonGroup.addButton(self.text_radio)
        self.html_radio.setChecked(True)
        self.search_btn = QPushButton(self.search_gbox)
        self.search_btn.setObjectName("search_btn")
        search_gbox_threads_layout.addWidget(self.lb_threads)
        search_gbox_threads_layout.addWidget(self.thread_count_sb)
        search_gbox_threads_layout.addWidget(self.html_radio)
        search_gbox_threads_layout.addWidget(self.text_radio)
        search_gbox_threads_layout.addWidget(self.search_btn)

        self.parameters_cb = QCheckBox(self.search_gbox)
        self.parameters_cb.setText("")
        self.parameters_cb.setObjectName("parameters_cb")
        self.parameters_le = QLineEdit(self.search_gbox)
        self.parameters_le.setEnabled(False)
        self.parameters_le.setObjectName("parameters_le")
        search_gbox_paramaters_layout.addWidget(self.parameters_cb)
        search_gbox_paramaters_layout.addWidget(self.parameters_le)

        #### log_gbox
        self.log_gbox = QGroupBox(self.leftSplitter)
        self.log_gbox.setFlat(True)
        self.log_gbox.setObjectName("log_gbox")
        log_layout = QVBoxLayout(self.log_gbox)
        self.log_te = QTextEdit(self.log_gbox)
        self.log_te.setLineWrapMode(QTextEdit.NoWrap)
        self.log_te.setReadOnly(True)
        self.log_te.setTextInteractionFlags(Qt.TextSelectableByKeyboard | Qt.TextSelectableByMouse)
        self.log_te.setObjectName("log_te")

        self.disconnect_btn = QPushButton(self.log_gbox)
        self.disconnect_btn.setObjectName("disconnect_btn")
        self.disconnect_btn.hide()
        log_layout.addWidget(self.log_te)
        log_layout_btn = QHBoxLayout()
        log_layout.addLayout(log_layout_btn)
        log_layout_btn.addWidget(self.disconnect_btn)
        log_layout_btn.addStretch()

        #### links_gbox
        self.links_gbox = QGroupBox(self.mainSplitter)
        self.links_gbox.setFlat(True)
        self.links_gbox.setObjectName("links_gbox")
        self.links_gbox.hide()
        links_gbox_layout = QVBoxLayout(self.links_gbox)
        links_gbox_links_layout = QVBoxLayout()
        links_gbox_buttons_layout = QHBoxLayout()
        links_gbox_layout.addLayout(links_gbox_links_layout)
        links_gbox_layout.addLayout(links_gbox_buttons_layout)

        self.links_text_edit = QTextEdit(self.links_gbox)
        self.links_text_edit.setObjectName("links_text_edit")
        links_gbox_links_layout.addWidget(self.links_text_edit)

        self.export_txt_btn = QPushButton(self.links_gbox)
        self.export_txt_btn.setObjectName("export_txt_btn")
        self.export_txt_btn.setEnabled(False)
        self.export_html_btn = QPushButton(self.links_gbox)
        self.export_html_btn.setObjectName("export_html_btn")
        self.export_html_btn.setEnabled(False)

        links_gbox_buttons_layout.addWidget(self.export_txt_btn)
        links_gbox_buttons_layout.addWidget(self.export_html_btn)
        
        ### menubar
        self.menubar = QMenuBar(MainWindow)
        # self.menubar.setGeometry(QRect(0, 0, 860, 21))
        self.menubar.setObjectName("menubar")
        self.menu_file = QMenu(self.menubar)
        self.menu_file.setObjectName("menu_file")
        self.menu_help = QMenu(self.menubar)
        self.menu_help.setObjectName("menu_help")
        MainWindow.setMenuBar(self.menubar)
        self.action_about = QAction(MainWindow)
        self.action_about.setObjectName("action_about")
        self.action_About_Qt = QAction(MainWindow)
        self.action_About_Qt.setObjectName("action_About_Qt")
        self.action_exit = QAction(MainWindow)
        self.action_exit.setObjectName("action_exit")
        self.actionSave = QAction(MainWindow)
        self.actionSave.setObjectName("actionSave")
        self.action_Gmail_Advanced_Search_Syntax = QAction(MainWindow)
        self.action_Gmail_Advanced_Search_Syntax.setObjectName("action_Gmail_Advanced_Search_Syntax")
        self.menu_file.addAction(self.action_exit)
        self.menu_help.addAction(self.action_Gmail_Advanced_Search_Syntax)
        self.menu_help.addSeparator()
        self.menu_help.addAction(self.action_about)
        self.menu_help.addAction(self.action_About_Qt)
        self.menubar.addAction(self.menu_file.menuAction())
        self.menubar.addAction(self.menu_help.menuAction())
        
        self.retranslateUi(MainWindow)
        QMetaObject.connectSlotsByName(MainWindow)
        MainWindow.setTabOrder(self.client_secrets_file_path_le, self.client_secret_file_path_tBtn)
        MainWindow.setTabOrder(self.client_secret_file_path_tBtn, self.remove_account_btn)
        MainWindow.setTabOrder(self.remove_account_btn, self.add_account_btn)
        MainWindow.setTabOrder(self.add_account_btn, self.accounts_cb)
        MainWindow.setTabOrder(self.decryption_key_le, self.connect_btn)
        MainWindow.setTabOrder(self.connect_btn, self.log_te)
        MainWindow.setTabOrder(self.log_te, self.mailboxes_lw)
        MainWindow.setTabOrder(self.mailboxes_lw, self.after_date_cb)
        MainWindow.setTabOrder(self.after_date_cb, self.after_date_edit)
        MainWindow.setTabOrder(self.after_date_edit, self.before_date_cb)
        MainWindow.setTabOrder(self.before_date_cb, self.before_date_edit)
        MainWindow.setTabOrder(self.before_date_edit, self.from_le)
        MainWindow.setTabOrder(self.from_le, self.to_le)
        MainWindow.setTabOrder(self.to_le, self.subject_le)
        MainWindow.setTabOrder(self.subject_le, self.thread_count_sb)
        MainWindow.setTabOrder(self.thread_count_sb, self.html_radio)
        MainWindow.setTabOrder(self.html_radio, self.text_radio)
        MainWindow.setTabOrder(self.text_radio, self.search_btn)
        MainWindow.setTabOrder(self.search_btn, self.parameters_cb)
        MainWindow.setTabOrder(self.parameters_cb, self.parameters_le)
        MainWindow.setTabOrder(self.parameters_le, self.disconnect_btn)
        MainWindow.setTabOrder(self.disconnect_btn, self.links_text_edit)
        MainWindow.setTabOrder(self.links_text_edit, self.export_txt_btn)
        MainWindow.setTabOrder(self.export_txt_btn, self.export_html_btn)
        MainWindow.setTabOrder(self.export_html_btn, self.mailboxes_lw)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(QApplication.translate("MainWindow", "Gmail URL Parser", None, QApplication.UnicodeUTF8))
        self.login_gbox.setTitle(QApplication.translate("MainWindow", "  Client secrets file path  ", None, QApplication.UnicodeUTF8))
        self.client_secrets_file_path_le.setPlaceholderText(QApplication.translate("MainWindow", "Please select your client secrets file", None, QApplication.UnicodeUTF8))
        self.lb_client_secrets_file_path.setText(QApplication.translate("MainWindow", "Path", None, QApplication.UnicodeUTF8))
        self.connect_btn.setText(QApplication.translate("MainWindow", "Connect", None, QApplication.UnicodeUTF8))
        self.client_secret_file_path_tBtn.setText(QApplication.translate("MainWindow", "...", None, QApplication.UnicodeUTF8))
        self.lb_account.setText(QApplication.translate("MainWindow", "Account", None, QApplication.UnicodeUTF8))
        self.add_account_btn.setText(QApplication.translate("MainWindow", "+", None, QApplication.UnicodeUTF8))
        self.remove_account_btn.setText(QApplication.translate("MainWindow", "-", None, QApplication.UnicodeUTF8))
        self.decryption_key_le.setPlaceholderText(QApplication.translate("MainWindow", "Decryption key", None, QApplication.UnicodeUTF8))
        self.lb_decryption_key.setText(QApplication.translate("MainWindow", "Key", None, QApplication.UnicodeUTF8))
        self.log_gbox.setTitle(QApplication.translate("MainWindow", "  Log  ", None, QApplication.UnicodeUTF8))
        self.search_gbox.setTitle(QApplication.translate("MainWindow", "  Search Parameters  ", None, QApplication.UnicodeUTF8))
        self.lb_to.setText(QApplication.translate("MainWindow", "To", None, QApplication.UnicodeUTF8))
        self.lb_from.setText(QApplication.translate("MainWindow", "From", None, QApplication.UnicodeUTF8))
        self.lb_subject.setText(QApplication.translate("MainWindow", "Subject", None, QApplication.UnicodeUTF8))
        self.search_btn.setText(QApplication.translate("MainWindow", "Search", None, QApplication.UnicodeUTF8))
        self.after_date_edit.setDisplayFormat(QApplication.translate("MainWindow", "yyyy-MM-dd", None, QApplication.UnicodeUTF8))
        self.before_date_edit.setDisplayFormat(QApplication.translate("MainWindow", "yyyy-MM-dd", None, QApplication.UnicodeUTF8))
        self.lb_select_mailbox.setToolTip(QApplication.translate("MainWindow", "<html><head/><body><p>Select multiple items to select labels</p></body></html>", None, QApplication.UnicodeUTF8))
        self.lb_select_mailbox.setText(QApplication.translate("MainWindow", "Select Mailbox or Labels", None, QApplication.UnicodeUTF8))
        self.after_date_cb.setText(QApplication.translate("MainWindow", "After", None, QApplication.UnicodeUTF8))
        self.before_date_cb.setText(QApplication.translate("MainWindow", "Before", None, QApplication.UnicodeUTF8))
        self.html_radio.setText(QApplication.translate("MainWindow", "html", None, QApplication.UnicodeUTF8))
        self.text_radio.setText(QApplication.translate("MainWindow", "text", None, QApplication.UnicodeUTF8))
        self.lb_threads.setText(QApplication.translate("MainWindow", "Threads", None, QApplication.UnicodeUTF8))
        self.links_gbox.setTitle(QApplication.translate("MainWindow", "  Links  ", None, QApplication.UnicodeUTF8))
        self.disconnect_btn.setText(QApplication.translate("MainWindow", "Disconnect", None, QApplication.UnicodeUTF8))
        self.export_txt_btn.setText(QApplication.translate("MainWindow", "Export as txt", None, QApplication.UnicodeUTF8))
        self.export_html_btn.setText(QApplication.translate("MainWindow", "Export as HTML", None, QApplication.UnicodeUTF8))
        self.menu_file.setTitle(QApplication.translate("MainWindow", "File", None, QApplication.UnicodeUTF8))
        self.menu_help.setTitle(QApplication.translate("MainWindow", "Help", None, QApplication.UnicodeUTF8))
        self.action_about.setText(QApplication.translate("MainWindow", "About", None, QApplication.UnicodeUTF8))
        self.action_About_Qt.setText(QApplication.translate("MainWindow", "About Qt", None, QApplication.UnicodeUTF8))
        self.action_exit.setText(QApplication.translate("MainWindow", "Exit", None, QApplication.UnicodeUTF8))
        self.action_exit.setShortcut(QApplication.translate("MainWindow", "Ctrl+Q", None, QApplication.UnicodeUTF8))
        self.actionSave.setText(QApplication.translate("MainWindow", "Save", None, QApplication.UnicodeUTF8))
        self.action_Gmail_Advanced_Search_Syntax.setText(QApplication.translate("MainWindow", "Gmail Advanced Search Syntax", None, QApplication.UnicodeUTF8))
コード例 #25
0
ファイル: gui.py プロジェクト: KittyTristy/ADLMIDI-pyGUI
class MainWindow(QMainWindow):
	def __init__(self):
		super(MainWindow, self).__init__()		
		self.debug = debug

		self.progset = QSettings("ADLMIDI-pyGUI", "ADLMIDI-pyGUI")
		
		self.about_window = None
		self.settings_window = None
		self.paused = False

		self.MaxRecentFiles = int(self.progset.value("file/MaxRecentFiles", 5))

		self.recentList = self.progset.value("file/recent", [])
		if type(self.recentList) is unicode: self.recentList = [self.recentList]

		self.banks = [	" 0 = AIL (Star Control 3, Albion, Empire 2, Sensible Soccer, Settlers 2, many others)",
						"01 = Bisqwit (selection of 4op and 2op)",
						"02 = HMI (Descent, Asterix)",
						"03 = HMI (Descent:: Int)",
						"04 = HMI (Descent:: Ham)",
						"05 = HMI (Descent:: Rick)",
						"06 = HMI (Descent 2)",
						"07 = HMI (Normality)",
						"08 = HMI (Shattered Steel)",
						"09 = HMI (Theme Park)",
						"10 = HMI (3d Table Sports, Battle Arena Toshinden)",
						"11 = HMI (Aces of the Deep)",
						"12 = HMI (Earthsiege)",
						"13 = HMI (Anvil of Dawn)",
						"14 = DMX (Doom           :: partially pseudo 4op)",
						"15 = DMX (Hexen, Heretic :: partially pseudo 4op)",
						"16 = DMX (MUS Play       :: partially pseudo 4op)",
						"17 = AIL (Discworld, Grandest Fleet, Pocahontas, Slob Zone 3d, Ultima 4, Zorro)",
						"18 = AIL (Warcraft 2)",
						"19 = AIL (Syndicate)",
						"20 = AIL (Guilty, Orion Conspiracy, Terra Nova Strike Force Centauri :: 4op)",
						"21 = AIL (Magic Carpet 2)",
						"22 = AIL (Nemesis)",
						"23 = AIL (Jagged Alliance)",
						"24 = AIL (When Two Worlds War :: 4op, MISSING INSTRUMENTS)",
						"25 = AIL (Bards Tale Construction :: MISSING INSTRUMENTS)",
						"26 = AIL (Return to Zork)",
						"27 = AIL (Theme Hospital)",
						"28 = AIL (National Hockey League PA)",
						"29 = AIL (Inherit The Earth)",
						"30 = AIL (Inherit The Earth, file two)",
						"31 = AIL (Little Big Adventure :: 4op)",
						"32 = AIL (Wreckin Crew)",
						"33 = AIL (Death Gate)",
						"34 = AIL (FIFA International Soccer)",
						"35 = AIL (Starship Invasion)",
						"36 = AIL (Super Street Fighter 2 :: 4op)",
						"37 = AIL (Lords of the Realm :: MISSING INSTRUMENTS)",
						"38 = AIL (SimFarm, SimHealth :: 4op)",
						"39 = AIL (SimFarm, Settlers, Serf City)",
						"40 = AIL (Caesar 2 :: partially 4op, MISSING INSTRUMENTS)",
						"41 = AIL (Syndicate Wars)",
						"42 = AIL (Bubble Bobble Feat. Rainbow Islands, Z)",
						"43 = AIL (Warcraft)",
						"44 = AIL (Terra Nova Strike Force Centuri :: partially 4op)",
						"45 = AIL (System Shock :: partially 4op)",
						"46 = AIL (Advanced Civilization)",
						"47 = AIL (Battle Chess 4000 :: partially 4op, melodic only)",
						"48 = AIL (Ultimate Soccer Manager :: partially 4op)",
						"49 = AIL (Air Bucks, Blue And The Gray, America Invades, Terminator 2029)",
						"50 = AIL (Ultima Underworld 2)",
						"51 = AIL (Kasparov's Gambit)",
						"52 = AIL (High Seas Trader :: MISSING INSTRUMENTS)",
						"53 = AIL (Master of Magic, Master of Orion 2 :: 4op, std percussion)",
						"54 = AIL (Master of Magic, Master of Orion 2 :: 4op, orchestral percussion)",
						"55 = SB  (Action Soccer)",
						"56 = SB  (3d Cyberpuck :: melodic only)",
						"57 = SB  (Simon the Sorcerer :: melodic only)",
						"58 = OP3 (The Fat Man 2op set)",
						"59 = OP3 (The Fat Man 4op set)",
						"60 = OP3 (JungleVision 2op set :: melodic only)",
						"61 = OP3 (Wallace 2op set, Nitemare 3D :: melodic only)",
						"62 = TMB (Duke Nukem 3D)",
						"63 = TMB (Shadow Warrior)",
						"64 = DMX (Raptor)"
					]
					
		self.openicon  = QIcon.fromTheme('document-open', QIcon('img/load.png'))
		self.saveicon  = QIcon.fromTheme('document-save', QIcon('img/save.png'))
		self.playicon  = QIcon.fromTheme('media-playback-start', QIcon('img/play.png'))
		self.pauseicon = QIcon.fromTheme('media-playback-pause', QIcon('img/pause.png'))
		self.stopicon  = QIcon.fromTheme('media-playback-stop', QIcon('img/stop.png'))
		self.quiticon  = QIcon.fromTheme('application-exit', QIcon('img/quit.png'))
		self.abouticon = QIcon.fromTheme('help-about', QIcon('img/about.png'))
		self.setticon  = QIcon.fromTheme('preferences-desktop', QIcon('img/settings.png'))

		self.winsetup()

	def addWorker(self, worker):
		worker.message.connect(self.update)
		worker.finished.connect(self.workerFinished)
		self.threads.append(worker)

	def workerFinished(self):
		pass
		#barf('MSG', 'Thread completed the task!')

	def killWorkers(self):
		pass
		#for worker in self.threads:
		#	worker.terminate()
		
	def winsetup(self):
		self.setWindowIcon(QIcon('img/note.png'))
		
		openFile = QAction(self.openicon, 'Open', self)
		openFile.setShortcut('Ctrl+O')
		openFile.triggered.connect(self.load)
		
		saveFile = QAction(self.saveicon, 'Save', self)
		saveFile.setShortcut('Ctrl+S')
		saveFile.triggered.connect(self.save)
		
		playFile = QAction(self.playicon, 'Play', self)
		playFile.setShortcut('Ctrl+P')
		playFile.triggered.connect(self.play)
		
		pausePlayb = QAction(self.pauseicon, 'Pause', self)
		pausePlayb.setShortcut('Ctrl+R')
		pausePlayb.triggered.connect(self.pause)
		
		stopPlay = QAction(self.stopicon, 'Stop', self)
		stopPlay.setShortcut('Ctrl+Z')
		stopPlay.triggered.connect(self.stop)
		
		exitAction = QAction(self.quiticon, 'Quit', self)
		exitAction.setShortcut('Ctrl+X')
		exitAction.triggered.connect(self.quit)
		
		aboutdlg = QAction(self.abouticon, 'About', self)
		aboutdlg.setShortcut('Ctrl+A')
		aboutdlg.triggered.connect(self.about)
		
		showSett = QAction(self.setticon, 'Settings', self)
		showSett.triggered.connect(self.settings)

		menubar = self.menuBar()

		fileMenu = menubar.addMenu('&File')
		configMenu = menubar.addMenu('&Options')
		configMenu.setStyleSheet("border: 1px solid black;")
		
		self.setLooped = QAction('Loop', configMenu, checkable=True)
		if self.progset.value("sound/Looped") == 'true': self.setLooped.setChecked(True)
		else: self.setLooped.setChecked(False)
		self.setLooped.setShortcut('Ctrl+L')
		
		self.setAutoplay = QAction('Autoplay', configMenu, checkable=True)
		if self.progset.value("sound/Autoplay") == 'true': self.setAutoplay.setChecked(True)
		else: self.setAutoplay.setChecked(False)
		self.setAutoplay.setShortcut('Ctrl+K')
		
		configMenu.addAction(self.setAutoplay)
		configMenu.addAction(self.setLooped)

		fileMenu.setStyleSheet("border: 1px solid black;")
		fileMenu.addAction(openFile)
		fileMenu.addAction(saveFile)
		fileMenu.addSeparator()

		self.recentMenu = fileMenu.addMenu('Recent')
		self.rfUpdate()

		fileMenu.addSeparator()
		fileMenu.addAction(showSett)
		fileMenu.addSeparator()
		fileMenu.addAction(exitAction)

		helpMenu = menubar.addMenu('&Help')
		helpMenu.setStyleSheet("border: 1px solid black;")
		helpMenu.addAction(aboutdlg)
		
		self.numCards = QSpinBox()
		numCards_text = QLabel(" OPL : ")
		self.numCards.setRange(1, 100)
		self.numCards.setValue(int(self.progset.value("sound/numCards", 3)))
		self.numCards.valueChanged.connect(self.updateMax4ops)
		
		self.fourOps = QSpinBox()
		fourOps_text = QLabel(" 4op Ch : ")
		self.fourOps.setRange(0, self.numCards.value()*6)
		self.fourOps.setValue(int(self.progset.value("sound/fourOps", self.numCards.value()*6)))
		
		self.twoOps = QSpinBox()
		twoOps_text = QLabel(" 2op Ch : ")
		self.twoOps.setValue((self.numCards.value()*12 - self.fourOps.value()))
		self.twoOps.setRange(self.twoOps.value(), self.twoOps.value())
		
		toolbar = self.addToolBar('Media')
		toolbar.addAction(playFile)
		toolbar.addAction(pausePlayb)
		toolbar.addAction(stopPlay)
		toolbar.setMovable(False)
		toolbar.addSeparator()
		toolbar.addWidget(numCards_text)
		toolbar.addWidget(self.numCards)
		toolbar.addSeparator()
		toolbar.addWidget(fourOps_text)
		toolbar.addWidget(self.fourOps)
		#toolbar.addSeparator()
		#toolbar.addWidget(twoOps_text)
		#toolbar.addWidget(self.twoOps)
		
		self.statusBar()
		
		self.setFixedSize(380, 90)
		self.center()
		self.setWindowTitle('ADLMIDI pyGUI')
		self.show()
		
		if self.debug: barf("MSG", "Loaded Main Window", True, False)
		self.update("ready")

		self.threads = []
		self.addWorker(AdlMidi(1))
		self.addWorker(AdlMidiSave(2))

	def rfUpdate(self):
		self.recentMenu.clear()
		def recentfile(f2l):
			return lambda: self.load2(f2l)
		self.recentFileActs = []
		recentLength = len(self.recentList)
		for i in range(self.MaxRecentFiles):
			try:
				if i >= recentLength: break
				rev = (recentLength-1)-i
				filetoload = self.recentList[rev]
				filename = path.split(filetoload)[1]
				self.fileact = QAction(filename, self.recentMenu)
				self.fileact.triggered.connect(recentfile(filetoload))
				self.recentFileActs.append(self.fileact)
			except Exception: pass
		for i in range(self.MaxRecentFiles):
			try: self.recentMenu.addAction(self.recentFileActs[i])
			except Exception: pass

	def get_bank(self):
		try:
			selection = self.settings_window.combo.currentText()
			selection = str(selection[0])+str(selection[1])
			return int(selection)
		except Exception: return 1
		
	def center(self):
		qr = self.frameGeometry()
		cp = QDesktopWidget().availableGeometry().center()
		qr.moveCenter(cp)
		self.move(qr.topLeft())

	def about(self):
		if self.about_window is None:
			window = QMessageBox(self)
			self.about_window = window
		else: window = self.about_window
		window = self.about_window
		window.setWindowIcon(QIcon(self.abouticon))
		window.setWindowTitle('About ADLMIDI pyGUI')
		
		credits = "<center><b>ADLMIDI pyGUI v%s (%s)</b><br>Developed by Tristy H. \"KittyTristy\"<br>[<a href=\"https://github.com/KittyTristy/ADLMIDI-pyGUI\">Website</a>] [<a href=\"mailto:[email protected]\">Email</a>] <br><br><br>" % (__version__, system())
		title = "<b>ADLMIDI pyGUI</b> is a GUI wrapper<br>written in Python for use with..<br><br><b>ADLMIDI: MIDI Player<br>for Linux and Windows with OPL3 emulation</b><br>"
		cw = "(C) -- <a href=\"http://iki.fi/bisqwit/source/adlmidi.html\">http://iki.fi/bisqwit/source/adlmidi.html</a></center>"
		credits = credits + title + cw
		window.setText(credits)
			
		window.show()
		window.activateWindow()
		window.raise_()
		
	def settings(self):
		if self.settings_window is None:
			window = QDialog(self)
			self.settings_window = window
		else: window = self.settings_window
		window = self.settings_window
		window.setWindowTitle('Settings')
		
		window.notelabel = QLabel("Currently these settings are only guaranteed to work prior to loading the first MIDI!\nYou'll have to restart ADLMIDI pyGui to change them again if they stop working. \n\nSorry! This will be fixed soon!")
		window.notelabel.setWordWrap(True)
		window.notelabel.setStyleSheet("font-size: 8pt; border-style: dotted; border-width: 1px; padding: 12px;")
		window.banklabel = QLabel("<B>Choose Instrument Bank</B>")
		window.space     = QLabel("")
		window.optlabel  = QLabel("<B>Options</B>")
		
		window.combo = QComboBox()
		window.combo.addItems(self.banks)
		#window.combo.setMaximumWidth(350)
		window.combo.setMaxVisibleItems(12)
		window.combo.setStyleSheet("combobox-popup: 0;")
		window.combo.setCurrentIndex(int(self.progset.value("sound/bank", 1)))
		window.combo.currentIndexChanged.connect(self.saveSettings)
		
		window.perc		= QCheckBox("Adlib Percussion Instrument Mode")
		#window.perc.stateChanged.connect(self.checkOpts)
		window.tremamp  = QCheckBox("Tremolo Amplification Mode")
		#window.tremamp.stateChanged.connect(self.checkOpts)
		window.vibamp   = QCheckBox("Vibrato Amplification Mode")
		#window.vibamp.stateChanged.connect(self.checkOpts)
		window.modscale = QCheckBox("Scaling of Modulator Volume")
		#window.modscale.stateChanged.connect(self.checkOpts)
		
		window.okButton = QPushButton('OK')
		window.okButton.clicked.connect(window.hide)
		
		vbox = QVBoxLayout()
		vbox.addWidget(window.space)
		vbox.addWidget(window.banklabel)
		vbox.addWidget(window.combo)
		vbox.addWidget(window.space)
		vbox.addWidget(window.optlabel)
		vbox.addWidget(window.perc)
		vbox.addWidget(window.tremamp)
		vbox.addWidget(window.vibamp)
		vbox.addWidget(window.modscale)
		vbox.addWidget(window.notelabel)
		
		hbox = QHBoxLayout()
		hbox.addStretch(1)
		hbox.addWidget(window.okButton)
		
		vbox.addLayout(hbox)
		window.setLayout(vbox) 
		
		window.setFixedSize(530, 369)
		window.show()
		window.activateWindow()
		window.raise_()
		
	def updateMax4ops(self):
		self.fourOps.setMaximum(self.numCards.value()*6)
		self.fourOps.setValue(self.numCards.value()*6)
		barf("DBG", "Updating Maximum of 4ops Chs to %s" % (self.numCards.value()*6), True, False)
		#self.twoOps.setValue(self.numCards.value()*12 - self.fourOps.value())
		#self.twoOps.setRange(self.twoOps.value(), self.twoOps.value())
		
	def checkOpts(self):
		global arglist
		#barf("ACT", "Checking if Options have changed..", True, False)
		arglist = []
		try:
			if QAbstractButton.isChecked(self.settings_window.perc) and not ('-p' in arglist): arglist.append('-p')
			elif not QAbstractButton.isChecked(self.settings_window.perc) and ('-p' in arglist): arglist.remove('-p')
		except Exception: pass
		try:
			if QAbstractButton.isChecked(self.settings_window.tremamp) and not ('-t' in arglist): arglist.append('-t')
			elif not QAbstractButton.isChecked(self.settings_window.tremamp) and ('-t' in arglist): arglist.remove('-t')
		except Exception: pass
		try:
			if QAbstractButton.isChecked(self.settings_window.vibamp) and not ('-v' in arglist): arglist.append('-v')
			elif not QAbstractButton.isChecked(self.settings_window.vibamp) and ('-v' in arglist): arglist.remove('-v')
		except Exception: pass
		try:
			if QAbstractButton.isChecked(self.settings_window.modscale) and not ('-s' in arglist): arglist.append('-s')
			elif not QAbstractButton.isChecked(self.settings_window.modscale) and ('-s' in arglist): arglist.remove('-s')
		except Exception: pass

		self.sel_bank = self.get_bank()

	def saveSettings(self):
		self.progset.setValue("sound/Autoplay", self.setAutoplay.isChecked())
		self.progset.setValue("sound/Looped", self.setLooped.isChecked())
		self.progset.setValue("sound/numCards", self.numCards.value())
		self.progset.setValue("sound/fourOps", self.fourOps.value())
		try: self.progset.setValue("sound/bank", self.settings_window.combo.currentIndex())
		except Exception: pass
		if len(self.recentList) >= 1: self.progset.setValue("file/recent", self.recentList[-self.MaxRecentFiles:])
		self.progset.setValue("file/MaxRecentFiles", self.MaxRecentFiles)
		#allkeys = self.progset.allKeys()
		#for key in allkeys:
		#	barf('DBG', str(key) + " " + str(self.progset.value(key)))
		
	def closeEvent(self, event):
		self.stop()
		#self.pkill()
		self.saveSettings()
		barf("DBG", "Quitting", True, False)
		
	def quit(self):
		self.stop()
		#self.pkill()
		self.saveSettings()
		barf("DBG", "Quitting", True, False)
		exit(0)

	def pkill(self):
		try: p.kill()
		except Exception: pass
		
	##############################################################
	##### Statusbar Functions ####################################
	##############################################################
	
	def clear(self):
		try: self.statusBar().removeWidget(self.playStatus)
		except Exception: pass
	
	@Slot(str)
	def update(self, status=''):
		self.clear()
		if status == "ready": text = "&nbsp;<B>Ready</b>"
		elif status == "play": text = "&nbsp;<B>Now Playing: </B>" + path.split(f.name)[1]
		elif status == "loop": text = "&nbsp;<B>Looping: </B>" + path.split(f.name)[1]
		elif status == "stop": text = "&nbsp;<B>Stopped: </B>" + path.split(f.name)[1]
		elif status == "pause": text = "&nbsp;<B>Paused: </B>" + path.split(f.name)[1]
		elif status == "loading": text = "&nbsp;<B>Loading.. </B>"
		elif status == "load": text = "&nbsp;<B>Loaded: </B>" + path.split(f.name)[1]
		elif status == "saving": text = "&nbsp;<B>Saving.. </B>"
		elif status == "saved": text = "&nbsp;<B>Saved as: </B>" + "saved/" + path.splitext(path.split(f.name)[1])[0] + ".wav"
		self.playStatus = QLabel(text)
		self.statusBar().addPermanentWidget(self.playStatus, 1)
		
	##############################################################
	####### Sound Functions ######################################
	##############################################################

	def play(self):
		global Paused, arglist
		if f != None and Paused == False:
			Paused = False
			self.stop()
			self.checkOpts()
			if not self.setLooped.isChecked(): arglist.append('-nl')
			arglist.append(str(self.progset.value("sound/bank", 1)))
			arglist.append(str(self.numCards.value()))
			arglist.append(str(self.fourOps.value()))
			for worker in self.threads:
				if worker.id == 1:
					worker.start()
		elif f != None and Paused == True:
			os.kill(p.pid, signal.SIGCONT)
			self.update("play")
			Paused = False

	def pause(self):
		global p, Paused
		if f != None:
			try:
				if Paused == False:
					os.kill(p.pid, signal.SIGSTOP)
					self.update("pause")
					Paused = True
				elif Paused == True:
					os.kill(p.pid, signal.SIGCONT)
					self.update("play")
					Paused = False
			except Exception: pass

	def stop(self):
		global Paused
		if f != None:
			Paused = False 
			self.pkill()
			self.killWorkers()
			self.update("stop")
				
	##############################################################
	##### Load/Save Functions ####################################
	##############################################################

	def load(self):
		global f
		lastdir = str(self.progset.value("file/lastdir", ""))
		fname, _ = QFileDialog.getOpenFileName(None, 'Open File', lastdir, "MIDI Audio File (*.mid *.MID)")
		if fname != "":
			f = file(fname, 'r')
			if not f.name in self.recentList: self.recentList.append(f.name)
			else:
				self.recentList.remove(f.name)
				self.recentList.append(f.name)
			self.progset.setValue("file/lastdir", path.split(f.name)[0])
			self.rfUpdate()
			self.update("load")
			self.pkill()
			if self.debug: barf("SAV", "Loaded %s" % path.split(f.name)[1], True, False)
			if self.setAutoplay.isChecked(): self.play()
			else: self.update("load")

	def load2(self, r_file=None):
		global f
		f = file(r_file, 'r')
		self.recentList.remove(f.name)
		self.recentList.append(f.name)
		self.rfUpdate()
		self.update("load")
		self.pkill()
		if self.debug: barf("SAV", "Loaded %s" % path.split(f.name)[1], True, False)
		if self.setAutoplay.isChecked(): self.play()
		else: self.update("load")
			
	def save(self):
		if f != None:
			self.stop()
			for worker in self.threads:
				if worker.id == 2:
					worker.start()