qt,rotation,selection,qgraphicsitem , How to rotate selected QGraphicsItems around the selection center?


How to rotate selected QGraphicsItems around the selection center?

Question:

Tag: qt,rotation,selection,qgraphicsitem

I would like to implement rotation of selected items.

I have noticed that there are 2 functions - rotate() which performs an immediate action but does not save the rotation on the item - and setRotation(), which stores rotation() (though it requires a repaint causing event).

If I select a single item and rotate it, I can set

selectedItem->setRotation(selectedItem->rotation() + deg);

This allows the item to store its rotation, and when I need to copy it to another scene, the item retains its rotation information. So it is what I need.

Trying to rotate multiple selected items though,

foreach(QGraphicsItem *selectedItem, scene()->selectedItems())
{
    if(selectedItem->flags() & QGraphicsItem::ItemIsMovable)
    {
        selectedItem->setRotation(selectedItem->rotation() + deg);
    }
}
viewport()->update();
foreach(QGraphicsItem *selectedItem, scene()->selectedItems())
{
    qDebug("%f", selectedItem->rotation());
}

This causes items to rotate around their own center. It is required that items rotate around the center of selection. Everything else works though - items will have a rotation that can be used later. (shown by qDebug)

To get items to rotate around the selection center:

I have tried to group, rotate, ungroup.

QGraphicsItemGroup* g = scene()->createItemGroup(scene()->selectedItems());
foreach(QGraphicsItem *selectedItem, scene()->selectedItems())
{
    if(!(selectedItem->flags() & QGraphicsItem::ItemIsMovable))
        g->removeFromGroup(selectedItem);
}
g->setRotation(g->rotation() + deg);
scene()->destroyItemGroup(g);
viewport()->update();
foreach(QGraphicsItem *selectedItem, scene()->selectedItems())
{
    qDebug("%f", selectedItem->rotation());
}

This seems to do exactly what I want - apparently.
But copying the items to another scene, the items do not have rotation (does it have another transform ? It doesn't seem like it).
The qDebug doesn't show anything - as if items have disappeared from selection, but they still show selection rectangle. (I don't clear selection)
Pressing on rotate button doesn't repeat rotation. I must unselect each item, then reselect to get rotation again.
Also - even though I remove locked items - they still rotate. (why ??)
So it just doesn't work.

Creating a transformation instead of rotation... I would need to set the center of transformation to the center of selection. Trying

QPointF origin = scene()->selectedItems().???
QPointF origin = scene()->selectionArea().???
QPointF origin = scene()->selectionArea().boundingRect().center();  // shows (0, 0)

If I do know where the center is, I can try:

// hacky till i figure out
QPointF origin(0,0);
foreach(QGraphicsItem *selectedItem, scene()->selectedItems())
{
    origin.setX(origin.x() + selectedItem->pos().x());
    origin.setY(origin.y() + selectedItem->pos().y());
}
int selSize = scene()->selectedItems().size();
origin.setX(origin.x()/selSize);
origin.setY(origin.y()/selSize);
qDebug("%f %f", origin.x(), origin.y());  // I don't know really if this is the center

foreach(QGraphicsItem *selectedItem, scene()->selectedItems())
{
    if(selectedItem->flags() & QGraphicsItem::ItemIsMovable)
    {
        QPointF origin1 = selectedItem->mapFromScene(origin);

        selectedItem->setTransform(selectedItem->transform().
                                   translate(origin1.x(), origin1.y()).
                                   rotate(deg).
                                   translate(-origin1.x(), -origin1.y()));
    }
}

Big improvement .. items rotate as a group... but for some reason after unselecting, and trying to rotate an individual item, it retains previous center of rotation...

How can I do this rotation ?


Answer:

You need to rotate and move each item individually, so that they can be later moved to another scene independently. You can manually calculate new rotations and positions:

void Form2::on_rotate_clicked() {
  QRectF rect;
  foreach(QGraphicsItem* item, scene->selectedItems()) {
    rect |= item->mapToScene(item->boundingRect()).boundingRect();
  }
  QPointF center = rect.center();
  qreal angle = 10;
  QTransform t;
  t.translate(center.x(), center.y());
  t.rotate(angle);
  t.translate(-center.x(), -center.y());
  foreach(QGraphicsItem* item, scene->selectedItems()) {
    item->setPos(t.map(item->pos()));
    item->setRotation(item->rotation() + angle);
  }
}

Related:


Pro file directive: copy target to folder at build step


qt,qt5
I have a TEMPLATE = subdirs project with 6 subprojects which build in specified order. I would like to copy the output file of project1 (it's target) to some folder. This folder is passed with LIBS += -L to project2 and project2 may use this file as a static library....

QODBCResult::exec: Unable to execute statement: "[Microsoft][ODBC SQL Server Driver]COUNT field incorrect or syntax error


c++,sql-server,qt,tsql,odbc
I get this error when I try to call stored procedure in QT using QODBC: QODBCResult::exec: Unable to execute statement: "[Microsoft][ODBC SQL Server Driver]COUNT field incorrect or syntax error Amount of parameters is correct, syntax looks alright to me. The procedure executes fine in Management Studio. What might be the...

Customizing QDateEdit style


c++,qt
How can i get the appearance of QDateEdit as shown on the image? I tried changing the stylesheet, but I dont know how to achieve the spacing between the button and the edit, nor how can I change the down arrow button....

Copy text and placeholders, variables to the clipboard


c++,qt,clipboard
In my application I want generate random numbers or strings with a text in front of it. It is important for me that the text won't appear in my window, but instead gets copied to the clipboard. int randomnumber = rand() % 46 + 1; QClipboard *cb = QApplication::clipboard(); cb->setText("Just...

Must compile Opencv with Mingw in order to use in QT under Winodws?


qt,opencv,mingw
I've visit these blogs https://zahidhasan.wordpress.com/2014/08/19/qt-5-3-1-64-bit-mingw-windows/ How to link opencv in QtCreator and use Qt library http://www.cnblogs.com/grandyang/p/4328896.html All of them are using Mingw to compile Opencv through Cmake. If I want to use Opencv in QT, is compiling with Mingw the only way? I have this question because I already compiled...

WPF Rotate an Image and align it


wpf,xaml,rotation,rendertransform
I've an Image component where I want to rotate the source : <Image Name="ImageTarget" HorizontalAlignment="Left" VerticalAlignment="Top" Stretch="Uniform" RenderTransformOrigin=".5,.5"> <Image.RenderTransform> <TransformGroup> <ScaleTransform ScaleX="{Binding Main.BindedViewMode, Converter={StaticResource ImageSizeConverter}}" /> <ScaleTransform ScaleY="{Binding Main.BindedViewMode, Converter={StaticResource ImageSizeConverter}}" /> <RotateTransform Angle="-90" /> </TransformGroup>...

Repeat state on mouse click QML


qt,qml,qtquick2
Within the code I have a State, a Transition and a RotationAnimation defined. After the property change takes place, i.e. after the rotation is set to 360, the onClicked handler is rendered mute and the animation will never be played again after subsequent MouseArea clicks. Here is my current code:...

Context Pointer Lost in FSEventStreamCreate Callback (c++)


c++,osx,qt,fsevents,file-watcher
im trying to test a simple filewatcher in mac using the FSEvent Api. I get the callback with the events and everything seems to work but i can't recover the info contained in the info field of the context structure. Here is my code: void feCallback(ConstFSEventStreamRef streamRef, void* pClientCallBackInfo, size_t...

How to set User Agent in QtWebEngine QML application


qt,qml,qt5,user-agent,qtwebengine
NOTE: I was able to do that on QtWebKit QML using the QtWebView extension. Here I am interested in using QtWebEngine. My simple test application import QtQuick 2.1 import QtQuick.Controls 1.1 import QtWebEngine 1.0 ApplicationWindow { width: 800 height: 600 color: "lightgray" visible: true WebEngineView { id: webview url:...

QWidget.paintevent() vs QLabel.setPixmap()


qt,qwidget,qlabel
I am trying to grab a widget and show it in another widget. Which one is less expensive? 1- using QWidget.paintevent() void MonitoringWidget::paintEvent(QPaintEvent *event) { if (m_mirrorWidget){ QPixmap mirrorPix = m_mirrorWidget->grab(); QPainter p(this); // p.drawPixmap(this->rect(),mirrorPix,mirrorPix.rect()); p.drawPixmap(ui->mirrorFrame->geometry(),mirrorPix,mirrorPix.rect()); update(); } return; } 2- QLabel.setPixmap()? QLabel mirrorLabel; QPixmap mirrorPix = m_mirrorWidget->grab(); mirrorLabel.setPixmap(mirrorPix )...

What does QHeaderView::paintSection do such that all I do to the painter before or after is ignored


c++,qt,qpainter,qheaderview
This question is further development of this post and is different, though may seem similar as this one. I am trying to reimplement QHeaderView::paintSection, so that the background returned from the model would be honored. I tried to do this void Header::paintSection(QPainter * painter, const QRect & rect, int logicalIndex)...

QT-FTP Upload Error


c++,qt,ftp,qnetworkreply
I'm trying to upload a simple txt file to ftp server but getting "QNetworkReply::ContentOperationNotPermittedError" reply from the server and i think it is about my file hierarchy. Here is the file order of my ftp server and my qt-ftp configuration : QUrl url("f13-preview.125mb.com/www/home/repo/test.txt"); url.setHost("f13-preview.125mb.com"); url.setUserName("1896230"); url.setPassword("mypassword"); url.setPath("f13-preview.125mb.com/www/home/repo/"); url.setScheme("ftp"); ...

Sorting based on the rules set by a string variable


c++,qt,sorting,c++11
In my hypothetical app, I receive a list of hotels from the server. struct Hotel { std::string name; // e.g. Hilton, Ritz int stars; // In range [0..5], 0 stands for "unrated" int freeRoomCount; // Number of available rooms [0..N] int parkingPlacesAvailable; // Number of parking places availalble [0..M] }...

change QDir::rootPath() to program running path?


c++,qt
I have a Qt FTP server that selects C:/ as root path. I'm trying to change that to select the starting program location path. For example: If ftpserver.exe is located in H:/programs/ftpserver.exe, it must automatically set the ftp root path to H:/. Code: ui->lineEditRootPath->setText(settings.value("settings/rootpath", QDir::rootPath()).toString()); Code: void MainWindow::on_toolButtonBrowse_clicked() { QString...

How to manipulate multiple Folders/Dir in QT?


c++,qt,qmediaplayer,qdir,qfileinfo
I want to know how to manipulate directories until I get video files. Firstly the main Directory is "F:/TestingVideos/" Inside the test video there are files e.g:1. Cash Office ,2.Rosville Gate ,3. My Videos Each of this videos holds other folders for example Cash Office has a Directory of "F:/TestingVideos/Cash...

Is it possible to rotate a vector in 3D space using quaternions only?


c++,rotation
I want to rotate a vector in 3D space around the origin. Let's say I have a hypothetical polygon centered around the origin, and laying perpendicular to the y-axis. I then want to rotate this polygon around some arbitrary axis by some arbitrary rotation amount. Example: Rotate around the Y...

How to rotate an image R raster


r,plot,rotation,raster
I have code below which saves an image to my pc. I would like to rotate that image by 45,90 and 135 degrees around its center (or bottom left hand corner) and then save as 3 different images. How could I do that? library(raster) r1 <- brick(system.file("external/rlogo.grd", package="raster")) x <-...

CSS rotate animation with pulse


html,css,animation,rotation,frontend
I am trying to make an animation using CSS. It should rotate an image and give it a pulse (something similar to Shazam's button animation). The following is my code. Image is rotating but if I add 'scale' to try and make it pulsate as well, it has a pulse...

Id in database using qt


database,qt,sqlite
I am new to qt. I have created a table in sql, and what I'm trying to do is to give an id whenever user adds data. For the first thing inserted it will be 1, second 2 and so on. So how to check what number was the last...

Qstring error. Saving from Textpool to string


c++,qt,qstring
I've been trying to make simple 'typing game' where program is checking if input = showcased word. I'm trying to use Qt GUI, so I've placed two text widgets, and "play" button. However, there is a problem with string (or QString). Error: no match for 'operator=' (operand types are 'QString'...

Loading animated gif data in QMovie


json,qt,pyside,animated-gif
I'm very new to Qt (specifically PySide) and I'm trying write a script that loads an animated gif from file into a QByteArray and then into a QMovie. The reason for going from file to the QByteArray is because I cannot keep that gif file in memory. I want to...

How to add a gif image in the statusbar Qt [closed]


c++,qt
I'm pretty new to Qt and I was told that I can add a gif image to the status bar using the QMovie class. Can anyone tell how it can be done and is there any other way to do this too?

How can I make a QTextEdit widget scroll from my program


c++,qt
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...

Unable to connect to mariadb database server with qt 4.8.5 and Ubuntu 12.04


mysql,qt,ubuntu,mariadb
I use the following code to connect to a MySQL server database. QSqlDatabase db_Server = QSqlDatabase::database("Test"); //find mysql driver db_Server = QSqlDatabase::addDatabase("QMYSQL","Test"); db_Server.setHostName("188.**.***.***"); db_Server.setPort(3306); db_Server.setDatabaseName("Test"); db_Server.setUserName("Test"); db_Server.setPassword("*********"); bool ret = db_Server.open(); if(ret) qDebug() << "Database open" else qDebug() << db_Server.lastError().text(); Lately they changed the server to mariadb and I assumed...

How to pass QString variable to QFile?


qt,qstring,qfile
getData gets the chosen file from a QTreeView and displays it on label 'test', enables the 'Apply' button, which when clicked calls setTheme void OptionsDialog::getData(const QModelIndex &index) { QString selected = model2->filePath(index); ui->test->setText(selected); ui->pushButton_apply_theme->setEnabled(true); } void OptionsDialog::setTheme() { //char *file = selected->toLatin1().data(); //const std::string file = selected->toStdString(); QFile qss(selected); qss.open(QFile::ReadOnly);...

QT Combo Box of Line Pattern


c++,qt,qcombobox
i want to make a line pattern combo box in Qt same as it is shown in the picture , please tell me is it possible to make a combo box in Qt like shown in the picture. Any help would be appreciated Regards ...

Qt can't assign value to QLabel


c++,qt
I like to start out saying that I'm about as noob as they come. This is my first c++ program I built from scratch. I gotten most of the bugs ironed out, however I can't seem to be able to assign a value to a QLabel. I want the function...

How can I override the member of (->) operator of a base class


c++,qt,inheritance,overloading,operator-keyword
Background: I have Qt generated UI classes with no common ancestor. I am subclassing a class (say, "Door") that uses one of these UI classes, and the derived class ("OakDoor") will use a different UI class, although much of the UI elements will have the same name. Until now I...

QEvent ownership


c++,qt,memory-management
I want to send both predefined and custom QEvent to a Qt application. Is the event required be allocated on the heap or can I just pass the pointer to a object on the stack? QKeyEvent stackevent(QEvent::KeyPress); QKeyEvent* heapevent = new QKeyEvent(QEvent::KeyPress); QEvent * event; event = &stackevent; //valid ??...

Rotating a Label In Qt with Python


python,qt
I'm somewhat new to Qt and was wondering how to rotate a Label that has a pixmap inside of it. I've tried somethings like this: def paintEvent (self, event): t = QtGui.QTransform() image = QtGui.QImage(_fromUtf8(":/icons/BOOM_OUT.png")) pixmap = QtGui.QPixmap.fromImage(image) self.label.setPixmap(pixmap) t.translate(400,300) t.rotate(45) p = QtGui.QPainter(self) p.setTransform(t) p.drawPixmap((-pixmap.width()/2),(-pixmap.height()/2), pixmap) p.end() I know...

connecting signals and slots with different relations


c++,qt,connect,signals-slots
First of all I'd say I'm a noob to GUI programming. I use Qt 5.4. I came up with this code while watching voidRealms videos. connect(ui->horizontalSlider,SIGNAL(sliderMoved(int)),ui->progressBar,SLOT(setValue(int))); Obviously this connects slider movement with progressbar fill. This actually works like progressbarfill <- slidermovement. How can I make into a different relation? Like...

Change attribute value of an XML tag in Qt


c++,xml,qt
I'm trying to change the language attribute of a .ts file in Qt using Qt itself. Here is the sample XML format. <?xml version='1.0' encoding='utf-8'?> <!DOCTYPE TS> <TS language="es_ES" version="2.1"> ... </TS> I have tried different ways, but no luck. Here are the methods I used. FileIOError FileIO::changeLanguageOfTsFile( QString tsFileName,...

Is there a way to prevent Qt slider dragging beyond a value?


qt,qslider
I have implemented the interface where the user is drawing a frame and then moving to next frame which will increment the slider value by 1. User can also increment or decrement the slider value. But, if user has drawn only upto frame 20 then user should not be able...

Separating axis theorem: rotation around center of mass


c++,math,rotation,rotational-matrices,separating-axis-theorem
The problem is in Polygon::FindAxisLeastPenetration: double Polygon::FindAxisLeastPenetration(unsigned int *faceIndex, const Polygon &polygonA, const Polygon &polygonB) const { double bestDistance = -std::numeric_limits<double>::infinity(); unsigned int bestIndex; for (unsigned int i = 0; i < polygonA.points.size(); i++) { Vector2D n = polygonA.normals[i]; Vector2D nw = polygonA.rotationMatrix * n; //ROTATION Matrix22 buT = polygonB.rotationMatrix.Transposed();...

How to change the opacity of Qt MainWindow?


qt,qmainwindow
How to change the opacity of the Qt MainWindow by some values? My main window contains nothing but just somehow I need to change the opacity using keystrokes. It looks like this now. I tried to set using this->setWindowOpacity(0.5); didn't get anything opacity effect. ...

How can I have an animated system tray icon in PyQt4?


python,qt,pyqt,pyqt4,system-tray
I am trying to create an animated systray icon for a pyqt4 app but am having trouble finding any examples in python. This is the closest I can find but it's in C++ and I don't know how to translate it over: Is there a way to have (animated)GIF image...

MATLAB: How to make camera light follow 3D Rotation


matlab,user-interface,3d,rotation,lighting
I have come into a problem recently when trying to rotate 3D objects. I am building a GUI and I have a separate figure where an object is plotted. In the figure, I allow the user to use MATLAB's built-in rotate button to move the object around. However, I am...

How to avoid user to click outside popup Dialog window using Qt and Python?


qt,user-interface,python-3.x,dialog,qt-creator
I created a Dialog window using Qt Creator and Python. I would like that Window stays on the top of my Gui AND avoid users to click outside that Dialog Until this dialog was closed.

std::ostream to QString?


c++,qt,exception
Is there a way to convert an std::ostream to a QString? Allow me to expand in case it is useful: I am writing a program in C++/Qt and I used to (not) deal with / debug exceptions by just using std::cout, as in for example: std::cout << "Error in void...

How to align GUI elements like this? Qt, C++


c++,qt
I need to align elements on GUI: actually, a single label, but at the specific position. I know how to use QGridLayout, QHBoxLayout, I know how to change the font to have the specified size. However, I don't know how to align the label like on this picture below. Any...

C++ & Qt: Random string from an array area


c++,arrays,string,qt,random
In my small Qt application, I want to pick a random string out of an array after I clicked on a button. I've read many threads but nothing works for me. So in my slot there's an array with several strings in it. I also implemented <string>, <time.h> and srand....

How to differentiate a QNetworkReply is aborted or not?


c++,qt,networking
I have the following code: connect(&netMgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(loadFinished(QNetworkReply*)), Qt::UniqueConnection); reply = netMgr.get(qheader); How could I tell whether the loadFinished(); slot is triggered by calling reply->abort() or not?...

Using QSimpleXmlNodeModel and QTreeView


c++,qt
I've been looking at ways to populate a QTreeView with data from an XML file. The XML will be simple. I've come across QSimpleXmlNodeModel and have been trying to figure out if this is suitable for my needs, but can't find any examples of its use. Can someone point me...

How can I wrap text in QGraphicsItem?


qt,text,word-wrap,qgraphicsitem
1) How can I wrap text in a QGraphicsTextItem to fit a fixed rectangle, with width and height ? Right now I am experimenting with creating a text, getting its bounding rectangle, and resizing it to fit the box - but I can't get wrapping. class TTT: public QGraphicsTextItem {...

load a thumbnail on QListWidget with reduced resolution


image,qt,qlistwidget,qlistwidgetitem
I need to reduce the resolution of the images that I add and show in a QListWidgtet. Now I use the next code but it does not show all the images because they are being loaded with full resolution void ImagesWizard::on_pbAddImages_clicked() { QFileDialog dialog(this); dialog.setDirectory(mInitPath); dialog.setFileMode(QFileDialog::ExistingFiles); dialog.setNameFilter(trUtf8("Images (*.jpg *.png *.tif...

Align horizontalcenter in Column


qt,qml,qtquick2,qt-quick
Column documentation explains how to achieve this: However, I would like to achieve this: That is, all items inside the Column should be horizontally aligned to the center. anchors.horizontalCenter: parent.Center does not work. How can I obtain the desired result?...

Update bindings to var properties in QML


qt,qml
If you take a look at this page it notes that bindings to var properties are not automatically updated when the object changes: Item { property var car: new Object({wheels: 4}) Text { text: "The car has " + car.wheels + " wheels"; } Component.onCompleted: { car.wheels = 6; }...

Return const reference to local variable correctly


c++,qt
Additionally to the answers 1, 2, 3 and GotW88, assume the following methods QString createString() { return QString("foobar"); } const QString& getString() { return createString(); } This will yield the famous "warning C4172: returning address of local variable or temporary" with VS2013. Now if i changed the second method to...

Deploying to Android results in file not found after adding QtQuick Controls


android,qt,deployment,qml,qt5.4
After importing QtQuick.Controls 1.2 and using StackedWidget component, I now get an error when deploying to Android as seen below. The missing file AnimationDrawable.qml is not missing from the Android build directory so I do not understand why it is not packaged with the APK. It deploys fine when I...

Updating ac value for Qtimer


qt,user-interface,adc
I am using qt tool for mini2440. I make a gui for i2c adc having starti2c and stopi2c. All things are working well: it reads value of signal when starti2c button press, but I want this value to be updated. I know that Qtimer can be used, but how can...