How to read columns in qtreeWidget? - qt

I have two columns in treewidget viz. Files and path. Now I want to dump the items into an xml file. But the issue I'm facing is that I'm unable to extract the items.
QDomDocument document;
QDomElement root = document.createElement("Playlist");
document.appendChild(root);
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this, "Save", "Do you want to save the playlist?", MessageBox::Yes | QMessageBox::No);
if(reply == QMessageBox::Yes)
{
//Add some elements
QDomElement playlist = document.createElement("MyPlaylist");
playlist.setAttribute("Name", "Playlist1");
root.appendChild(playlist);
for(int h = 0; h < ui->treeWidget->topLevelItemCount(); h++)
{
QDomElement file = document.createElement("File");
file.setAttribute("ID", ui->treeWidget->columnAt(0)); //1
file.setAttribute("Path", ui->treeWidget->columnAt(1)); //2
playlist.appendChild(file);
}
}
Can anyone help me out how to handle such situation wherein multiple column items are to be read. Comments 1 & 2 are the essence of whole story.

I think, you can write it like:
[..]
for(int h = 0; h < ui->treeWidget->topLevelItemCount(); h++)
{
QDomElement file = document.createElement("File");
QTreeWidgetItem *item = ui->treeWidget->topLevelItem(h);
file.setAttribute("ID", item->text(0)); //1
file.setAttribute("Path", item->text(1)); //2
playlist.appendChild(file);
}

Related

QList<QString> to QString.arg()

I have the following QString:
QString funcProxy = "executeProxy(\"%1\", \"%2\", \"%3\")";
The data for each on is in:
QList<QString> listProxy;
How would I go about adding the data in listProxy to funcProxy using the arg() method?
funcProxy.arg(??);
Thanks
Regarding the answer from #owacoder, you do not actually need the replace function, the following should work correclty:
for (int i = 0; i < listProxy.size(); ++i) {
funcProxy = funcProxy.arg(listProxy.at(i));
}
Why you ask: From the documentation on QString::arg()
Returns a copy of this string with the lowest numbered place marker replaced by string
Thus it replaces the lowest number with the string in the arg call. First iteration contains %1, %2 and %3, so it replaces %1. Next iteration contains %2 and %3, thus replaces %2.
Alternatively if you have control over funcProxy you can do the following given you can change your list to a QStringList:
QString funcProxy = "executeProxy(\"%1\")";
QStringList listProxy{"a", "b", "c"};
funcProxy = funcProxy.arg(listProxy.join("\", \""));
If you know you'll have exactly 3 elements in your list, you can do this:
funcProxy.arg(listProxy.at(0)).arg(listProxy.at(1)).arg(listProxy.at(2));
Otherwise, you could use this:
for (int i = 0; i < listProxy.size(); ++i)
funcProxy.replace(QString("%%1").arg(i+1), listProxy.at(i));

QGraphicsItem: Why no `stackAfter` method?

I'm having an annoying time trying to get around the 'recommended' way of doing something.
So, I have a stack of cards. I want to make it so that when I deal a card, it becomes the last-drawn object of the entire scene (typical bring_to_front functionality).
The recommended way to do this is just adding to the object's zValue until it is larger than all the rest, but I was hoping to do away with rather "lazy" integers running around all over the place with judicious use of the stackBefore method, which simulates reorganizing the order in which objects were added to the scene.
This works perfectly fine when I shuffle my cards in a limited set (get list of selected items, random.shuffle, for item do item.stackBefore(next item)), but it is certainly not working when it comes to bubbling the card to the top of the entire scene.
I considered adding a copy of the object to the scene and then removing the original, but it just seems like I should be able to do stackAfter like I would when using a Python list (or insertAt or something).
Sample code:
def deal_items(self):
if not self.selection_is_stack():
self.statusBar().showMessage("You must deal from a stack")
return
item_list = self.scene.sorted_selection()
for i,item in enumerate(item_list[::-1]):
width = item.boundingRect().width()
item.moveBy(width+i*width*0.6,0)
another_list = self.scene.items()[::-1]
idx = another_list.index(item)
for another_item in another_list[idx+1:]:
another_item.stackBefore(item)
This works. It just seems somewhat... ugly.
self.scene.items returns the items in the stacking order (link). So if you want to stackAfter an item, you can just query the z value of the current topmost item and then set the z value of the new topmost card to a value one larger.
item.setZValue(self.scene.items().first().zValue() + 1)
Hope that helps.
Edit added src for stackBefore and setZValue from http://gitorious.org/qt/
src/gui/graphicsview/qgraphicsitem.cpp
void QGraphicsItem::stackBefore(const QGraphicsItem *sibling)
{
if (sibling == this)
return;
if (!sibling || d_ptr->parent != sibling->parentItem()) {
qWarning("QGraphicsItem::stackUnder: cannot stack under %p, which must be a sibling", sibling);
return;
}
QList<QGraphicsItem *> *siblings = d_ptr->parent
? &d_ptr->parent->d_ptr->children
: (d_ptr->scene ? &d_ptr->scene->d_func()->topLevelItems : 0);
if (!siblings) {
qWarning("QGraphicsItem::stackUnder: cannot stack under %p, which must be a sibling", sibling);
return;
}
// First, make sure that the sibling indexes have no holes. This also
// marks the children list for sorting.
if (d_ptr->parent)
d_ptr->parent->d_ptr->ensureSequentialSiblingIndex();
else
d_ptr->scene->d_func()->ensureSequentialTopLevelSiblingIndexes();
// Only move items with the same Z value, and that need moving.
int siblingIndex = sibling->d_ptr->siblingIndex;
int myIndex = d_ptr->siblingIndex;
if (myIndex >= siblingIndex) {
siblings->move(myIndex, siblingIndex);
// Fixup the insertion ordering.
for (int i = 0; i < siblings->size(); ++i) {
int &index = siblings->at(i)->d_ptr->siblingIndex;
if (i != siblingIndex && index >= siblingIndex && index <= myIndex)
++index;
}
d_ptr->siblingIndex = siblingIndex;
for (int i = 0; i < siblings->size(); ++i) {
int &index = siblings->at(i)->d_ptr->siblingIndex;
if (i != siblingIndex && index >= siblingIndex && index <= myIndex)
siblings->at(i)->d_ptr->siblingOrderChange();
}
d_ptr->siblingOrderChange();
}
}
void QGraphicsItem::setZValue(qreal z)
{
const QVariant newZVariant(itemChange(ItemZValueChange, z));
qreal newZ = newZVariant.toReal();
if (newZ == d_ptr->z)
return;
if (d_ptr->scene && d_ptr->scene->d_func()->indexMethod != QGraphicsScene::NoIndex) {
// Z Value has changed, we have to notify the index.
d_ptr->scene->d_func()->index->itemChange(this, ItemZValueChange, &newZ);
}
d_ptr->z = newZ;
if (d_ptr->parent)
d_ptr->parent->d_ptr->needSortChildren = 1;
else if (d_ptr->scene)
d_ptr->scene->d_func()->needSortTopLevelItems = 1;
if (d_ptr->scene)
d_ptr->scene->d_func()->markDirty(this, QRectF(), /*invalidateChildren=*/true);
itemChange(ItemZValueHasChanged, newZVariant);
if (d_ptr->flags & ItemNegativeZStacksBehindParent)
setFlag(QGraphicsItem::ItemStacksBehindParent, z < qreal(0.0));
if (d_ptr->isObject)
emit static_cast<QGraphicsObject *>(this)->zChanged();
}

Mapping MPI processes to particular nodes

I think this question is irrelavant to ask here. But could n't help myself.
Suppose I have a cluster with 100 nodes with each node having 16 cores.
I have an mpi application whose communication pattern is already known and I also know the cluster topology(i.e hop distance between nodes).
Now I know the processes to node mapping that reduces the contention on the network. For example: process to node mappings are 10->20,30->90.
How do I map the process with rank 10 to the node-20?
Please help me in this.
If you are not constrained with any kind of a queueing system you can control the rank to node mapping by creating your own machinefile.
For instance if the file my_machine_file has the following 1600 lines
node001
node002
node003
....
node100
node001
node002
node003
....
node100
...
[repeat 13 more times]
...
node001
node002
node003
....
node100
it would correspond to the mapping
0-> node001, 1 -> node002, ... 99 -> node100, 100 -> node001, ...
you should run your application with
mpirun -machinefile my_machine_file -n 1600 my_app
When your application needs less than 1600 processes you can edit your machinefile accordingly.
Please remember though that the cluster admin has probably numbered the nodes respecting the topology of the interconnect. Yet there are reports of sensible increase (order of 10%-20%) in performance through careful exploitation of the cluster topology. (References to follow).
Note: Starting an MPI program with mpirun is neither standardized nor portable. However here the question is clearly related to a specific compute cluster and a specific implementation (OpenMPI) and does not request a portable solution.
A little late to this party, but here's a subroutine in C++ that will give you a node communicator and a master communicator (just for the masters of nodes), as well as the size and rank of each. It's clumsy, but I haven't found a better way to do this unfortunately. Luckily it only adds about 0.1s to the wall times. Maybe you or someone else will get some use out of it.
#define MASTER 0
using namespace std;
/*
* Make a comunicator for each node and another for just
* the masters of the nodes. Upon completion, everyone is
* in a new node communicator, knows its size and their rank,
* and the rank of their master in the master communicator,
* which can be useful to use for indexing.
*/
bool CommByNode(MPI::Intracomm &NodeComm,
MPI::Intracomm &MasterComm,
int &NodeRank, int &MasterRank,
int &NodeSize, int &MasterSize,
string &NodeNameStr)
{
bool IsOk = true;
int Rank = MPI::COMM_WORLD.Get_rank();
int Size = MPI::COMM_WORLD.Get_size();
/*
* ======================================================================
* What follows is my best attempt at creating a communicator
* for each node in a job such that only the cores on that
* node are in the node's communicator, and each core groups
* itself and the node communicator is made using the Split() function.
* The end of this (lengthly) process is indicated by another comment.
* ======================================================================
*/
char *NodeName, *NodeNameList;
NodeName = new char [1000];
int NodeNameLen,
*NodeNameCountVect,
*NodeNameOffsetVect,
NodeNameTotalLen = 0;
// Get the name and name character count of each core's node
MPI::Get_processor_name(NodeName, NodeNameLen);
// Prepare a vector for character counts of node names
if (Rank == MASTER)
NodeNameCountVect = new int [Size];
// Gather node name lengths to master to prepare c-array
MPI::COMM_WORLD.Gather(&NodeNameLen, 1, MPI::INT, NodeNameCountVect, 1, MPI::INT, MASTER);
if (Rank == MASTER){
// Need character count information for navigating node name c-array
NodeNameOffsetVect = new int [Size];
NodeNameOffsetVect[0] = 0;
NodeNameTotalLen = NodeNameCountVect[0];
// build offset vector and total char count for all node names
for (int i = 1 ; i < Size ; ++i){
NodeNameOffsetVect[i] = NodeNameCountVect[i-1] + NodeNameOffsetVect[i-1];
NodeNameTotalLen += NodeNameCountVect[i];
}
// char-array for all node names
NodeNameList = new char [NodeNameTotalLen];
}
// Gatherv node names to char-array in master
MPI::COMM_WORLD.Gatherv(NodeName, NodeNameLen, MPI::CHAR, NodeNameList, NodeNameCountVect, NodeNameOffsetVect, MPI::CHAR, MASTER);
string *FullStrList, *NodeStrList;
// Each core keeps its node's name in a str for later comparison
stringstream ss;
ss << NodeName;
ss >> NodeNameStr;
delete NodeName; // node name in str, so delete c-array
int *NodeListLenVect, NumUniqueNodes = 0, NodeListCharLen = 0;
string NodeListStr;
if (Rank == MASTER){
/*
* Need to prepare a list of all unique node names, so first
* need all node names (incl duplicates) as strings, then
* can make a list of all unique node names.
*/
FullStrList = new string [Size]; // full list of node names, each will be checked
NodeStrList = new string [Size]; // list of unique node names, used for checking above list
// i loops over node names, j loops over characters for each node name.
for (int i = 0 ; i < Size ; ++i){
stringstream ss;
for (int j = 0 ; j < NodeNameCountVect[i] ; ++j)
ss << NodeNameList[NodeNameOffsetVect[i] + j]; // each char into the stringstream
ss >> FullStrList[i]; // stringstream into string for each node name
ss.str(""); // This and below clear the contents of the stringstream,
ss.clear(); // since the >> operator doesn't clear as it extracts
//cout << FullStrList[i] << endl; // for testing
}
delete NodeNameList; // master is done with full c-array
bool IsUnique; // flag for breaking from for loop
stringstream ss; // used for a full c-array of unique node names
for (int i = 0 ; i < Size ; ++i){ // Loop over EVERY name
IsUnique = true;
for (int j = 0 ; j < NumUniqueNodes ; ++j)
if (FullStrList[i].compare(NodeStrList[j]) == 0){ // check against list of uniques
IsUnique = false;
break;
}
if (IsUnique){
NodeStrList[NumUniqueNodes] = FullStrList[i]; // add unique names so others can be checked against them
ss << NodeStrList[NumUniqueNodes].c_str(); // build up a string of all unique names back-to-back
++NumUniqueNodes; // keep a tally of number of unique nodes
}
}
ss >> NodeListStr; // make a string of all unique node names
NodeListCharLen = NodeListStr.size(); // char length of all unique node names
NodeListLenVect = new int [NumUniqueNodes]; // list of unique node name lengths
/*
* Because Bcast simply duplicates the buffer of the Bcaster to all cores,
* the buffer needs to be a char* so that the other cores can have a similar
* buffer prepared to receive. This wouldn't work if we passed string.c_str()
* as the buffer, becuase the receiving cores don't have string.c_str() to
* receive into, and even if they did, c_srt() is a method and can't be used
* that way.
*/
NodeNameList = new char [NodeListCharLen]; // even though c_str is used, allocate necessary memory
NodeNameList = const_cast<char*>(NodeListStr.c_str()); // c_str() returns const char*, so need to recast
for (int i = 0 ; i < NumUniqueNodes ; ++i) // fill list of unique node name char lengths
NodeListLenVect[i] = NodeStrList[i].size();
/*for (int i = 0 ; i < NumUnique ; ++i)
cout << UniqueNodeStrList[i] << endl;
MPI::COMM_WORLD.Abort(1);*/
//delete NodeStrList; // Arrays of string don't need to be deallocated,
//delete FullStrList; // I'm guessing becuase of something weird in the string class.
delete NodeNameCountVect;
delete NodeNameOffsetVect;
}
/*
* Now we send the list of node names back to all cores
* so they can group themselves appropriately.
*/
// Bcast the number of nodes in use
MPI::COMM_WORLD.Bcast(&NumUniqueNodes, 1, MPI::INT, MASTER);
// Bcast the full length of all node names
MPI::COMM_WORLD.Bcast(&NodeListCharLen, 1, MPI::INT, MASTER);
// prepare buffers for node name Bcast's
if (Rank > MASTER){
NodeListLenVect = new int [NumUniqueNodes];
NodeNameList = new char [NodeListCharLen];
}
// Lengths of node names for navigating c-string
MPI::COMM_WORLD.Bcast(NodeListLenVect, NumUniqueNodes, MPI::INT, MASTER);
// The actual full list of unique node names
MPI::COMM_WORLD.Bcast(NodeNameList, NodeListCharLen, MPI::CHAR, MASTER);
/*
* Similar to what master did before, each core (incl master)
* needs to build an actual list of node names as strings so they
* can compare the c++ way.
*/
int Offset = 0;
NodeStrList = new string[NumUniqueNodes];
for (int i = 0 ; i < NumUniqueNodes ; ++i){
stringstream ss;
for (int j = 0 ; j < NodeListLenVect[i] ; ++j)
ss << NodeNameList[Offset + j];
ss >> NodeStrList[i];
ss.str("");
ss.clear();
Offset += NodeListLenVect[i];
//cout << FullStrList[i] << endl;
}
// Now since everyone has the same list, just check your node and find your group.
int CommGroup = -1;
for (int i = 0 ; i < NumUniqueNodes ; ++i)
if (NodeNameStr.compare(NodeStrList[i]) == 0){
CommGroup = i;
break;
}
if (Rank > MASTER){
delete NodeListLenVect;
delete NodeNameList;
}
// In case process fails, error prints and job aborts.
if (CommGroup < 0){
cout << "**ERROR** Rank " << Rank << " didn't identify comm group correctly." << endl;
IsOk = false;
}
/*
* ======================================================================
* The above method uses c++ strings wherever possible so that things
* like node name comparisons can be done the c++ way. I'm sure there's
* a better way to do this because that was way too many lines of code...
* ======================================================================
*/
// Create node communicators
NodeComm = MPI::COMM_WORLD.Split(CommGroup, 0);
NodeSize = NodeComm.Get_size();
NodeRank = NodeComm.Get_rank();
// Group for master communicator
int MasterGroup;
if (NodeRank == MASTER)
MasterGroup = 0;
else
MasterGroup = MPI_UNDEFINED;
// Create master communicator
MasterComm = MPI::COMM_WORLD.Split(MasterGroup, 0);
MasterRank = -1;
MasterSize = -1;
if (MasterComm != MPI::COMM_NULL){
MasterRank = MasterComm.Get_rank();
MasterSize = MasterComm.Get_size();
}
MPI::COMM_WORLD.Bcast(&MasterSize, 1, MPI::INT, MASTER);
NodeComm.Bcast(&MasterRank, 1, MPI::INT, MASTER);
return IsOk;
}

Filling some QTableWidgetItems with QString from file

I'm trying to fill a QTableWidget from a file that was exported by my program, but when I try to set text to the table cells they just ignore me, nothing happens.
void MainWindow::on_actionOpen_Project_triggered()
{
QString line, fileName;
fileName = QFileDialog::getOpenFileName(this,tr("Open Project"), "", tr("Project Files (*.project)"));
if(!fileName.isEmpty()){
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return;
QTextStream in(&file);
for(int i=0;i<ui->code->rowCount();i++){ // goes through table rows
for(int j=0;j<ui->code->columnCount();j++){ // through table columns
ui->code->setCurrentCell(i,j);
QTableWidgetItem *cell = ui->code->currentItem();
in >> line;
if(!line.isEmpty()){
cell = new QTableWidgetItem(line); // relates the pointer to a new object, because the table is empty.
ui->errorlog->append(line); // just for checking if the string is correct visually.
}
}
}
file.close();
}
}
The errorlog object shows on the screen the correct values opened from the file, however the table is not filled. Any problems found?
This line:
cell = new QTableWidgetItem(line);
doesn't do what you think it does. Assigning the cell doesn't change anything in the table – cell is just a local variable, overwriting it doesn't have any effect elsewhere.
You (probably) want to do something like this instead:
cell->setText(line);
Or (if you don't really need to change the current item):
ui->code->item(i,j)->setText(line);
If those give you a segfault, it's that you haven't set the table's widget items yet. In that case, you should do something like:
QTableWidgetItem *cell = ui->code->item(i,j);
if (!cell) {
cell = new QTableWidgetItem;
ui->code->setItem(i,j,cell);
}
if (!line.isEmpty()) {
cell->setText(line);
}
This will populate all the cells with QTableWidgetItems the first time this function is called, and reuse them subsequently.

How to add items dynamically to QListWidget?

I want to add items dynamically to QListWidget in Qt.
I have used the following piece of code to add items dynamically, but I am able to add only one item in QListWidget...
for(int i=0; i<5; i++)
{
structLocationDetails[i].strlocationName = metaresult["locationName"];
QString strtemp = structLocationDetails[i].strlocationName;
list=new QListWidget(this);
list->setSortingEnabled(true);
list->setGeometry(0,0,190, 450);
QStringList items;
item1=new QListWidgetItem(QIcon(":/imagesIcon.png"),structLocationDetails[i].strlocationName,list);
connect(list,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(myitem(QListWidgetItem*)));
}
Here actually I am parsing an XML file and trying to add the parsed xml file contents(locationName) to the QListWidget.
How can I achieve this?
Please provide me any suggestions on this...
Thanks...
changing the code do the job...
list=new QListWidget(this);
list->setSortingEnabled(true);
list->setGeometry(0,0,190, 450);
connect(list,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(myitem(QListWidgetItem*)));
for(int i=0; i<5; i++)
{
structLocationDetails[i].strlocationName = metaresult["locationName"];
item1=new QListWidgetItem(QIcon(":/imagesIcon.png"),structLocationDetails[i].strlocationName,list);
}

Resources