Qt - several built-in QTextBlock

Is it possible to place multiple QTextBlocks in a QTextDocument in the same horizontal line?

I need to know which block of text was pressed, and QTextBlock would be nice to use because of its setUserState (int) method, which can be used to store the identifier of a particular block. Are there any more efficient approaches?

+4
source share
1 answer

Not sure if I received your question correctly, but I take a picture (three years after the question was asked .....)

Basically, you can put QTextBlocks in a horizontal line with a QTextTable . If you then create a class that inherits from QTextEdit , you can catch mouse events and figure out which text block was clicked.

I am posting some code below where I have a very simple dialog in which there is only textedit (from the derived class mentioned above). I create a table laying out three text blocks in a horizontal line and setting their user state to the column number. Then I have a text editing class with only the mouseEvent method mouseEvent , which only prints the userState any text block it is in on the command line to show the principle.

Let me know if this helps, or if you misunderstood your question.

dialog.h

 #ifndef MYDIALOG_H #define MYDIALOG_H #include "ui_dialog.h" class MyDialog : public QDialog, public Ui::Dialog { public: MyDialog(QWidget * parent = 0, Qt::WindowFlags f = 0); void createTable(); }; #endif 

dialog.cpp

 #include "dialog.h" #include <QTextTable> #include <QTextTableFormat> MyDialog::MyDialog(QWidget * parent, Qt::WindowFlags f) : QDialog(parent,f) { setupUi(this); } void MyDialog::createTable() { QTextCursor cursor = textEdit->textCursor(); QTextTableFormat tableFormat; tableFormat.setCellPadding(40); tableFormat.setBorderStyle(QTextFrameFormat::BorderStyle_None); QTextTable* table=cursor.insertTable(1,3,tableFormat); for( int col = 0; col < table->columns(); ++col ) { cursor = table->cellAt(0, col).firstCursorPosition(); cursor.insertBlock(); cursor.block().setUserState(col); cursor.insertText(QString("Block in Column ")+QString::number(col)); } } 

mytextedit.h

 #ifndef MYTEXTEDIT_H #define MYTEXTEDIT_H #include <QTextEdit> class MyTextEdit : public QTextEdit { public: MyTextEdit(QWidget * parent = 0); void mousePressEvent(QMouseEvent *event); }; #endif 

mytextedit.cpp

 #include "mytextedit.h" #include <QMouseEvent> #include <QTextBlock> #include <QtCore> MyTextEdit::MyTextEdit(QWidget * parent) : QTextEdit(parent) { } void MyTextEdit::mousePressEvent(QMouseEvent *event) { if(event->button() == Qt::LeftButton) { qDebug() << this->cursorForPosition(event->pos()).block().userState(); } } 

main.cpp (for completeness only)

 #include <QApplication> #include "dialog.h" int main(int argc, char** argv) { QApplication app(argc,argv); MyDialog dialog; dialog.show(); dialog.createTable(); return app.exec(); } 
+1
source

All Articles