PDA

View Full Version : HOW CAN i RESIZE THE COLUMN WIDTH OF ONE OF THE COLUMNS IN A QTABLEVIEW



ayanda83
5th November 2017, 17:28
Hi ladies and gents, I have a QTableView with 4 columns and I would like to permanently resize the second column to 50% the entire width of the QTableView. I thought this would be something easy to figure out but it has proven otherwise. I have attached a screenshot of what I am trying to achieve below. As can be seen in the screenshot below, the second column is 3-times longer than the first and the third column.12655

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->tableView->setColumnWidth(1, 900);
model = new QStandardItemModel(74, 4, ui->innertabWidget);
this->setWindowTitle("Tender Bot");
QFile sitesFile("websites.txt");
if(!sitesFile.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug() << "Something went wrong, file did not open" <<endl;
}
else
{
QTextStream out(&sitesFile);
int count = 0;
while(!out.atEnd())
{
QModelIndex index = model->index(count, 0, QModelIndex());
model->setData(index, sitesFile.readLine(0).simplified());
count++;
}
}
model->setHeaderData(0, Qt::Horizontal, "Websites");
model->setHeaderData(1, Qt::Horizontal, "Downloaded");
model->setHeaderData(2, Qt::Horizontal, "Date");
model->setHeaderData(3, Qt::Horizontal, "Buttons");
ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
ui->tableView->setModel(model);
}I thought line 6 in the code snippet above would achieve my desired outcome but it doesn't work.

Please assist.

d_stranz
6th November 2017, 02:00
Methods to set the sizes of table elements generally don't work unless the table is visible (and maybe has content). So calling these methods in the constructor have no effect since the table will not become visible until the showEvent() of the MainWindow has occurred. Try implementing MainWindow:: showEvent() and insert that sizing code there. You'll also be able to retrieve the actual size of the table at that point and set the column width to the true 50% you are aiming for.

AND PLEASE DON'T USE ALL CAPS WHEN POSTING TITLES. IT IS ANNOYING AS WELL AS BEING HARD TO READ. It doesn't get your question answered any faster either. Thanks.