當前位置: 首頁>>代碼示例>>Python>>正文


Python QLineEdit.clear方法代碼示例

本文整理匯總了Python中PyQt5.QtWidgets.QLineEdit.clear方法的典型用法代碼示例。如果您正苦於以下問題:Python QLineEdit.clear方法的具體用法?Python QLineEdit.clear怎麽用?Python QLineEdit.clear使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在PyQt5.QtWidgets.QLineEdit的用法示例。


在下文中一共展示了QLineEdit.clear方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: FindDialog

# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import clear [as 別名]
class FindDialog(QDialog):
    def __init__(self, parent=None):
        super(FindDialog, self).__init__(parent)

        findLabel = QLabel("Enter the name of a contact:")
        self.lineEdit = QLineEdit()

        self.findButton = QPushButton("&Find")
        self.findText = ''

        layout = QHBoxLayout()
        layout.addWidget(findLabel)
        layout.addWidget(self.lineEdit)
        layout.addWidget(self.findButton)

        self.setLayout(layout)
        self.setWindowTitle("Find a Contact")

        self.findButton.clicked.connect(self.findClicked)
        self.findButton.clicked.connect(self.accept)

    def findClicked(self):
        text = self.lineEdit.text()

        if not text:
            QMessageBox.information(self, "Empty Field",
                    "Please enter a name.")
            return

        self.findText = text
        self.lineEdit.clear()
        self.hide()

    def getFindText(self):
        return self.findText
開發者ID:death-finger,項目名稱:Scripts,代碼行數:37,代碼來源:part7.py

示例2: Example

# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import clear [as 別名]
class Example(QWidget, QWindow):
    def __init__(self):
        super().__init__()

        self.initUI()

    def dialoga(self):
        text, ok = QInputDialog.getText(self, "Username", "Enter your username:")

        if ok:
            text = "/username" + text
            s.sendall(str.encode(text))
        else:
            print("error: NO USERNAME")
            sys.exit()

    def initUI(self):
        self.dialoga()
        self.sendamessage = QLabel("Send:")
        self.tray_icon = SystemTrayIcon(QtGui.QIcon("Outki.ico"), self)
        self.tray_icon.show()
        self.messageEdit = QLineEdit()
        global messageBox
        messageBox = QTextEdit()
        messageBox.setReadOnly(True)
        self.sendButton = QPushButton("Send")

        grid = QGridLayout()
        grid.setSpacing(1)

        grid.addWidget(messageBox, 1, 0, 2, 4)
        grid.addWidget(self.sendamessage, 3, 0, 4, 0)
        grid.addWidget(self.messageEdit, 3, 1, 4, 2)
        grid.addWidget(self.sendButton, 3, 3, 4, 3)

        self.setLayout(grid)
        self.sendButton.clicked.connect(self.send)
        self.messageEdit.returnPressed.connect(self.send)
        threade = ThreadingExample()
        self.setGeometry(300, 300, 300, 300)
        self.setWindowTitle("Outki")
        self.setWindowIcon(QIcon("Outki.ico"))
        self.show()

    def send(self):
        tosend = self.messageEdit.text()
        self.messageEdit.clear()
        messageBox.moveCursor(QtGui.QTextCursor.End)
        messageBox.append("You: " + tosend)
        s.sendall(str.encode(tosend))
開發者ID:spider93287,項目名稱:Outki,代碼行數:52,代碼來源:OutkiClient.py

示例3: DirectorySelector

# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import clear [as 別名]
class DirectorySelector(QFrame):
    def __init__(self, parent, label_text, send_to_other=None, other=None):
        QFrame.__init__(self)

        self.parent = parent
        self.send_to_other = send_to_other
        self.other = other

        self.input_dir = None

        # Create the GUI widgets
        self.main_layout = QHBoxLayout(self)
        self.label = QLabel(label_text)
        self.dir_entry = QLineEdit()
        self.browse_button = PyQtExtras.CommandButton('Browse')
        self.browse_button.set_handler(self.on_browse)

        self.main_layout.addWidget(self.label)
        self.main_layout.addWidget(self.dir_entry)
        self.main_layout.addWidget(self.browse_button)

    def on_browse(self):
        print('Browsing for directory')
        directory = QFileDialog(self.parent).getExistingDirectory()
        if directory != None:
            self.input_dir = str(directory)
            self.dir_entry.clear()
            self.dir_entry.insert(self.input_dir)
            if self.other != None and self.send_to_other != None:
                self.send_to_other(self.other, self.input_dir)

    def get_dir(self):
        document_text = self.dir_entry.text()
        # Make sure the instance variable for the current text and the text inside the entry field match
        if document_text != self.input_dir:
            self.input_dir = document_text
        return self.input_dir

    def set_dir(self, input_dir):
        self.input_dir = input_dir
        self.dir_entry.clear()
        self.dir_entry.insert(self.input_dir)
開發者ID:jhavstad,項目名稱:model_runner,代碼行數:44,代碼來源:ModelRunnerGUIQt.py

示例4: Template

# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import clear [as 別名]
class Template(QWidget):

    def __init__(self):
        super().__init__()
        self.database = read_database(DatabaseFilename)
        self.initUI()

        # miscellaneous stuff
        self.setGeometry(300, 300, WidgetWidth, WidgetHeight)
        self.setWindowTitle('%s %s' % (ExName, ExVersion))
        self.show()

    def initUI(self):
        grid = QGridLayout()
        self.setLayout(grid)

        # row 0 of grid
        label = QLabel('Name:')
        label.setAlignment(Qt.AlignRight)
        grid.addWidget(label, 0, 0)

        self.qle_name = QLineEdit(self)
        grid.addWidget(self.qle_name, 0, 1)

        label = QLabel('    ')      # add a little spacer
        grid.addWidget(label, 0, 2)

        label = QLabel('Age:')
        label.setAlignment(Qt.AlignRight)
        grid.addWidget(label, 0, 3)

        self.qle_age = QLineEdit(self)
        grid.addWidget(self.qle_age, 0, 4)

        # row 1 of grid
        label = QLabel('Height:')
        label.setAlignment(Qt.AlignRight)
        grid.addWidget(label, 1, 3)

        self.qle_height = QLineEdit(self)
        grid.addWidget(self.qle_height, 1, 4)

        # row 2 - could use some vertical separation - just put empty label
        label = QLabel('')
        grid.addWidget(label, 2, 4)

        # row 3 of grid - a horizontal box containing buttons
        hbox = QHBoxLayout()

        hbox.addStretch(1)

        btn = QPushButton('Load', self)
        btn.clicked.connect(self.loadUser)
        hbox.addWidget(btn)

        btn = QPushButton('Clear', self)
        hbox.addWidget(btn)
        btn.clicked.connect(self.clearFields)

        btn = QPushButton('Save', self)
        hbox.addWidget(btn)
        btn.clicked.connect(self.saveUser)

        grid.addLayout(hbox, 3, 4, 4, 1)

    def clearFields(self):
        """Clear all GUI fields."""

        self.qle_name.clear()
        self.qle_age.clear()
        self.qle_height.clear()

    def loadUser(self):
        """Get data for a user from database.

        Uses the "name" lineedit to query the database
        and populate the other fields.
        """

        name = self.qle_name.text()
        if not name:
            msg = f"Sorry, you must supply a name"
            QMessageBox.warning(self, "Problem", msg)
            return

        student = get_student(self.database, name)
        if not student:
            msg = f"Sorry, student '{name}' doesn't exist in the database"
            QMessageBox.warning(self, "Problem", msg)
        else:
            age = student.get('age', '')
            height = student.get('height', '')
            self.qle_age.setText(str(age))
            self.qle_height.setText(str(height))

    def saveUser(self):
        """Save student data in lineedits to the in-memory structure."""

        name = self.qle_name.text()
        if not name:
#.........這裏部分代碼省略.........
開發者ID:rzzzwilson,項目名稱:Random-Stuff,代碼行數:103,代碼來源:test.py

示例5: SpreadSheet

# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import clear [as 別名]
class SpreadSheet(QMainWindow):

    dateFormats = ["dd/M/yyyy", "yyyy/M/dd", "dd.MM.yyyy"]

    currentDateFormat = dateFormats[0]

    def __init__(self, rows, cols, parent = None):
        super(SpreadSheet, self).__init__(parent)

        self.toolBar = QToolBar()
        self.addToolBar(self.toolBar)
        self.formulaInput = QLineEdit()
        self.cellLabel = QLabel(self.toolBar)
        self.cellLabel.setMinimumSize(80, 0)
        self.toolBar.addWidget(self.cellLabel)
        self.toolBar.addWidget(self.formulaInput)
        self.table = QTableWidget(rows, cols, self)
        for c in range(cols):
            character = chr(ord('A') + c)
            self.table.setHorizontalHeaderItem(c, QTableWidgetItem(character))

        self.table.setItemPrototype(self.table.item(rows - 1, cols - 1))
        self.table.setItemDelegate(SpreadSheetDelegate(self))
        self.createActions()
        self.updateColor(0)
        self.setupMenuBar()
        self.setupContents()
        self.setupContextMenu()
        self.setCentralWidget(self.table)
        self.statusBar()
        self.table.currentItemChanged.connect(self.updateStatus)
        self.table.currentItemChanged.connect(self.updateColor)
        self.table.currentItemChanged.connect(self.updateLineEdit)
        self.table.itemChanged.connect(self.updateStatus)
        self.formulaInput.returnPressed.connect(self.returnPressed)
        self.table.itemChanged.connect(self.updateLineEdit)
        self.setWindowTitle("Spreadsheet")

    def createActions(self):
        self.cell_sumAction = QAction("Sum", self)
        self.cell_sumAction.triggered.connect(self.actionSum)

        self.cell_addAction = QAction("&Add", self)
        self.cell_addAction.setShortcut(Qt.CTRL | Qt.Key_Plus)
        self.cell_addAction.triggered.connect(self.actionAdd)

        self.cell_subAction = QAction("&Subtract", self)
        self.cell_subAction.setShortcut(Qt.CTRL | Qt.Key_Minus)
        self.cell_subAction.triggered.connect(self.actionSubtract)

        self.cell_mulAction = QAction("&Multiply", self)
        self.cell_mulAction.setShortcut(Qt.CTRL | Qt.Key_multiply)
        self.cell_mulAction.triggered.connect(self.actionMultiply)

        self.cell_divAction = QAction("&Divide", self)
        self.cell_divAction.setShortcut(Qt.CTRL | Qt.Key_division)
        self.cell_divAction.triggered.connect(self.actionDivide)

        self.fontAction = QAction("Font...", self)
        self.fontAction.setShortcut(Qt.CTRL | Qt.Key_F)
        self.fontAction.triggered.connect(self.selectFont)

        self.colorAction = QAction(QIcon(QPixmap(16, 16)), "Background &Color...", self)
        self.colorAction.triggered.connect(self.selectColor)

        self.clearAction = QAction("Clear", self)
        self.clearAction.setShortcut(Qt.Key_Delete)
        self.clearAction.triggered.connect(self.clear)

        self.aboutSpreadSheet = QAction("About Spreadsheet", self)
        self.aboutSpreadSheet.triggered.connect(self.showAbout)

        self.exitAction = QAction("E&xit", self)
        self.exitAction.setShortcut(QKeySequence.Quit)
        self.exitAction.triggered.connect(QApplication.instance().quit)

        self.printAction = QAction("&Print", self)
        self.printAction.setShortcut(QKeySequence.Print)
        self.printAction.triggered.connect(self.print_)

        self.firstSeparator = QAction(self)
        self.firstSeparator.setSeparator(True)

        self.secondSeparator = QAction(self)
        self.secondSeparator.setSeparator(True)

    def setupMenuBar(self):
        self.fileMenu = self.menuBar().addMenu("&File")
        self.dateFormatMenu = self.fileMenu.addMenu("&Date format")
        self.dateFormatGroup = QActionGroup(self)
        for f in self.dateFormats:
            action = QAction(f, self, checkable=True,
                    triggered=self.changeDateFormat)
            self.dateFormatGroup.addAction(action)
            self.dateFormatMenu.addAction(action)
            if f == self.currentDateFormat:
                action.setChecked(True)
                
        self.fileMenu.addAction(self.printAction)
        self.fileMenu.addAction(self.exitAction)
#.........這裏部分代碼省略.........
開發者ID:death-finger,項目名稱:Scripts,代碼行數:103,代碼來源:spreadsheet.py

示例6: DefaultAttributeHandler

# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import clear [as 別名]
class DefaultAttributeHandler(QGroupBox, AbstractAttributeHandler):
    def __init__(self, attribute, values, parent=None):
        QGroupBox.__init__(self, attribute, parent)
        self._attribute = attribute
        self._current_items = []
        self._defaults = {}
        self._inputField = None
        self._inputFieldType = None
        self._insertIndex = -1
        self._insertAtEnd = False
        self._shortcuts = {}

        # Setup GUI
        self._layout = FloatingLayout()
        self.setLayout(self._layout)
        self._buttons = {}

        # Add interface elements
        self.updateValues(values)

    def focusInputField(self, selectInput=True):
        if self._inputField is not None:
            if selectInput:
                self._inputField.selectAll()
            self._inputField.setFocus(Qt.ShortcutFocusReason)

    def addShortcut(self, shortcut, widget, value):
        if widget is not None:
            if shortcut not in self._shortcuts:
                sc = QShortcut(QKeySequence(shortcut), self)
                self._shortcuts[shortcut] = sc
                if isinstance(widget, QPushButton):
                    sc.activated.connect(bind(lambda w: w.click() if not w.isChecked() else None, widget))
                elif isinstance(widget, QLineEdit):
                    sc.activated.connect(self.focusInputField)
            else:
                raise ImproperlyConfigured("Shortcut '%s' defined more than once" % shortcut)
        else:
            raise ImproperlyConfigured("Shortcut '%s' defined for value '%s' which is hidden" % (shortcut, value))

    def updateValues(self, values):
        if isinstance(values, type):
            self.addInputField(values)
        else:
            for val in values:
                v = val
                shortcut = None
                widget = None

                # Handle the case of the value being a 2-tuple consisting of (value, shortcut)
                if type(val) is tuple or type(val) is list:
                    if len(val) == 2:
                        v = val[0]
                        shortcut = val[1]
                    else:
                        raise ImproperlyConfigured("Values must be types, strings, numbers, or tuples of length 2: '%s'" % str(val))

                # Handle the case where value is a Python type
                if isinstance(v, type):
                    if v is float or v is int or v is str:
                        self.addInputField(v)
                        widget = self._inputField
                    else:
                        raise ImproperlyConfigured("Input field with type '%s' not supported" % v)

                # * marks the position where buttons for new values will be insered
                elif val == "*" or val == "<*":
                    self._insertIndex = self._layout.count()
                elif val == "*>":
                    self._insertIndex = self._layout.count()
                    self._insertAtEnd = True

                # Add the value button
                else:
                    self.addValue(v)
                    widget = self._buttons[v]

                # If defined, add the specified shortcut
                if shortcut is not None:
                    self.addShortcut(shortcut, widget, v)

    def defaults(self):
        return self._defaults

    def autoAddEnabled(self):
        return self._insertIndex >= 0

    def onInputFieldReturnPressed(self):
        val = str(self._inputField.text())
        self.addValue(val, True)
        for item in self._current_items:
            item[self._attribute] = val
        self.updateButtons()
        self.updateInputField()
        self._inputField.clearFocus()

    def addInputField(self, _type):
        if self._inputField is None:
            self._inputFieldType = _type
            self._inputField = QLineEdit()
#.........這裏部分代碼省略.........
開發者ID:mlilien,項目名稱:sloth,代碼行數:103,代碼來源:propertyeditor.py

示例7: QtChronophoreUI

# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import clear [as 別名]

#.........這裏部分代碼省略.........
        signed in users.
        """
        names = [
            controller.get_user_name(user, full_name=CONFIG['FULL_USER_NAMES'])
            for user in controller.signed_in_users()
        ]
        self.lbl_signedin_list.setText('\n'.join(sorted(names)))

    def _show_feedback_label(self, message, seconds=None):
        """Display a message in lbl_feedback, which times out after some
        number of seconds.
        """
        if seconds is None:
            seconds = CONFIG['MESSAGE_DURATION']

        logger.debug('Label feedback: "{}"'.format(message))

        self.feedback_label_timer.timeout.connect(self._hide_feedback_label)
        self.lbl_feedback.setText(str(message))
        self.lbl_feedback.show()
        self.feedback_label_timer.start(1000 * seconds)

    def _hide_feedback_label(self):
        # TODO(amin): Figure out how to either limit the size of the label,
        # to reset the layout to a normal size upon its disappearance, or
        # both. The whole layout currently gets messed up if this label is
        # assigned a long string.
        self.lbl_feedback.setText('')
        logger.debug('Feedback label hidden')

    def _sign_button_press(self):
        """Validate input from ent_id, then sign in to the Timesheet."""
        user_id = self.ent_id.text().strip()

        try:
            status = controller.sign(user_id)

        # ERROR: User type is unknown (!student and !tutor)
        except ValueError as e:
            logger.error(e, exc_info=True)
            QMessageBox.critical(
                self,
                __title__ + ' Error',
                str(e),
                buttons=QMessageBox.Ok,
                defaultButton=QMessageBox.Ok,
            )

        # ERROR: User is unregistered
        except controller.UnregisteredUser as e:
            logger.debug(e)
            QMessageBox.warning(
                self,
                'Unregistered User',
                str(e),
                buttons=QMessageBox.Ok,
                defaultButton=QMessageBox.Ok,
            )

        # User needs to select type
        except controller.AmbiguousUserType as e:
            logger.debug(e)
            u = QtUserTypeSelectionDialog('Select User Type: ', self)
            if u.exec_() == QDialog.Accepted:
                status = controller.sign(user_id, user_type=u.user_type)
                self._show_feedback_label(
                    'Signed {}: {} ({})'.format(
                        status.in_or_out, status.user_name, status.user_type
                    )
                )

        # User has signed in or out normally
        else:
            sign_choice_confirmed = QMessageBox.question(
                self,
                'Confirm Sign-{}'.format(status.in_or_out),
                'Sign {}: {}?'.format(status.in_or_out, status.user_name),
                buttons=QMessageBox.Yes | QMessageBox.No,
                defaultButton=QMessageBox.Yes,
            )

            logger.debug('Sign {} confirmed: {}'.format(
                status.in_or_out, sign_choice_confirmed
            ))

            if sign_choice_confirmed == QMessageBox.No:
                # Undo sign-in or sign-out
                if status.in_or_out == 'in':
                    controller.undo_sign_in(status.entry)
                elif status.in_or_out == 'out':
                    controller.undo_sign_out(status.entry)
            else:
                self._show_feedback_label(
                    'Signed {}: {}'.format(status.in_or_out, status.user_name)
                )

        finally:
            self._set_signed_in()
            self.ent_id.clear()
            self.ent_id.setFocus()
開發者ID:mesbahamin,項目名稱:timebook,代碼行數:104,代碼來源:qtview.py

示例8: Calculator

# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import clear [as 別名]
class Calculator(QWidget):
    NumDigitButtons = 10
    
    def __init__(self, parent=None):
        super(Calculator, self).__init__(parent)

        self.pendingAdditiveOperator = ''
        self.pendingMultiplicativeOperator = ''

        self.sumInMemory = 0.0
        self.sumSoFar = 0.0
        self.factorSoFar = 0.0
        self.waitingForOperand = True

        self.display = QLineEdit('0')
        self.display.setReadOnly(True)
        self.display.setAlignment(Qt.AlignRight)
        self.display.setMaxLength(15)

        font = self.display.font()
        font.setPointSize(font.pointSize() + 8)
        self.display.setFont(font)

        self.digitButtons = []
        
        for i in range(Calculator.NumDigitButtons):
            self.digitButtons.append(self.createButton(str(i),
                    self.digitClicked))

        self.pointButton = self.createButton(".", self.pointClicked)
        self.changeSignButton = self.createButton(u"\N{PLUS-MINUS SIGN}",
                self.changeSignClicked)

        self.backspaceButton = self.createButton("Backspace",
                self.backspaceClicked)
        self.clearButton = self.createButton("Clear", self.clear)
        self.clearAllButton = self.createButton("Clear All", self.clearAll)

        self.clearMemoryButton = self.createButton("MC", self.clearMemory)
        self.readMemoryButton = self.createButton("MR", self.readMemory)
        self.setMemoryButton = self.createButton("MS", self.setMemory)
        self.addToMemoryButton = self.createButton("M+", self.addToMemory)

        self.divisionButton = self.createButton(u"\N{DIVISION SIGN}",
                self.multiplicativeOperatorClicked)
        self.timesButton = self.createButton(u"\N{MULTIPLICATION SIGN}",
                self.multiplicativeOperatorClicked)
        self.minusButton = self.createButton("-", self.additiveOperatorClicked)
        self.plusButton = self.createButton("+", self.additiveOperatorClicked)

        self.squareRootButton = self.createButton("Sqrt",
                self.unaryOperatorClicked)
        self.powerButton = self.createButton(u"x\N{SUPERSCRIPT TWO}",
                self.unaryOperatorClicked)
        self.reciprocalButton = self.createButton("1/x",
                self.unaryOperatorClicked)
        self.equalButton = self.createButton("=", self.equalClicked)

        mainLayout = QGridLayout()
        mainLayout.setSizeConstraint(QLayout.SetFixedSize)

        mainLayout.addWidget(self.display, 0, 0, 1, 6)
        mainLayout.addWidget(self.backspaceButton, 1, 0, 1, 2)
        mainLayout.addWidget(self.clearButton, 1, 2, 1, 2)
        mainLayout.addWidget(self.clearAllButton, 1, 4, 1, 2)

        mainLayout.addWidget(self.clearMemoryButton, 2, 0)
        mainLayout.addWidget(self.readMemoryButton, 3, 0)
        mainLayout.addWidget(self.setMemoryButton, 4, 0)
        mainLayout.addWidget(self.addToMemoryButton, 5, 0)

        for i in range(1, Calculator.NumDigitButtons):
            row = ((9 - i) / 3) + 2
            column = ((i - 1) % 3) + 1
            mainLayout.addWidget(self.digitButtons[i], row, column)

        mainLayout.addWidget(self.digitButtons[0], 5, 1)
        mainLayout.addWidget(self.pointButton, 5, 2)
        mainLayout.addWidget(self.changeSignButton, 5, 3)

        mainLayout.addWidget(self.divisionButton, 2, 4)
        mainLayout.addWidget(self.timesButton, 3, 4)
        mainLayout.addWidget(self.minusButton, 4, 4)
        mainLayout.addWidget(self.plusButton, 5, 4)

        mainLayout.addWidget(self.squareRootButton, 2, 5)
        mainLayout.addWidget(self.powerButton, 3, 5)
        mainLayout.addWidget(self.reciprocalButton, 4, 5)
        mainLayout.addWidget(self.equalButton, 5, 5)
        self.setLayout(mainLayout)

        self.setWindowTitle("Calculator")

    def digitClicked(self):
        clickedButton = self.sender()
        digitValue = int(clickedButton.text())

        if self.display.text() == '0' and digitValue == 0.0:
            return

#.........這裏部分代碼省略.........
開發者ID:death-finger,項目名稱:Scripts,代碼行數:103,代碼來源:calculator.py

示例9: MainWindow

# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import clear [as 別名]

#.........這裏部分代碼省略.........
        self.show_progress = QCheckBox("Show progress info and statistics")
        self.show_summary = QCheckBox("Show final summary of included modules")
        self.disable_console = QCheckBox("Disable the Console on MS Windows")
        for i, widget in enumerate((
            self.module, self.standalone, self.nofreeze, self.python_debug,
            self.warning, self.recurse_std, self.recurse_not, self.execute,
            self.pythonpath, self.enhaced, self.nolineno, self.rmbuilddir,
            self.nuitka_debug, self.keep_debug, self.traced, self.plusplus,
            self.experimental, self.force_clang, self.force_mingw,
            self.force_lto, self.show_scons, self.show_progress,
                self.show_summary, self.disable_console)):
            widget.setToolTip(widget.text())
            g0grid.addWidget(widget, i if i < i + 1 else i - (i - 1), i % 2)
        # group 1 paths
        self.target = QLineEdit()
        self.outdir = QLineEdit(os.path.expanduser("~"))
        self.t_icon = QLineEdit()
        self.target.setToolTip("Python App file you want to Compile to Binary")
        self.outdir.setToolTip("Folder to write Compiled Output Binary files")
        self.t_icon.setToolTip("Icon image file to embed for your Python App")
        self.target.setPlaceholderText("/full/path/to/target/python_app.py")
        self.outdir.setPlaceholderText("/full/path/to/output/folder/")
        self.t_icon.setPlaceholderText("/full/path/to/python_app/icon.png")
        self.completer, self.dirs = QCompleter(self), QDirModel(self)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)
        self.completer.popup().setStyleSheet("border: 1px solid gray")
        self.completer.popup().setVerticalScrollBarPolicy(
            Qt.ScrollBarAlwaysOff)
        self.outdir.setCompleter(self.completer)
        self.t_icon.setCompleter(self.completer)
        self.target.setCompleter(self.completer)
        self.clear_1 = QPushButton(QIcon.fromTheme("edit-clear"), "", self,
                                   clicked=lambda: self.target.clear())
        self.clear_2 = QPushButton(QIcon.fromTheme("edit-clear"), "", self,
                                   clicked=lambda: self.t_icon.clear())
        self.clear_3 = QPushButton(QIcon.fromTheme("edit-clear"), "", self,
                                   clicked=lambda: self.outdir.clear())
        self.open_1 = QPushButton(
            QIcon.fromTheme("folder-open"), "", self, clicked=lambda:
                self.target.setText(str(QFileDialog.getOpenFileName(
                    self, __doc__, os.path.expanduser("~"), """Python (*.py);;
                    Python for Windows (*.pyw);;All (*.*)""")[0])))
        self.open_2 = QPushButton(
            QIcon.fromTheme("folder-open"), "", self, clicked=lambda:
                self.t_icon.setText(str(QFileDialog.getOpenFileName(
                    self, __doc__, os.path.expanduser("~"),
                    "PNG (*.png);;JPG (*.jpg);;ICO (*.ico);;All (*.*)")[0])))
        self.open_3 = QPushButton(
            QIcon.fromTheme("folder-open"), "", self, clicked=lambda:
                self.outdir.setText(str(QFileDialog.getExistingDirectory(
                    self, __doc__, os.path.expanduser("~")))))
        self.l_icon = QLabel("Target Icon")
        g1vlay.addWidget(QLabel("<b>Target Python"), 0, 0)
        g1vlay.addWidget(self.target, 0, 1)
        g1vlay.addWidget(self.clear_1, 0, 2)
        g1vlay.addWidget(self.open_1, 0, 3)
        g1vlay.addWidget(self.l_icon, 1, 0)
        g1vlay.addWidget(self.t_icon, 1, 1)
        g1vlay.addWidget(self.clear_2, 1, 2)
        g1vlay.addWidget(self.open_2, 1, 3)
        g1vlay.addWidget(QLabel("<b>Output Folder"), 2, 0)
        g1vlay.addWidget(self.outdir, 2, 1)
        g1vlay.addWidget(self.clear_3, 2, 2)
        g1vlay.addWidget(self.open_3, 2, 3)
開發者ID:juancarlospaco,項目名稱:nuitka-gui,代碼行數:70,代碼來源:nuitka-gui.py

示例10: Layout

# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import clear [as 別名]
class Layout(QMainWindow):
    
    def __init__(self):
        super().__init__()
        self.pos = conf.position
        self.res = conf.resize
        self.statusText = 'Kullanıma Hazır !'
        self.initUI()

    def setURL(self,code):
        if len(code) == 11 :
            return conf.app.youTube_host + code

    def codeURL(self,url):
        url_data = urllib.parse.urlparse(url)
        query = urllib.parse.parse_qs(url_data.query)
        if len(query["v"][0]) and len(query["v"][0]) == 11 :
            return self.setURL(query["v"][0])
        return False


    def getSearch(self):
        searchTerm = self.searchBox.text()
        self.searchBtn.setDisabled(True)
        if len(searchTerm) == 0 :
            print('Temizlendi')
            self.infoClear()
        elif len(searchTerm) != 0 and self.searchBtn.isEnabled() == False :
            self.searchBtn.setDisabled(False)
            if len(searchTerm) == 11 :
                code = self.setURL(searchTerm)
                self.getVideo(code)

            elif len(searchTerm) == 43 :
                code = self.codeURL(searchTerm)
                if code == False :
                    self.statusBar().showMessage('Lütfen geçerli bir Youtube bağlantısı yada Video kodu girin !')
                self.getVideo(code)

            elif len(searchTerm) == 83 :
                code = self.codeURL(searchTerm)
                if code == False :
                    self.statusBar().showMessage('Lütfen geçerli bir Youtube bağlantısı yada Video kodu girin !')
                self.getVideo(code)

            else :
                self.statusBar().showMessage('Lütfen geçerli bir Youtube bağlantısı yada Video kodu girin !')
    def getVideo(self,code):
        self.setDisabled(True)
        self.statusBar().showMessage('Yükleniyor !')
        self.yt = YouTube(code)
        videos = self.yt.get_videos()
        quality = ['Kalite']
        for v in videos :
            if v.extension == 'mp4' :
                quality.append( v.resolution)
        quality = sorted(set(quality),reverse=True)
        self.quality.clear()
        self.quality.addItems(quality)
        self.quality.model().item(0).setEnabled(False)
        self.quality.show()
        self.filename = self.yt.filename
        self.info.setText(self.yt.filename)
        self.downloadBtn.show()
        self.statusBar().showMessage('Yüklendi !')
        self.setDisabled(False)

    def infoClear(self):
            self.downloadBtn.setDisabled(True)
            self.quality.clear()
            self.quality.hide()
            self.info.clear()
            self.downloadBtn.setDisabled(True)
            self.downloadBtn.hide()

    def searchChange(self):
        searchTerm = self.searchBox.text()
        if len(searchTerm) == 0 :
            self.infoClear()
            self.searchBtn.setDisabled(True)
            self.searchBtn.setDisabled(True)
            self.statusBar().showMessage(self.statusText)
        elif len(searchTerm) != 0 :
            self.statusBar().showMessage('Kullanıma Hazır !')
            self.searchBtn.setDisabled(False)


    def toolBarButtons(self):
        # Search Button
        self.searchBtn = QPushButton(conf.app.toolBar.searchBtn.title,self)
        self.searchBtn.clicked.connect(self.getSearch)
        self.searchBtn.setDisabled(True)
        self.searchBtn.move(conf.app.toolBar.searchBtn.pos.x,conf.app.toolBar.searchBtn.pos.y)
        # Download Button
        # downloadBtn = QPushButton(conf.app.toolBar.downloadBtn.title,self)
        # downloadBtn.move(conf.app.toolBar.downloadBtn.pos.x,conf.app.toolBar.downloadBtn.pos.y)

    def toolBar(self):
        self.toolBarButtons()
        self.searchBox = QLineEdit(self)
#.........這裏部分代碼省略.........
開發者ID:ferdiunal,項目名稱:Youtube-Downloader,代碼行數:103,代碼來源:layout.py

示例11: View

# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import clear [as 別名]
class View(QWidget):

    # Send data to port
    send_data           = pyqtSignal(object)
    # Chage baudrate
    baudrate_changed    = pyqtSignal(object)
    # Change end of line
    eol_changed         = pyqtSignal(object)
    # Change port
    port_changed        = pyqtSignal(object)
    # Pause model
    pause_m             = pyqtSignal(object)
    # Continue model
    start_m             = pyqtSignal(object)

    def __init__(self):
        QWidget.__init__(self)

        self.queue      = None
        self.end_cmd    = None
        self.autoscroll = False
        self.msg_sent   = False

        self.timer = QTimer()
        self.timer.timeout.connect(self.update_gui)
        self.timer.start(100)
                
        self.__initUI()

    def __initUI(self):
        vbox = QVBoxLayout(self)

        # Command box
        cmd_hbox = QHBoxLayout()

        self.cmd_edit = QLineEdit()
        cmd_hbox.addWidget(self.cmd_edit)

        cmd_btn = QPushButton('Send')
        cmd_btn.clicked.connect(self.emit_send_data)
        cmd_hbox.addWidget(cmd_btn)

        cmd_btn = QPushButton('Start')
        cmd_btn.clicked.connect(self.start_m.emit)
        cmd_hbox.addWidget(cmd_btn)

        cmd_btn = QPushButton('Stop')
        cmd_btn.clicked.connect(self.pause_m.emit)
        cmd_hbox.addWidget(cmd_btn)

        vbox.addLayout(cmd_hbox)

        # Text edit area
        self.editer = QPlainTextEdit()
        self.editer.scrollContentsBy = self.ModScrollContentsBy
        vbox.addWidget(self.editer)

        # Settings area
        stng_hbox = QHBoxLayout()

        # - Autoscroll
        chk_btn = QCheckBox('Autoscroll')
        chk_btn.stateChanged.connect(self.set_autoscroll)
        stng_hbox.addWidget(chk_btn)

        cmd_btn = QPushButton('Clear')
        cmd_btn.clicked.connect(self.editer.clear)
        stng_hbox.addWidget(cmd_btn)

        stng_hbox.addStretch(1)

        # - Ending of line
        self.eol_menu = QComboBox()
        self.eol_menu.addItem('No line ending')
        self.eol_menu.addItem('Newline')
        self.eol_menu.addItem('Carriage return')
        self.eol_menu.addItem('Both NL + CR')
        self.eol_menu.setCurrentIndex(0)
        self.eol_menu.currentIndexChanged.connect(self.emit_eol_changed)
        stng_hbox.addWidget(self.eol_menu)

        # - Baudrate select
        self.br_menu = QComboBox()
        self.br_menu.addItem('300 baud')
        self.br_menu.addItem('1200 baud')
        self.br_menu.addItem('2400 baud')
        self.br_menu.addItem('4800 baud')
        self.br_menu.addItem('9600 baud')
        self.br_menu.addItem('19200 baud')
        self.br_menu.addItem('38400 baud')
        self.br_menu.addItem('57600 baud')
        self.br_menu.addItem('115200 baud')
        self.br_menu.addItem('230400 baud')
        self.br_menu.addItem('460800 baud')
        self.br_menu.currentIndexChanged.connect(self.emit_br_changed)
        # Set default baudrate 9600
        self.br_menu.setCurrentIndex(4)

        stng_hbox.addWidget(self.br_menu)

#.........這裏部分代碼省略.........
開發者ID:alberand,項目名稱:PySM,代碼行數:103,代碼來源:view.py

示例12: SessionEditor

# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import clear [as 別名]
class SessionEditor(QDialog):
    def __init__(self, parent=None):
        super(SessionEditor, self).__init__(parent)
        self.setWindowModality(Qt.WindowModal)

        layout = QVBoxLayout()
        self.setLayout(layout)

        grid = QGridLayout()
        layout.addLayout(grid)

        self.name = QLineEdit()
        self.nameLabel = l = QLabel()
        l.setBuddy(self.name)
        grid.addWidget(l, 0, 0)
        grid.addWidget(self.name, 0, 1)

        self.autosave = QCheckBox()
        grid.addWidget(self.autosave, 1, 1)

        self.basedir = widgets.urlrequester.UrlRequester()
        self.basedirLabel = l = QLabel()
        l.setBuddy(self.basedir)
        grid.addWidget(l, 2, 0)
        grid.addWidget(self.basedir, 2, 1)

        self.inclPaths = ip = QGroupBox(self, checkable=True, checked=False)
        ipLayout = QVBoxLayout()
        ip.setLayout(ipLayout)

        self.replPaths = QCheckBox()
        ipLayout.addWidget(self.replPaths)
        self.replPaths.toggled.connect(self.toggleReplace)

        self.include = widgets.listedit.FilePathEdit()
        self.include.listBox.setDragDropMode(QAbstractItemView.InternalMove)
        ipLayout.addWidget(self.include)

        grid.addWidget(ip, 3, 1)

        self.revt = QPushButton(self)
        self.clear = QPushButton(self)
        self.revt.clicked.connect(self.revertPaths)
        self.clear.clicked.connect(self.clearPaths)

        self.include.layout().addWidget(self.revt, 5, 1)
        self.include.layout().addWidget(self.clear, 6, 1)

        layout.addWidget(widgets.Separator())
        self.buttons = b = QDialogButtonBox(self)
        layout.addWidget(b)
        b.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        b.accepted.connect(self.accept)
        b.rejected.connect(self.reject)
        userguide.addButton(b, "sessions")
        app.translateUI(self)

    def translateUI(self):
        self.nameLabel.setText(_("Name:"))
        self.autosave.setText(
            _("Always save the list of documents in this session"))
        self.basedirLabel.setText(_("Base directory:"))
        self.inclPaths.setTitle(_("Use session specific include path"))
        self.replPaths.setText(_("Replace global path"))
        self.replPaths.setToolTip(
            _("When checked, paths in LilyPond preferences are not included."))
        self.revt.setText(_("Copy global path"))
        self.revt.setToolTip(
            _("Add and edit the path from LilyPond preferences."))
        self.clear.setText(_("Clear"))
        self.clear.setToolTip(_("Remove all paths."))

    def load(self, name):
        settings = sessions.sessionGroup(name)
        self.autosave.setChecked(settings.value("autosave", True, bool))
        self.basedir.setPath(settings.value("basedir", "", str))
        self.include.setValue(
            qsettings.get_string_list(settings, "include-path"))
        self.inclPaths.setChecked(settings.value("set-paths", False, bool))
        self.replPaths.setChecked(settings.value("repl-paths", False, bool))
        if not self.replPaths.isChecked():
            self.addDisabledGenPaths()
            self.revt.setEnabled(False)
        # more settings here

    def fetchGenPaths(self):
        """Fetch paths from general preferences."""
        return qsettings.get_string_list(QSettings(),
                                         "lilypond_settings/include_path")

    def addDisabledGenPaths(self):
        """Add global paths, but set as disabled."""
        genPaths = self.fetchGenPaths()
        for p in genPaths:
            i = QListWidgetItem(p, self.include.listBox)
            i.setFlags(Qt.NoItemFlags)

    def toggleReplace(self):
        """Called when user changes setting for replace of global paths."""
        if self.replPaths.isChecked():
#.........這裏部分代碼省略.........
開發者ID:wbsoft,項目名稱:frescobaldi,代碼行數:103,代碼來源:dialog.py

示例13: MainWindow

# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import clear [as 別名]
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.fnames = []  # list of file names to be converted
        self.office_listener_started = False

        self.parse_cla()

        addQPB = QPushButton(self.tr('Add'))
        delQPB = QPushButton(self.tr('Delete'))
        clearQPB = QPushButton(self.tr('Clear'))
        vlayout1 = utils.add_to_layout('v', addQPB, delQPB, clearQPB, None)

        self.filesList = utils.FilesList()
        self.filesList.setSelectionMode(QAbstractItemView.ExtendedSelection)
        hlayout1 = utils.add_to_layout('h', self.filesList, vlayout1)

        outputQL = QLabel(self.tr('Output folder:'))
        self.toQLE = QLineEdit()
        self.toQLE.setReadOnly(True)
        self.toQTB = QToolButton()
        self.toQTB.setText('...')
        hlayout2 = utils.add_to_layout('h', outputQL, self.toQLE, self.toQTB)

        self.audiovideo_tab = AudioVideoTab(self)
        self.image_tab = ImageTab(self)
        self.document_tab = DocumentTab(self)

        self.tabs = [self.audiovideo_tab, self.image_tab, self.document_tab]
        tab_names = [self.tr('Audio/Video'), self.tr('Images'),
                     self.tr('Documents')]

        self.tabWidget = QTabWidget()
        for num, tab in enumerate(tab_names):
            self.tabWidget.addTab(self.tabs[num], tab)
        self.tabWidget.setCurrentIndex(0)

        self.origQCB = QCheckBox(
                self.tr('Save each file in the same\nfolder as input file'))
        self.deleteQCB = QCheckBox(self.tr('Delete original'))
        convertQPB = QPushButton(self.tr('&Convert'))

        hlayout3 = utils.add_to_layout('h', self.origQCB, self.deleteQCB, None)
        hlayout4 = utils.add_to_layout('h', None, convertQPB)
        final_layout = utils.add_to_layout(
                'v', hlayout1, self.tabWidget, hlayout2, hlayout3, hlayout4)

        self.dependenciesQL = QLabel()
        self.statusBar().addPermanentWidget(self.dependenciesQL, stretch=1)

        widget = QWidget()
        widget.setLayout(final_layout)
        self.setCentralWidget(widget)

        openAction = utils.create_action(
                self, self.tr('Open'), QKeySequence.Open, None,
                self.tr('Open a file'), self.filesList_add
                )
        convertAction = utils.create_action(
                self, self.tr('Convert'), 'Ctrl+C', None,
                self.tr('Convert files'), self.start_conversion
                )
        quitAction = utils.create_action(
                self, self.tr('Quit'), 'Ctrl+Q', None,
                self.tr('Quit'), self.close
                )
        edit_presetsAction = utils.create_action(
                self, self.tr('Edit Presets'), 'Ctrl+P', None,
                self.tr('Edit Presets'), self.open_dialog_presets
                )
        importAction = utils.create_action(
                self, self.tr('Import'), None, None,
                self.tr('Import presets'), self.import_presets
                )
        exportAction = utils.create_action(
                self, self.tr('Export'), None, None,
                self.tr('Export presets'), self.export_presets
                )
        resetAction = utils.create_action(
                self, self.tr('Reset'), None, None,
                self.tr('Reset presets'), self.reset_presets
                )
        syncAction = utils.create_action(
                self, self.tr('Synchronize'), None, None,
                self.tr('Synchronize presets'), self.sync_presets
                )
        removeoldAction = utils.create_action(
                self, self.tr('Remove old'), None, None,
                self.tr('Remove old presets'), self.removeold_presets
                )
        clearallAction = utils.create_action(
                self, self.tr('Clear All'), None, None,
                self.tr('Clear form'), self.clear_all
                )
        preferencesAction = utils.create_action(
                self, self.tr('Preferences'), 'Alt+Ctrl+P',
                None, self.tr('Preferences'), self.open_dialog_preferences
                )
        trackerAction = utils.create_action(
#.........這裏部分代碼省略.........
開發者ID:Ilias95,項目名稱:FF-Multi-Converter,代碼行數:103,代碼來源:ffmulticonverter.py

示例14: Actividad7

# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import clear [as 別名]
class Actividad7(QWidget):
	def __init__(self):
		super().__init__()
		self.ventana()
		
	def ventana(self):
		#Etiquetas
		self.entrada = QLineEdit("Numero de datos", self)
		self.entrada.move(5,5)
		self.combo = QComboBox(self)
		self.combo.move(160,5)
		x= QLabel("X:", self)
		x.move(5,40)
		btn= QPushButton("Calcular", self)
		btn.move(190,35)
		y = QLabel("f(X):", self)
		y.move(5,70)
		self.entradax = QLineEdit(self)
		self.entradax.move(35,35)
		self.entraday = QLineEdit(self)
		self.entraday.move(35,65)
		btn2= QPushButton("Borrar Todo", self)
		btn2.move(190,65)
		self.valor = QLineEdit("Valor a estimar en",self)
		self.valor.move(5,95)
		self.ecuacion= QLabel("Y=",self)
		self.ecuacion.move(5,130)

		#Eventos
		self.entrada.textChanged[str].connect(self.combobox)
		self.combo.activated[str].connect(self.cambio)
		self.entradax.textChanged[str].connect(self.x)
		self.entraday.textChanged[str].connect(self.y)
		btn.clicked.connect(self.boton)
		self.entrada.selectionChanged.connect(self.sel1)
		self.entradax.selectionChanged.connect(self.sel2)
		self.entraday.selectionChanged.connect(self.sel3)
		self.valor.selectionChanged.connect(self.sel4)
		btn2.clicked.connect(self.borrar)
		#Ventana
		self.setGeometry(300, 300, 310, 150)
		self.setWindowTitle("Polinomios de interpolacion de Langrange")
		self.show()
	
	def combobox(self, text):
		self.combo.clear()
		self.entradax.clear()
		self.entraday.clear()
		if text =='':
			text='0'
		for c in range(int(text)):
			self.combo.addItem(str(c+1))
			if len(xl)<= c:
				xl.append(0.0)
				yl.append(0.0)
		if text != "0":
			self.entradax.setText(str(xl[self.combo.currentIndex()]))
			self.entraday.setText(str(yl[self.combo.currentIndex()]))
			
	def cambio(self, text):
		self.entradax.setText(str(xl[int(text)-1]))
		self.entraday.setText(str(yl[int(text)-1]))
	def x(self, text):
		if text == "" or text == '-':
			text= "0"
		xl[self.combo.currentIndex()]= float(text)
	def y(self, text):
		if text == "" or text == '-':
			text= "0"
		yl[self.combo.currentIndex()]= float(text)
	def boton(self):
		if self.valor.text() == "": #Si el usuario deja en blanco el valor a conocer se conocera que es 0
			self.valor.setText("0")
		datos= int(self.entrada.text()) #datos es el numero de datos ingresados por el usuario
		cx= float(self.valor.text())#cx sera el valor que el usuario quiera conocer
		suma=0 #Se declara la sumatoria
		for c in range(datos): #Este for funciona para movernos en I
			pro=1 #Se declara la variable producto
			for c2 in range(datos):#Este for funciona para movernos en J
				if c2!=c: #Si I es diferente a J se realizara la operacion producto 
					pro*= (cx-xl[c2])/(xl[c]-xl[c2]) #Producto de
			pro*= yl[c] #Al final de pasar por cada J se multiplica por f(X) en el cual I esta actualmente
			suma+= pro #pro pasa a ser parte de la Sumatoria
		self.ecuacion.setText("Y= " + str(suma)) #Al final se imprime la Sumatoria
		self.ecuacion.adjustSize()
	def sel1(self):
		self.entrada.clear()
	def sel2(self):
		self.entradax.clear()
	def sel3(self):
		self.entraday.clear()
	def sel4(self):
		self.valor.clear()
	def borrar(self):
		for c in range(len(xl)):
			xl[c]= 0.0
			yl[c]= 0.0
		self.sel1()
		self.sel2()
		self.sel3()
#.........這裏部分代碼省略.........
開發者ID:NoelCordova,項目名稱:tadp,代碼行數:103,代碼來源:polinomioLagrage.py

示例15: Window

# 需要導入模塊: from PyQt5.QtWidgets import QLineEdit [as 別名]
# 或者: from PyQt5.QtWidgets.QLineEdit import clear [as 別名]

#.........這裏部分代碼省略.........
        accessGroup = QGroupBox("Access")

        accessLabel = QLabel("Read-only:")
        accessComboBox = QComboBox()
        accessComboBox.addItem("False")
        accessComboBox.addItem("True")

        self.accessLineEdit = QLineEdit()

        echoComboBox.activated.connect(self.echoChanged)
        validatorComboBox.activated.connect(self.validatorChanged)
        alignmentComboBox.activated.connect(self.alignmentChanged)
        inputMaskComboBox.activated.connect(self.inputMaskChanged)
        accessComboBox.activated.connect(self.accessChanged)

        echoLayout = QGridLayout()
        echoLayout.addWidget(echoLabel, 0, 0)
        echoLayout.addWidget(echoComboBox, 0, 1)
        echoLayout.addWidget(self.echoLineEdit, 1, 0, 1, 2)
        echoGroup.setLayout(echoLayout)

        validatorLayout = QGridLayout()
        validatorLayout.addWidget(validatorLabel, 0, 0)
        validatorLayout.addWidget(validatorComboBox, 0, 1)
        validatorLayout.addWidget(self.validatorLineEdit, 1, 0, 1, 2)
        validatorGroup.setLayout(validatorLayout)

        alignmentLayout = QGridLayout()
        alignmentLayout.addWidget(alignmentLabel, 0, 0)
        alignmentLayout.addWidget(alignmentComboBox, 0, 1)
        alignmentLayout.addWidget(self.alignmentLineEdit, 1, 0, 1, 2)
        alignmentGroup. setLayout(alignmentLayout)

        inputMaskLayout = QGridLayout()
        inputMaskLayout.addWidget(inputMaskLabel, 0, 0)
        inputMaskLayout.addWidget(inputMaskComboBox, 0, 1)
        inputMaskLayout.addWidget(self.inputMaskLineEdit, 1, 0, 1, 2)
        inputMaskGroup.setLayout(inputMaskLayout)

        accessLayout = QGridLayout()
        accessLayout.addWidget(accessLabel, 0, 0)
        accessLayout.addWidget(accessComboBox, 0, 1)
        accessLayout.addWidget(self.accessLineEdit, 1, 0, 1, 2)
        accessGroup.setLayout(accessLayout)

        layout = QGridLayout()
        layout.addWidget(echoGroup, 0, 0)
        layout.addWidget(validatorGroup, 1, 0)
        layout.addWidget(alignmentGroup, 2, 0)
        layout.addWidget(inputMaskGroup, 0, 1)
        layout.addWidget(accessGroup, 1, 1)
        self.setLayout(layout)

        self.setWindowTitle("Line Edits")

    def echoChanged(self, index):
        if index == 0:
            self.echoLineEdit.setEchoMode(QLineEdit.Normal)
        elif index == 1:
            self.echoLineEdit.setEchoMode(QLineEdit.Password)
        elif index == 2:
            self.echoLineEdit.setEchoMode(QLineEdit.PasswordEchoOnEdit)
        elif index == 3:
    	    self.echoLineEdit.setEchoMode(QLineEdit.NoEcho)

    def validatorChanged(self, index):
        if index == 0:
            self.validatorLineEdit.setValidator(0)
        elif index == 1:
            self.validatorLineEdit.setValidator(QIntValidator(self.validatorLineEdit))
        elif index == 2:
            self.validatorLineEdit.setValidator(QDoubleValidator(-999.0, 999.0, 2, self.validatorLineEdit))

        self.validatorLineEdit.clear()

    def alignmentChanged(self, index):
        if index == 0:
            self.alignmentLineEdit.setAlignment(Qt.AlignLeft)
        elif index == 1:
            self.alignmentLineEdit.setAlignment(Qt.AlignCenter)
        elif index == 2:
    	    self.alignmentLineEdit.setAlignment(Qt.AlignRight)

    def inputMaskChanged(self, index):
        if index == 0:
            self.inputMaskLineEdit.setInputMask('')
        elif index == 1:
            self.inputMaskLineEdit.setInputMask('+99 99 99 99 99;_')
        elif index == 2:
            self.inputMaskLineEdit.setInputMask('0000-00-00')
            self.inputMaskLineEdit.setText('00000000')
            self.inputMaskLineEdit.setCursorPosition(0)
        elif index == 3:
            self.inputMaskLineEdit.setInputMask('>AAAAA-AAAAA-AAAAA-AAAAA-AAAAA;#')

    def accessChanged(self, index):
        if index == 0:
            self.accessLineEdit.setReadOnly(False)
        elif index == 1:
            self.accessLineEdit.setReadOnly(True)
開發者ID:Axel-Erfurt,項目名稱:pyqt5,代碼行數:104,代碼來源:lineedits.py


注:本文中的PyQt5.QtWidgets.QLineEdit.clear方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。