You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何为QTableWidget列应用验证器?实现仅大写字母输入

Alright, let's break down how to make your QTableWidget's second column only accept uppercase letters, plus how to apply validators to columns in general. I'll walk you through two practical approaches that fit different use cases:

1. Quick Fix: Assign Validators Directly to Column Cells (Small Tables)

If your table isn't too large or dynamic, you can set up a validator for the second column's editors when the user starts editing a cell. Here's how to do it in PyQt/PySide (C++ logic is nearly identical):

First, create a validator that matches only uppercase letters using a regular expression. Then, hook into the table's cellDoubleClicked signal to attach the validator to the editor when the user clicks into the second column:

from PyQt5.QtWidgets import QTableWidget, QLineEdit, QRegularExpressionValidator
from PyQt5.QtCore import QRegularExpression

class CustomTable(QTableWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setColumnCount(3)
        self.setRowCount(5)
        
        # Listen for when a cell is double-clicked to start editing
        self.cellDoubleClicked.connect(self.setup_uppercase_validator)

    def setup_uppercase_validator(self, row, column):
        # Target the second column (remember: Qt uses 0-based indexing)
        if column != 1:
            return
            
        # Get or create the line edit editor for the cell
        editor = self.cellWidget(row, column)
        if not editor:
            editor = QLineEdit()
            # Validator that allows only uppercase letters (adjust regex if you want to require at least one character)
            validator = QRegularExpressionValidator(QRegularExpression("^[A-Z]*$"))
            editor.setValidator(validator)
            # Optional: Auto-convert lowercase input to uppercase for better UX
            editor.textChanged.connect(lambda text: editor.setText(text.upper()))
            self.setCellWidget(row, column, editor)
2. Clean & Scalable: Use a Custom Item Delegate (Large/Dynamic Tables)

For bigger tables or if you want reusable logic, a custom QItemDelegate is the way to go. Delegates control how cells are edited, so we can override the createEditor method to apply the validator only to the second column:

from PyQt5.QtWidgets import QItemDelegate, QLineEdit
from PyQt5.QtCore import QRegularExpression, QModelIndex

class UppercaseColumnDelegate(QItemDelegate):
    def createEditor(self, parent, option, index):
        # Create the default editor (a QLineEdit for text cells)
        editor = super().createEditor(parent, option, index)
        
        # Only apply the validator to the second column (index 1)
        if index.column() == 1 and isinstance(editor, QLineEdit):
            # Regex to match uppercase letters only
            validator = QRegularExpressionValidator(QRegularExpression("^[A-Z]*$"))
            editor.setValidator(validator)
            # Optional auto-convert to uppercase
            editor.textChanged.connect(lambda text: editor.setText(text.upper()))
        return editor

# Then attach the delegate to your table:
my_table = QTableWidget()
my_table.setItemDelegate(UppercaseColumnDelegate())

Key Notes:

  • The regex ^[A-Z]*$ allows empty inputs. If you want to require at least one uppercase letter, use ^[A-Z]+$ instead.
  • Qt uses 0-based indexing, so the "second column" is always index 1—don't mix this up with 1-based numbering!
  • For C++ projects, the logic is the same: create a subclass of QItemDelegate, override createEditor, and initialize a QRegularExpressionValidator with the appropriate regex.

内容的提问来源于stack exchange,提问作者VaP

火山引擎 最新活动