PDA

View Full Version : Text Alignment in a textedit in qt creator



aaditya190
11th December 2013, 06:24
I wish to introduce text alignment in a textedit such that whenever I press ENTER key, It automatically takes 4 spaces in the next line just like the code editor in qt.... Is there any way to implement this? Can anyone help me out?

wagmare
11th December 2013, 07:21
use eventFilter to filter the enterKey press

eventFilter(QObject *obj, QEvent *event)
{
if (obj == textEdit) {
if (event->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
qDebug() << "Ate key press" << keyEvent->key();
return true;
} else {
return false;
}
} else {
// pass the event on to the parent class
return QMainWindow::eventFilter(obj, event);
}
}

and use settext ()

textEdit->setText("<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; text-indent:20px;\">the showing text</p>");

Lykurg
11th December 2013, 07:35
Some additional notes:

Instead of setting an event filter you can subclass QTextEdit (or QPlainTextEdit which QtC is using) and use keyPressEvent() directly. Since setText() replaces the entire previous text, better use QTextCursor. It can be received by textCursor().

aaditya190
11th December 2013, 07:36
I am using this code as an event of MainWindow in mainwindow.cpp as-:



MainWindow::eventFilter(QObject *obj, QEvent *event)
{

if (obj == ui->textEdit)
{
if (event->type() == QEvent::KeyPress)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event);
qDebug() << "Ate key press" << keyEvent->key();
return true;
} else {
return false;
}
} else {
// pass the event on to the parent class
return QMainWindow::eventFilter(obj, event);
}
}



It is giving an error that ISO C++ forbids declaration of 'eventFilter' with no type..

Can you please tell me how to declare this event in mainwindow.h ? and where to define the settext() property of textedit? Please I am very new to Qt. Kindly help me.

wagmare
11th December 2013, 10:00
follow as lykurg said .. first create an object as a subclass of QTextEdit , reimplement keyPressEvent of that class . http://www.codeprogress.com/cpp/libraries/qt/qtHandleQKeyEvent.php#.Uqg29vWEq1s
and use the QTextCursor to set the text with the above html code i gave last time .