Qt - several QTextBlock inline - qt

Is it possible to arrange several QTextBlocks in QTextDocument in one horizontal line?
I need to know which block of text was clicked and QTextBlock would be nice to use due to its method setUserState(int), which can be used to hold id of particular block. Are there better approaches?

Not sure if I got your question right, but I am taking a shot at it (some three years after the question was asked.....)
In principle you can put QTextBlocks in a horizontal line using a QTextTable. If you then create a class which inherits from QTextEdit you can catch the mouse events and find out which text block was clicked.
I post some code below where I have a very simply dialog that only has a textedit in it (of the derived class mentioned above). I create a table laying out three text blocks in a horizontal line and set their user state to the column number. Then I have the text edit class only with the overloaded mouseEvent method which only prints the userState of whatever text block it is in to the command line, just to show the principle.
Let me know if this is of any help or if 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 (just for completeness)
#include <QApplication>
#include "dialog.h"
int main(int argc, char** argv)
{
QApplication app(argc,argv);
MyDialog dialog;
dialog.show();
dialog.createTable();
return app.exec();
}

Related

How to simulate a drag and drop action using QTest

In order to create a test case for a drag and drop bug in the QTreeView widget I tried to simulate a drag and drop mouse movement behavior.
I basically select the first element in the QTreeView and want it to drag and drop on the third element. I did this by using a combination of QTest::mousePress and QTest::mouseMove. At the end there should be of course a QTest::mouseRelease, but I already failed in reproducing the mousePress and mouseMove.
These are steps necessary to reproduce:
User moves mouse on center of first item
User presses the left mouse button
User holds the left mouse button pressed and moves the mouse to the center of the third item
User releases the left mouse button
If one does these action as described I can see, that the QTreeView Widgets reacts appropriately, and indicating special highlights and vertical lines, in case the item will be move between to items.
Unfortunately, my automatized test fails to reproduce this behavior. It seems that calling QTest::mousePress in sequence does something different. Also using a pair of QTest::mousePress and QTest::mouseMove is something differently.
This is my code:
main.cpp
#include "TestObject.h"
#include <QTest>
QTEST_MAIN(TestObject)
TestObject.h
#include <QtTest/QtTest>
class TestObject : public QObject
{
Q_OBJECT
private slots:
void dragAndDrop();
};
TestObject.cpp
#include "TestObject.h"
#include "TestObject.moc"
#include <QTest>
#include <QTreeView>
#include <QStandardItemModel>
#include <QPropertyAnimation>
#include "MouseMover.h"
void TestObject::dragAndDrop() {
qDebug() << "Hello";
QStandardItemModel model;
QTreeView view;
view.setModel(&model);
view.show();
view.setHeaderHidden(true);
view.setDragDropMode(QAbstractItemView::DragDropMode::DragDrop);
view.setDefaultDropAction(Qt::DropAction::MoveAction);
view.setColumnHidden(1, true);
for (auto rowIter = 0; rowIter < 3; rowIter++) {
QList<QStandardItem*> items;
for (auto colIter = 0; colIter < 2; colIter++) {
items << new QStandardItem(QString("%1-%2").arg(rowIter).arg(colIter));
}
model.appendRow(items);
}
MouseMover mover;
mover.setWidget(view.viewport());
QPropertyAnimation anim(&mover, "mousePosition");
QTimer::singleShot(0, [&]() {
auto startValue = view.visualRect(model.index(0, 0)).center();
auto endValue = view.visualRect(model.index(2, 0)).center();
QTest::mousePress(view.viewport(), Qt::MouseButton::LeftButton, Qt::KeyboardModifier::NoModifier, startValue);
anim.setStartValue(startValue);
anim.setEndValue(endValue);
anim.setDuration(500);
anim.start();
});
qApp->exec();
}
MouseMover.h
#pragma once
#include <QObject>
#include <QTest>
class MouseMover : public QObject {
Q_OBJECT
public:
Q_PROPERTY(QPoint mousePosition READ mousePosition WRITE setMousePosition MEMBER mMousePosition)
void setWidget(QWidget* widget) {
mWidget = widget;
}
QPoint mousePosition() const {
return mMousePosition;
}
void setMousePosition(const QPoint& pos) {
mMousePosition = pos;
if (mWidget) {
QTest::mousePress(mWidget, Qt::MouseButton::LeftButton, Qt::KeyboardModifier::NoModifier, mMousePosition);
QTest::mouseMove(mWidget, mMousePosition);
}
}
private:
QPoint mMousePosition;
QWidget* mWidget{ nullptr };
};
MouseMover.cpp
#include "MouseMover.h"
mouseMoveEvent() handler starts and blocks at QDrag.exec(). In order to simulate the drop, you have to schedule it e.g. with QTimer:
def complete_qdrag_exec():
QTest.mouseMove(drop_target)
QTest.qWait(50)
QTest.mouseClick(drop_target, Qt.MouseButton.LeftButton)
QTimer.singleShot(1000, complete_qdrag_exec)
QTest.mousePress(drag_source, Qt.MouseButton.LeftButton, Qt.KeyboardModifier.NoModifier, QPoint(10, 10))
QTest.mouseMove(drag_source, QPoint(50, 50)) # Ensure distance sufficient for DND start threshold
Above is plain Python (PyQt6/PySide6). I assume it's similar for C++ ...

Qt Custom ProgressBar can't refresh (paintEvent)

i've created a custom progress bar, but when i call the SetValue() method the paintEvent method (overrided) is not called, so the progress bar show just the veryfirst value.
This is the Header grafica_progressbar.h
#ifndef GRAFICA_PROGRESSBAR_H
#define GRAFICA_PROGRESSBAR_H
#include <QWidget>
#include <QProgressBar>
#include <QPaintEvent>
#include <QPainter>
#include <QBrush>
#include <QStyle>
#include <QPen>
#include <QColor>
class grafica_ProgressBar : public QProgressBar
{
Q_OBJECT
public:
grafica_ProgressBar();
protected:
void paintEvent(QPaintEvent*) Q_DECL_OVERRIDE;
};
#endif // GRAFICA_PROGRESSBAR_H
and this is the cpp grafica_progressbar.cpp
#include "grafica_progressbar.h"
grafica_ProgressBar::grafica_ProgressBar()
{
}
void grafica_ProgressBar::paintEvent(QPaintEvent *)
{
int tmpValue = value();
int TopPos = QStyle::sliderPositionFromValue(minimum(), maximum(), tmpValue, width());
QPainter p(this);
if (tmpValue<maximum()*0.85)
{
p.setPen(Qt::green);
p.setBrush(QBrush(Qt::green));
}
else
{
p.setPen(QColor(255,51,51));
p.setBrush(QColor(255,51,51));
}
p.drawRect(0,0,TopPos,height());
p.setPen(Qt::gray);
p.setBrush(QBrush(Qt::lightGray));
p.drawRect(TopPos, 0, width(), height()); //riempio tutto il resto di grigio
p.setPen(Qt::black);
p.setBrush(QBrush(Qt::black));
p.drawText(0,0, width(), height(), Qt::AlignCenter, QString::number(tmpValue ) + " bar");
}
and this is the first call into the userinterface costructor
TestProgres = new grafica_ProgressBar();
ui->gridLayout->addWidget(TestProgres);
TestProgres->setMaximum(400);
TestProgres->setValue(300);
if i try to call TestProgres->setValue(200) inside a button, i can't see any refresh.
So, where's the problem?
The code starts to work after a "clean, rebuilt & run" operation.
I've edited the code just for showing the correct value.
Thanks to all!

How to make slot for multiple QPushButtons?

From Qvector is set the number of buttons and their names (text). After cliking on the button I need to reseave text on it and display in lineEdit.
The header file:
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include <QWidget>
#include <QVector>
#include <QLineEdit>
#include <QPushButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
class Dialog : public QDialog
{
Q_OBJECT
public:
Dialog(QWidget *parent = 0);
~Dialog();
private slots:
void Buttons(QVector<QString>&);
private:
QVector<QPushButton*>button;
QString mline;
QLineEdit *line;
QVBoxLayout *layout;
QAction *Clicked;
};
#endif // DIALOG_H
The source file:
#include "dialog.h"
Dialog::Dialog(QWidget *parent): QDialog(parent)
{
this->setFixedSize(this->minimumSize());
line = new QLineEdit(this);
layout = new QVBoxLayout(this);
layout->addWidget(line);
QVector<QString>v;
v.append("a");
v.append("b");
v.append("c");
v.append("5");
v.append("45");
Buttons(v);
for(int i=0;i<button.size();i++)
layout->addWidget(button[i]);
setLayout(layout);
}
Dialog::~Dialog(){}
void Dialog::Buttons(QVector<QString>&vec)
{
if(!button.isEmpty())
button.clear();
for(int i=0; i<vec.size();i++)
{
button.append(new QPushButton(this));
button[i]->setText(vec[i]);
button[i]->show();
}
}
For it I'm not using user interface (ui), and couldn't make slots for all the buttons. How can it be done?
You can use QButtonGroup to id the buttons and consolidate the signals from all the buttons to a single slot
Example
QButtonGroup myButtongroup;
connect(&myButtonGroup,SIGNAL(buttonClicked(QAbstractButton*),this, SLOT(myButtonClicked (QAbstractButton*)));
for(int i=0; i<vec.size();i++)
{
QString buttonName = vec[i];
myButtonGroup.addButton(new QPushButton(buttonName,this),i);
//Get the button using myButtonGroup.button(i) to add to your layout
// You can add the buttons to the layout right here to elimate one more loop
layout.addWidget(myButtonGroup.button(i));
}
//Slot for button clicked
void Dialog::myButtonClicked(QAbstractButton *myButton)
{
line->setText(myButton->text());// Adding the button name to line edit
}
For more QButtonGroup signals refer the documentation
You can use signal/slot in your case. The signal/slot is related to QObject. It does not matter whether you use QT Designer or not. In your code,
for(int i=0; i<vec.size();i++)
{
button.append(new QPushButton(this));
connect(button[i], SIGNAL( clicked() ), this, SLOT(OnButtonClicked()));
button[i]->setText(vec[i]);
button[i]->show();
}
Maintain a QList of QPushButton references that you add and use "signals and slots" to register the clicked() signal of each button to a single slot. Inside the function, iterate the QList of QPushButton by comparing with QObject::sender() and identify the source.
#include <QApplication>
#include <QVBoxLayout>
#include <QPushButton>
#include <QLabel>
class TestWidget: public QWidget
{
Q_OBJECT
private:
QLabel *label;
QVBoxLayout *mainLayout;
QList<QPushButton*> mButtonList;
public:
TestWidget(QWidget *parent=nullptr) : QWidget(parent)
{
mainLayout = new QVBoxLayout(this);
label = new QLabel;
mainLayout->addWidget(label);
this->setLayout(mainLayout);
}
void addButton(QString buttonName)
{
QPushButton *button = new QPushButton(buttonName);
QObject::connect(button, SIGNAL(clicked(bool)), this, SLOT(buttonClicked(bool)));
mButtonList.append(button);
mainLayout->addWidget(button);
}
public slots:
void buttonClicked(bool event)
{
Q_UNUSED(event)
static_cast<QPushButton*>(QObject::sender())->setFocus();
for (int i = 0; i < mButtonList.size(); ++i)
{
if (mButtonList.at(i) == sender())
{
label->setText(QString(mButtonList.at(i)->text()));
break;
}
}
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
TestWidget wid;
wid.addButton("First Button");
wid.addButton("Second Button");
wid.addButton("Third Button");
wid.addButton("Fourth Button");
wid.show();
return a.exec();
}
#include "main.moc"
The above sample code along with *.pro file is available in github

QQuickWidget grab image

I am saving an image of a QQuickWidget with several QML children but all I have is a blank image.
C++ side:
QQuickWidget* content..
content->setSource(QUrl("qml:/main.qml"));
QPixmap *pm = content->grab(QRect(QPoint(0,0),QSize(-1,-1));
pm->save("someFilename.png", 0, 100);
QML side:
Rectangle{ width: 5; height: 5; color: "yellow"; objectname: "rootobj"}
In the QML I wish to dynamically add children and be able to show them in the image. I have tried QQuickWindow grabWindow method with a connection to a slot and it works but it captures only the window visible area and I need to capture the whole QML.
I believe this is not rocket science just that I am not getting it somewhere. Thanks for your replies!
Addendum:
Ok, I do not think its the issue of before/after rendering since I can see all the qml children before I call the picture grabber. So sorry for not being precise.
c++ side:
QQuickWidget* content..
content->setSource(QUrl("qml:/main.qml"));
//do all my dynamic qml children adding
After I can visually see all my qml:
QPixmap *pm = content->grab(QRect(QPoint(0,0),QSize(-1,-1));
pm->save(....
Unless I am wrong, I dont think its rendering issue. Thank you!
Issue is like Mido said. You can solve it like follows.
Create a class Viewer:
viewer.h
class Viewer : public QQuickView{
Q_OBJECT
public:
explicit Viewer(QWindow *parent = 0);
Viewer(bool showBar);
virtual ~Viewer();
void setMainQmlFile(const QString file);
void addImportPath(const QString path);
public slots:
void beforeRendering();
void afterRendering()
}
Viewer.cpp
#include "viewer.h"
Viewer::Viewer(QWindow *parent)
: QQuickView(parent)
{
setWidth(800);
setHeight(480);
connect(this, SIGNAL(beforeRendering()), this, SLOT(beforeRendering()));
connect(this, SIGNAL(afterRendering()), this, SLOT(afterRendering()));
}
void Viewer::setMainQmlFile(const QString file)
{
setSource(QUrl::fromLocalFile(file));
}
void Viewer::addImportPath(const QString path)
{
engine()->addImportPath(path);
}
void Viewer::beforeRendering()
{
//
}
void Viewer::afterRendering()
{
//grab window
QImage img = this->grabWindow();
img.save(path);
//or your code
}
main.cpp
Viewer *viewer = new Viewer;
//
///
//
viewer->setMainQmlFile(QStringLiteral("qml/main.qml"));
viewer->show();
I think your issue is that the capture screen is done before the rendering of the QML object.
In order to make it work you should connect the grab of the signal after rendering signal:
connect(this, SIGNAL(beforeRendering()), this, SLOT(sltBeforeRendering()));
connect(this, SIGNAL(afterRendering()), this, SLOT(sltAfterRendering()));
do the grab in sltAfterRendering slot.
To grab screen I use the grabWindow() function and I call it from QML.
It depends on the behaviour that you want from your software.
Try this:
grabber.h
#ifndef GRABBER_H
#define GRABBER_H
#include <QObject>
#include <QImage>
#include <QQuickView>
class Grabber : public QObject
{
Q_OBJECT
public:
explicit Grabber(QObject *parent = 0);
Grabber(QQuickView *view);
~Grabber();
Q_INVOKABLE void capture(QString const &path) const;
signals:
public slots:
private:
QQuickView* view_;
};
#endif // GRABBER_H
grabber.cpp
#include "grabber.h"
Grabber::Grabber(QObject *parent) :
QObject(parent)
{
}
Grabber::Grabber(QQuickView* view) :
view_(view)
{
}
Grabber::~Grabber()
{
if(view_ != NULL)
{
delete view_;
view_ = NULL;
}
}
void Grabber::capture(QString const &path) const
{
QImage img = view_->grabWindow();
img.save(path);
}
main.cpp
#include <QtGui/QGuiApplication>
#include "qtquick2applicationviewer.h"
#include <QQmlContext>
#include <QQmlEngine>
#include "grabber.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QtQuick2ApplicationViewer *viewer = new QtQuick2ApplicationViewer;
Grabber * grab = new Grabber(viewer);
viewer->setHeight(480);
viewer->setWidth(800);
viewer->rootContext()->setContextProperty("grab", grab);
viewer->setMainQmlFile(QStringLiteral("qml/main.qml"));
viewer->showExpanded();
return app.exec();
}
Call it from QML with:
grab.capture(path + "imageName.png")

'QMessageBox::critical' : none of the 4 overloads could convert all the argument types

I want to display an error message whenever my independent thread encounters the word "alert1" in a specific .txt file. But I get the above error inside the monitorForAlerts() inside mythread.cpp file. The line expectedly executes if I were to place it inside dialog.cpp. So I guess this is due to non-inheritance of this object. Can you please advise me how to solve this error for the given code?
Here is the code:
dialog.h
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include <QtCore>
#include "mythread.h"
namespace Ui {
class Dialog;
}
class Dialog : public QDialog
{
Q_OBJECT
public:
explicit Dialog(QWidget *parent = 0);
~Dialog();
public slots:
private:
Ui::Dialog *ui;
private slots:
void on_pushButton_clicked();
void on_pushButton_2_clicked();
};
#endif // DIALOG_H
mythread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
#include <QtCore>
#include <QDebug>
#include <QFile>
#include <Windows.h>
#include <QMessageBox>
#include <QTimer>
#define ALERTS_MESSAGE_STORAGE_PATH "E:\\QT1\\simpleGUIThread2\\simpleGUIThread2\\usbAlert.txt"
#define TIMER_VALUE 500
class MyThread : public QThread
{
Q_OBJECT
public:
explicit MyThread(QObject *parent = 0);
void run();
QString name;
void monitorForAlerts();
int exec();
public slots:
signals:
void testSignal(QString message);
public slots:
};
#endif // MYTHREAD_H
dialog.cpp
#include "dialog.h"
#include "ui_dialog.h"
Dialog::Dialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::Dialog)
{
ui->setupUi(this);
}
Dialog::~Dialog()
{
delete ui;
}
void Dialog::on_pushButton_clicked()
{
ui->label->show();
}
void Dialog::on_pushButton_2_clicked()
{
ui->label->hide();
}
mythread.cpp
#include "mythread.h"
#include "dialog.h"
MyThread::MyThread(QObject *parent) :
QThread(parent)
{
}
void MyThread::run()
{
exec();
}
int MyThread::exec()
{
while(1)
{
monitorForAlerts();
emit(testSignal("hello world!!"));
sleep(1);
}
}
void MyThread::monitorForAlerts()
{
QString response = ALERTS_MESSAGE_STORAGE_PATH;
QFile resp(response);
resp.open(QIODevice::WriteOnly);
resp.close();
QFile resp1(response);
char buf[121];
char buf1[] = "alert1";
char buf2[] = "alert2";
resp1.open(QIODevice::ReadOnly);
while(resp1.size() == 0)
{
Sleep(3000);
}
qint64 lineLength = resp1.readLine(buf, sizeof(buf));
resp1.close();
if(strcmp(buf,buf1) == 0)
{
QFile::remove(ALERTS_MESSAGE_STORAGE_PATH);
qDebug()<<"warning 1!!";
QMessageBox::critical(this,tr("ERROR"),tr("Large change in illumination.\nPlease re-capture reference image.\n"));
}
if(strcmp(buf,buf2) == 0)
{
QFile::remove(ALERTS_MESSAGE_STORAGE_PATH);
qDebug()<<"warning 2!!";
QMessageBox::critical(this,tr("ERROR"),tr("The camera position has been moved or an object is obscuring its view.\nPlease check the device.\n"));
}
}
main.cpp
#include "dialog.h"
#include <QApplication>
#include "mythread.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MyThread mThread1;
mThread1.name = "mThread1";
mThread1.start();
Dialog w;
w.show();
return a.exec();
}
LATEST UPDATE*********************************************************************
Hi Zlatomir,
I choose to take your 1st advice. I have created a signal that the thread will emit and connect it to a slot for QDialog. Please let me know if my understanding is correct, because I do not know where to implement the connect(), since the signal is declared in mythread.h and the slot in dialog.h. The connection type argument for connect is Qt::QueuedConnection, so that gui elements from another thread different than main-thread.
are NOT created. Is this statement correct? and where do I place this?
connect( mThread, SIGNAL(alertSignal(QString)), this, SLOT(alertSlot(QString)), Qt::QueuedConnection);
mythread.h
//....
signals:
void alertSignal(QString message);
//....
dialog.h
//....
public slots:
void alertSlot(QString message);
//....
mythread.cpp
//....
if(strcmp(buf,buf1) == 0)
{
QFile::remove(ALERTS_MESSAGE_STORAGE_PATH);
qDebug()<<"warning 1!!";
emit(alertSignal("alert1"));
}
else if(strcmp(buf,buf2) == 0)
{
QFile::remove(ALERTS_MESSAGE_STORAGE_PATH);
qDebug()<<"warning 2!!";
emit(alertSignal("alert2"));
}
dialog.cpp
void Dialog::alertSlot(QString message)
{
if(strcmp(message, "alert1"))
QMessageBox::critical(this,tr("ERROR"),tr("Large change in illumination.\nPlease re-capture reference image.\n"));
else if(strcmp(message, "alert2"))
QMessageBox::critical(this,tr("ERROR"),tr("The camera position has been moved or an object is obscuring its view.\nPlease check the device.\n"));
}
Now if this were correct, how do i implement the connect() and in which file?
The first argument is the problem, in your case this is not a good argument, because there this is a pointer to a MyThread instance, and MyThread is not a QWidget (is not derived from QWidget).
To solve this you can show the QMessageBox::critical from a slot in mainwindow (the Dialog class in your code, there you pass the instance of main-window that is a QWidget) and connect that slot with a signal that you emit from your thread, make sure that the connection type argument for connect is Qt::QueuedConnection, so that you don't try to create gui elements from another thread different than main-thread.
Another option would be to validate the data before you start the second thread and to tell
the user that he needs to provide the right files.
LE: Also check the QThread's documentation for the recommended way to use the class, now it's recommended not to derive from QThread.
LE2 - answer to the update
That connect can be made where ever you can have the two instances that you want to connect, in your case main.cpp is a good place to connect those (don't forget to fully qualify the name for connect: QObject::connect):
//...
MyThread mThread1;
mThread1.name = "mThread1";
mThread1.start();
Dialog w;
QObject::connect( &mThread1, SIGNAL(alertSignal(QString)), &w, SLOT(alertSlot(QString)), Qt::QueuedConnection);
w.show();
//...

Resources