Chapter 10. Input Elements

Ever faced a situation where users “type whatever” and your app falls apart with errors, weird values, and endless handlers? Every Qt developer knows this feeling: the interface is ready, but data input becomes a minefield.

This chapter will reveal how to turn input into a controlled process: clean, predictable, and user-friendly. Here you’ll discover a non-obvious insight: many input tasks (clipboard, drag & drop, selection, undo/redo) are already solved by Qt—you just need to properly “enable” them instead of reinventing the wheel. Result: less code, fewer bugs, faster development.

The focus is on QLineEdit + textChanged/textEdited signals, Password mode, “smart” restrictions via QValidator, plus document work with QTextEdit/QTextDocument (including export to ODF/HTML and printing to PDF via QPrinter). Plus—practical breakdown of QSyntaxHighlighter: why professional developers use syntax highlighting even in utilities.

Don’t delay: one wrong input strategy usually surfaces on the first release—and fixing it costs more than getting it right from the start.

This chapter includes ready-to-use code examples.

Chapter Self-Check

What’s the key difference between textChanged() and textEdited() signals in QLineEdit?Answer
Correct answer: textChanged() is emitted on any text change (including programmatic via setText()), while textEdited() is only emitted on changes made manually by the user.
Why is QPlainTextEdit recommended over QTextEdit for editing plain text?Answer
Correct answer: QPlainTextEdit doesn’t support RTF formatting, making it more lightweight, simple, and efficient for plain text work.
What role does the QTextDocument object play in text editing widgets?Answer
Correct answer: QTextDocument stores document content and provides methods to work with it (undo/redo, search, formatting); many QTextEdit methods delegate to QTextDocument.
Why isn’t a pointer to the SyntaxHighlighter object saved after creation in the syntax highlighting example?Answer
Correct answer: The SyntaxHighlighter object automatically sets QTextDocument as its parent, which will manage its memory and automatically delete it when destroyed.
Why are states like InsideCStyleComment and InsideCString used in the syntax coloring example?Answer
Correct answer: The highlightBlock() method processes only one line at a time, so states are needed to track multi-line constructs (/**/ comments and strings) that can start on one line and end on another.
What three values can the validate() method return and when is each used?Answer
Correct answer: Invalid—string cannot be accepted; Intermediate—string is not final (e.g., “1” for range 50-100); Acceptable—string is correct and can be accepted.
Why is the Intermediate state needed in validators when we have Invalid and Acceptable?Answer
Correct answer: Intermediate allows users to enter intermediate values during typing (e.g., when entering “100”, “1” is entered first), without prematurely blocking input.
How can you create a PDF file from QTextEdit content without using QTextDocumentWriter?Answer
Correct answer: Create a QPrinter object with high resolution mode, set PdfFormat, specify the filename, and call document()->print(&printer).
In what situations is setReadOnly(true) better than a validator?Answer
Correct answer: setReadOnly() is suitable when you need to completely prohibit editing and allow only viewing; validators are used to control input format when editing is allowed.
Why does the append() method in QTextEdit work faster and require less memory than insertPlainText()?Answer
Correct answer: Text added via append() isn’t added to the undo() operation list, eliminating the need to store change history for this operation.
What ready-made validator classes does Qt provide and what are they used for?Answer
Correct answer: QIntValidator and QDoubleValidator for validating integer and floating-point number input respectively; QRegularExpressionValidator for validation using regular expressions.

Hands-On Assignments

Easy Level

Registration Form with Validation
Create a simple registration form with three fields: username (letters only), email, and password (hidden input). Add a label showing how many characters are entered in the username field. Implement a custom validator for the username field that prohibits entering digits and special characters.
Hints: Use QLineEdit for input fields. For password, apply setEchoMode(QLineEdit::Password). Create a validator class inherited from QValidator and check characters using QString::contains() and regular expressions. Connect the textChanged() signal to a slot for updating the character counter.

Medium Level

Simple Text Editor with Formatting
Create a text editor based on QTextEdit with a toolbar containing buttons for: saving to HTML and PDF, clearing text, undo/redo actions, increasing/decreasing font size. Add a word counter that updates when text changes. Implement the ability to open and display simple HTML files.
Hints: Use QVBoxLayout for layout. Create QHBoxLayout for buttons. For PDF saving, use QPrinter with setOutputFormat(QPrinter::PdfFormat). Connect undoAvailable/redoAvailable signals to manage button activity. For word counting, use toPlainText().split(QRegularExpression(“\\s+”), Qt::SkipEmptyParts).count().

Hard Level

Editor with JSON Syntax Highlighting
Create an editor for JSON files with custom syntax highlighting. Implement a QSyntaxHighlighter that colors: keys (blue), string values (green), numbers (orange), boolean values and null (purple), curly and square brackets (bold). Add real-time JSON validation—when entering invalid JSON, show an error indicator and highlight the problematic line with red background.
Hints: Inherit from QSyntaxHighlighter and implement highlightBlock(). Use regular expressions to find patterns: keys (“.*”:), strings (“.*”), numbers (\b\d+\.?\d*\b). For validation, use QJsonDocument::fromJson() and check for parsing errors. Apply setFormat() with QTextCharFormat to highlight problematic line backgrounds. Use previousBlockState() to track multi-line strings.

💬 Join the Discussion!

Figured out input widgets and validation? Managed to implement your own syntax highlighting?

Share your findings on working with QTextEdit, tell us about difficulties with validators, or ask questions about syntax highlighting!

Maybe you found a more elegant solution for the coloring algorithm or an interesting way to apply QSyntaxHighlighter?

Leave a Reply

Your email address will not be published. Required fields are marked *