Ber
Ber

Reputation: 41813

How can I make a QTextEdit widget scroll from my program

I have a QTextEdit widget with a vertical scroll bar.

report_text = new QTextEdit();
report_text->setAcceptRichText(true);
report_text->setReadOnly(true);
report_text->setTextInteractionFlags(Qt::NoTextInteraction);
report_text->setAlignment(Qt::AlignTop);
report_text->setWordWrapMode(QTextOption::NoWrap);
report_text->setFrameStyle(QFrame::NoFrame);
report_text->setMinimumSize(600, 380);
report_text->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred);

This is Qt 4.8 embedded.

Now I need a method or an event I can send to the widget to make it it scroll up or down just as if the up or down buttons on the scroll bar had been pressed.

I tried the scroll() method, but I scrolls the whole widget, including the scroll bar.

I also tried sending a QWheelEvent, but nothing happens.

QWheelEvent ev(QPoint(), 10, 0, 0);
report_text->setFocus();
QApplication::sendEvent(report_text, &ev);

What am I missing?

Upvotes: 1

Views: 1285

Answers (2)

Ber
Ber

Reputation: 41813

Here is what I found as a suitable solution:

The vertical scrollbar may be accessed using the QTextEdit::verticalScrollBar() method.

Scrollbars have a triggerAction() method to conveniently simulate user interaction with the buttons and the slider. The available actions are defined in QAbstractSlider.

So the resulting code is only a single line:

report_text->verticalScrollBar()->triggerAction(QAbstractSlider::SliderSingleStepAdd);

Interestingly, this works even when the scrollbar is hidden with

report_text->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

Upvotes: 4

UmNyobe
UmNyobe

Reputation: 22890

It is probable that the delta you provided is just way too small.

From the documentation of QWheelEvent::delta():

Returns the distance that the wheel is rotated, in eighths of a degree. A positive value indicates that the wheel was rotated forwards away from the user; a negative value indicates that the wheel was rotated backwards toward the user.

Most mouse types work in steps of 15 degrees, in which case the delta value is a multiple of 120; i.e., 120 units * 1/8 = 15 degrees.

The text scrolling in Qt unit is the number of whole line. So if the widget computes that you want to scroll 0.9 lines, he might do nothing.

So try again with

QWheelEvent ev(QPoint(), 120, 0, 0);

Note: Nothing here apply to an event with control or shift modifier.

Upvotes: 2

Related Questions