3

I need to create a table like this

table

how can I align first column left, 2nd and 3rd columns center, and last column right sothat when someone put data in, it is automatically aligned as I want ?

My first code:

ui->tableWidget->setColumnCount(4);
ui->tableWidget->setRowCount(52);
ui->tableWidget->setHorizontalHeaderLabels(QStringList() << tr("Name") << tr("Age") << tr("Position") << tr("Salary"));

I know we have something like

ui.tableWidget->item(i, 0)->setTextAlignment(Qt::AlignLeft);

But i don't know how to set it for every row of a column.

Many thanks !

trangan
  • 341
  • 8
  • 22
  • Look at this http://stackoverflow.com/questions/4958893/how-to-set-text-alignment-on-a-column-of-qtableview-programatically or this http://stackoverflow.com/a/15828907/6385043. – maxik Jun 27 '16 at 07:42
  • Maybe use a *real* model (and a QTableView) so that you can return the right alignment for the alignment role. – peppe Jun 27 '16 at 08:09
  • @maxik: thanks for your hint. I tried with that already but it doesnt work. They program a table and they put data in it also. Here I program a table for other people to put data. – trangan Jun 27 '16 at 08:53
  • @peppe: thank you. I just have learnt Qt for a week. I dont understand your idea. What do you mean by "real model" ? Could you give me a hint with code ? – trangan Jun 27 '16 at 08:55
  • @htmlamateur you might go with peppe's answer or you read the second link more closely: http://stackoverflow.com/a/15829092/6385043 there it describes a factory implementation for item creation. Or subclassing the `QTableWidgetItem` itself. A plenty of possibilities to solve this. – maxik Jun 27 '16 at 08:57
  • @maxik: I still can not imagine how i could do it with each column. RIght now i just have such simple idea: `for (int i=0; itableWidget->rowCount(); i++) { ui->tableWidget->item(i,0)->setTextAlignment (Qt::AlignLeft); }` But I receive error message "access violation" :( – trangan Jun 27 '16 at 12:35
  • @htmlamateur the solution should work if you consider that `rowCount` must not match the current row count, so check the gathered item for `null`. Reading your code, I see you declare `ui->tableWidget->setRowCount(52);` and I think that you placed less then this count of elements inside, haven't you? I really like to point out the last point of the answer you received already (http://stackoverflow.com/a/37969001/6385043). Read this http://doc.qt.io/qt-5/model-view-programming.html, you will hardly find such a good documentation. – maxik Jun 27 '16 at 12:56
  • @maxik: thank you, I have solved this problem with model – trangan Jul 15 '16 at 13:28

0 Answers0