Qt - Updating in the function called by QSignalMapper - c++

I have a QTreeWidget in which each of its items has a QComboBox in a column. I have connected it to a slot with a QSignalMapper, and I'm successfully retrieving both the item and the index in the combobox when it is triggered. I did it like this:
foreach(Workplace *wp, allWorkplaces){
QTreeWidgetItem *workplaceItem = new QTreeWidgetItem;
workplaceItem->setText(0, wp->workplaceName());
workplaceItem->setText(1, wp->workplaceDescription());
myWorkplaceUi->treeWidget->addTopLevelItem(workplaceItem);
QComboBox *combo = new QComboBox();
combo->addItems(allShiftModels);
combo->setAutoFillBackground(true);
ShiftModel *shiftModel = qobject_cast<ShiftModel *>(wp->usedShiftModel);
myWorkplaceUi->treeWidget->setItemWidget(workplaceItem,2, combo);
if(shiftModel && !shiftModel->shiftModelName().isEmpty()){
qDebug()<<"after the cast: "<< shiftModel->shiftModelName();
combo->setCurrentIndex(combo->findText(shiftModel->shiftModelName(), Qt::MatchExactly));
}else{
combo->setCurrentIndex(combo->findText("None", Qt::MatchExactly));
}
connect(combo, SIGNAL(currentIndexChanged(int)), signalMapper, SLOT(map()));
signalMapper->setMapping(combo, QString("%1").arg(wp->workplaceName()));
}
connect(signalMapper, SIGNAL(mapped(const QString &)),this, SLOT(changed(const QString &)));
My objective is, after retrieving both the Workplace and the ShiftModel, to update them in the instances of my already created Workplaces. So, basically, I try to find the Workplace and the ShiftModel that were selected, because depending on the ShiftModel selected, I will change a pointer to the ShiftModel in the Workplace class:
class Workplace : public QObject
{
Q_OBJECT
public:
(...)
ShiftModel *usedShiftModel;
(...)
}
And the changed slot:
void workplacesdialog::changed(QString position){
QList<Workplace* > allWorkplaces = this->myProject->listMyWorkplaces();
QList<ShiftModel*> allShiftModels = this->myProject->myFactory->listShiftModels();
foreach(Workplace* workplace, allWorkplaces){
foreach(ShiftModel *shiftmodel, allShiftModels){
qDebug() <<"workplace:"<< workplace->workplaceName();
qDebug() <<"shiftmodel:"<< shiftmodel->shiftModelName();
QString wp = position;
QTreeWidgetItem* item=(QTreeWidgetItem*)myWorkplaceUi->treeWidget->findItems(wp,Qt::MatchExactly,0).at(0);
QComboBox *combo = (QComboBox*)myWorkplaceUi->treeWidget->itemWidget(item,2);
if(combo && item){
QString sm = combo->currentText();
qDebug() << "selected shiftmodel "<< sm << " on workplace "<< wp;
if(workplace->workplaceName()==wp && shiftmodel->shiftModelName()==sm){
workplace->usedShiftModel = shiftmodel;
break;
}
else{
workplace->usedShiftModel = 0;
return;
}
}else{
qDebug() << "cast failed!";
return;
}
}
}
}
So, my problem with this is, when I click one of the comboboxes, successfully retrieve both the item and index selected, but then, when I try to traverse them with the two foreach loops in the slot, it does not work as I expected. I hoped that every time I clicked on an index in one of the comboboxes, this would be called, and it is. Although, for some reason, the method I'm using to match what the user selected with what was already instatiated doesn't work.
Also, it looks like it only hits both the 1st workplace on the allWorkplaces list as well as the 1st shiftmodel on the ShiftModels list, and this is my problem.
If anyone knows how to fix this or has any ideas to share, please let me know. Thank you.

The problem is this:
if(workplace->workplaceName()==wp && shiftmodel->shiftModelName()==sm){
workplace->usedShiftModel = shiftmodel;
break;
}
else{
workplace->usedShiftModel = 0;
return;
}
If either the workplace name does not match, or the shift model name does not match, the relation between the work place and its currently linked shift model is removed and your function returns.
I could restructure the two for-loops for you, but there is an easier and less error-prone way:
Note: I marked some code paths with "TODO" which I skipped due to lack of time. You should be able to figure them out yourself though.
// Set up hashes for quick lookup
QHash< QString, Workplace* > workplaceHash;
QList<Workplace* > allWorkplaces = this->myProject->listMyWorkplaces();
foreach( Workplace* workplace, allWorkplaces )
{
workplaceHash.insert( workplace, workplace->workplaceName() );
}
// TODO: Do a similar thing for the shift models here
// Find the selected workplace
if( !workplaceHash.contains( position ) )
{
// TODO: Error handling (An unknown/No workplace was selected)
return;
}
// else: A valid workplace was selected
Workplace* selectedWorkplace = workplaceHash.value( position );
// TODO: Retrieve the name of the shift model (stored in variable sm)
// Find the selected shiftmodel
if( !shiftplaceHash.contains( sm ) )
{
// No shift model was selected
selectedWorkplace->usedShiftModel= 0;
return;
}
// Else: Both work place and shift model were selected
Shiftplace* selectedShiftModel = shiftplaceHash.value( sm );
selectedWorkplace->usedShiftModel = selectedShiftModel;
A few ideas for refactoring:
You could maybe do the creation of the hashes outside of this method and store them in member variables. Just make sure that the hash is always updated when a workplace is added or removed.
You could make spotting errors easier by extracting parts of the code into separate methods, e.g. QString getSelectedShiftModelName() etc.

So, In the end I figured out my loops were really messed up... This is working now:
void workplacesdialog::changed(QString position){
QList<Workplace* > allWorkplaces = this->myProject->listMyWorkplaces();
QList<ShiftModel*> allShiftModels = this->myProject->myFactory->listShiftModels();
qDebug() << allWorkplaces.size() << " workplaces";
qDebug() << allShiftModels.size() << " ShiftModels";
QString wp = position;
QString sm;
QTreeWidgetItem* item=(QTreeWidgetItem*)myWorkplaceUi->treeWidget->findItems(wp,Qt::MatchExactly,0).at(0);
QComboBox *combo = (QComboBox*)myWorkplaceUi->treeWidget->itemWidget(item,2);
if(combo && item){
sm = combo->currentText();
qDebug() << "selected shiftmodel "<< sm << " on workplace "<< wp;
}else{
qDebug() << "cast failed!";
return;
}
foreach(Workplace* workplace, allWorkplaces){
foreach(ShiftModel *shiftmodel, allShiftModels){
qDebug() <<"workplace:"<< workplace->workplaceName();
qDebug() <<"shiftmodel:"<< shiftmodel->shiftModelName();
if(workplace->workplaceName()==wp && shiftmodel->shiftModelName()==sm){
qDebug() << "found match!: "<< wp << " >>>>> " << sm;
workplace->usedShiftModel = shiftmodel;
return;
}else if(workplace->workplaceName()==wp && sm=="None"){
qDebug() << "clear match: "<< wp << " >>>>> " << sm;
workplace->usedShiftModel = 0;
return;
}
}
}
}

Related

Qt WebEngine incorrect page margins when printing

I implement the ability to print reports in my project. Reports are presented as HTML content. There is an instance of QPrinter with custom fields:
printer = new QPrinter(QPrinter::ScreenResolution);
qreal topMargin = 15;
qreal bottomMargin = 15;
qreal leftMargin = 20;
qreal rightMargin = 15;
QPrinter::Unit units = QPrinter::Millimeter;
printer->setPageMargins(leftMargin,topMargin,rightMargin,bottomMargin,units);
When printing in PDF, everything is fine
view->printToPdf([=] (QByteArray bd) {
//Запись файла
}, printer->pageLayout());
But when printing with the "print" function, the fields are set incorrectly:
QWebEnginePage *page = new QWebEnginePage;
page->setHtml(currentForPrint);
connect(page, &QWebEnginePage::loadFinished, [page, printer] (bool ok) {
if (!ok) {
qDebug() << "error"; return;
}
page->print(printer, [=] (bool ok) {
if (ok)
qDebug() << "success";
else
qDebug() << "error 2";
});
});
image
Qt Version - 5.9.3.
This is a bug in WebEngine. I have reported it and will fix it as soon as it's possible. As a workaround you could enable full page printing in your QPrinter:
printer->setFullPage(true);
This works for me.

QSqlDatbase is closed before the query finishes

I am trying to implement a database object for my application, but it became a nightmare when I started using multiple connections. Below, you can see my database C++ class code:
// here are the declarations
QString server_addr;
QString username;
QString password;
QString database_name;
QSqlDatabase connection;
QString error;
QString connectionName;
QSqlQuery m_query;
// and here are the definitions
database::database(QString connectionName) {
preferences p; p.read();
QString iConnectionName = (connectionName == "") ? default_connection_name : connectionName;
this->connectionName = iConnectionName;
if (QSqlDatabase::contains(iConnectionName))
this->connection = QSqlDatabase::database(iConnectionName);
else this->connection = QSqlDatabase::addDatabase("QMYSQL", iConnectionName);
this->connection.setHostName(p.database->server_addr);
this->connection.setUserName(p.database->username);
this->connection.setPassword(p.database->password);
this->connection.setDatabaseName(p.database->database_name);
this->connection.setPort(p.database->serverPort);
if (!connection.open())
{
this->error = this->connection.lastError().text();
}
else this->error = "";
}
QSqlQuery database::query(QString query_text) {
this->m_query = QSqlQuery(query_text, this->connection);
this->m_query.exec();
return m_query;
}
database::~database() {
if (!this->m_query.isActive()) QSqlDatabase::removeDatabase(this->connectionName);
qDebug() << "database object destroyed\n";
}
The problem occurs in a another class (that uses the database):
databaseAdaptor::databaseAdaptor() {
this->db = database();
// other construction operations
}
void databaseAdaptor::fetch() {
QSqlQuery q = db.query("SELECT * FROM `activities`");
qDebug() << "Rows count: " << q.numRowsAffected();
}
It worked some versions in the past, but for some reason, now the output from qDebug() is
Rows count: -1 // and it should be 2 for my current version of database.
In the Qt Documentation, it is said that this class' members are thread-safe. Could this be the problem? I mean, could the thread end before the queries finish their execution?
If so, how can I keep the connection open until all the queries finished their execution?
(I know it's much to read, but I am sure that other might have this problem at some point, so please take your time and read it). Thank you!

is it possible to "update" a QTextCursor?

In a QTextEdit object, let's say I want to know the character's position under the mouse cursor.
I can write...
void MyQTextEditObject::mousePressEvent(QMouseEvent* mouse_event) {
mycursor = this->textCursor();
qDebug() << "pos=" << mycursor.position();
}
... it works (the mouse position changes from 0 to the last index of the last character) but the mousePressEvent() method creates a new cursor every time an event occurs. It bothers me since I don't know the "cost" of such a creation.
So, why not create a cursor attribute and use it in mousePressEvent() ?
Something like :
class MyQTextEditObject : public QTextEdit {
Q_OBJECT
public:
// [...]
QTextCursor cursor;
}
MyQTextEditObject::MyQTextEditObject(QWidget* parent) : QTextEdit(parent) {
// [...]
this->cursor = this->textCursor();
}
void MyQTextEditObject::mousePressEvent(QMouseEvent* mouse_event) {
qDebug() << "pos=" << this->cursor.position();
}
But the position doesn't change anymore, as if it was fixed. So, is there a way to somehow update the cursor ? Or is the cost of repeated creation of a QTextCursor insignificant ?
update : writing something like...
mycursor= this->cursorForPosition(mouse_event->pos());
... creates a new cursor and seems to be the equivalent to :
mycursor= this->textCursor();
In your first example, instead of
mycursor = this->textCursor();
qDebug() << "pos=" << mycursor.position();
why do not you call it directly as?
qDebug() << "pos=" << this->textCursor().position();
Because in python
self.textCursor().position()
works.
Also, I am not sure but in your second example maybe you need to set the "cursor" as "textCursor" again with setTextCursor().
void MyQTextEditObject::mousePressEvent(QMouseEvent* mouse_event) {
this->setTextCursor(cursor)
qDebug() << "pos=" << this->cursor.position();
}

QTreeView insertRows via method crushs / direct call works

I have following strange problem.
I've implemented a QAbstractItemModel to the point that I can insert child nodes to the tree view but something strange occurs when I try to add the nodes via the insertRows() method.
First where all is called:
QApplication a(argc, argv);
QResource::registerResource("Qt5Tutorial.rcc");
QTreeView *treeView = new QTreeView();
treeView->show();
Node rootNode("rootNode");
CameraNode childNode0("childNode0", &rootNode);
CameraNode childNode1("childNode1", &rootNode);
LightNode childNode2("childNode2", &rootNode);
CameraNode childNode3("childNode3", &childNode0);
TransformNode childNode4("childNode4", &childNode2);
TransformNode tryNode("potato");
// setup model
ObjectTreeModel model(&rootNode);
treeView->setModel(&model);
// insert directly via the insert child method
// this works!
childNode0.insertChild(1, &tryNode);
// get the QModelIndex of childNode1
// must be passed in the insertRows() method
QModelIndex index(model.index(1, 0, QModelIndex()));
// the output is "childNode1" what is totally right
qDebug() << "index: "<<static_cast<Node*>(index.internalPointer())->getName();
// output see posted beneath
qDebug() << rootNode.log();
// should insert in "childNode1" -> at 0th position and just 1 Node object
// see the method beneath
model.insertRows(0, 1, index);
// if i try to call the method rootNode.log(); now again, it crashes
return a.exec();
This is the output from the rootNode.log() call:
---rootNode
---childNode0
---childNode3
---potato
---childNode1
---childNode2
---childNode4
As you can see the "Potato" Node is correctly inserted.
View an image
http://www10.pic-upload.de/04.01.13/m65huuqq4ruu.png
But once I try to expand the childNode1 node it crashes. But look at the last comment in the code above. As i mentioned -> if i try to output the tree view now (it iterates through all nodes) it crashes.
When the method is called everything seems to be ok - just when i try to expend the tree view it crashes -> the debug output let me think that all should be ok
The actual error message is a access violation when reading at position ... (translated from German - don't know if its called the same in English)
bool ObjectTreeModel::insertRows(int position, int row, const QModelIndex &parent)
{
beginInsertRows(parent, position, position + row - 1);
Node *parentNode = getNode(parent);
qDebug() << "parentName: " << parentNode->getName();
bool success = false;
for(int i = position; i < row; i++)
{
qDebug() << "inside loop";
qDebug() << "position: " << position << "row: " << row;
TransformNode childNode("insertedNode");
success = parentNode->insertChild(i, &childNode);
qDebug() << "success: " << success;
}
endInsertRows();
return success;
}
The debug output for the method above:
getNode: successful
parentName: "childNode1"
inside loop
position: 0 row: 1
called inserchild
success: true
I have no idea why this happens becuase the debug output seems right and it should be basically the same as insert the node directly via the insertChild method.
I hope that someone has an idea why it doesn't work.
Best regards, Michael
Almost everything is correct. Just this two lines not:
TransformNode *childNode = new TransformNode("insertedNode");
success = parentNode->insertChild(i, childNode);

Empty scrollArea QT C++

I am loading data from xml executed by timer. xml is parsed and populated in entity object.
In a loop im taking the data from entity object and populate QCommandLinkButton's. and in the end a batch of buttons are set into the verticalLayout and then in scrollArea.
but every time data is loaded its appends to the old data. How can I empty the content of the srollArea before repopulating scrollArea.
MainWindow::methodExecudedByTimer(){
foreach(int i, map.keys()){
QCommandLinkButton* buttonEmail = new QCommandLinkButton(this);
Email em = map[i];
buttonEmail->setText(em.__toString());
ui->verticalLayout->addWidget(buttonEmail);
}
ui->scrollArea->setLayout(ui->verticalLayout);
}
you can use setWidget replace setLayout.and then new data coming,you can call takeWidget to remove old data.
MainWindow::methodExecudedByTimer(){
foreach(int i, map.keys()){
QCommandLinkButton* buttonEmail = new QCommandLinkButton(this);
Email em = map[i];
buttonEmail->setText(em.__toString());
ui->verticalLayout->addWidget(buttonEmail);
}
ui->scrollArea->takeWidget();
QWidget *widget = new QWidget();
QSize size = ui->scrollArea->size();
widget->setMinimumSize(size.width(),size.height());
widget->setLayout(ui->verticalLayout);
ui->scrollArea->setWidget(widget);
}
I found the answer in the depths of Internet.
before foreach i added this:
qDebug() << "check if layout filled";
if(ui->verticalLayout->count() > 0){
qDebug() << "empty layout";
QLayoutItem *item = NULL;
while ((item = ui->verticalLayout->takeAt(0)) != 0) {
delete item->widget();
}
}else{
// on app first run
qDebug() << "layout empty";
}