How to set minimum height of QListWidgetItem? - qt

How can I set the minimum height of a QListWidgetItem? I'm using QListWidget::setItemWidget() with a customized widget, and although I explicitly declared minimum height of my customized widget, those QListWidgetItems still have a pretty low height attribute.

To set minimum height of each individual QListWidgetItem you can use sizeHint() function. For example, following code will set minimum height of all the QListWidgetItem to 30px..
int count = ui->listWidget->count();
for(int i = 0; i < count; i++)
{
QListWidgetItem *item = ui->listWidget->item(i);
item->setSizeHint(QSize(item->sizeHint().width(), 30));
}
Hope this helps..

Use setSizeHint on the items.
void QListWidgetItem::setSizeHint ( const QSize & size )
This is the right method for telling the delegate how much screen it must preserve for the item.
Look at http://qt-project.org/doc/qt-4.8/qlistwidgetitem.html#setSizeHint

Related

Qt connect QScrollBar with QLineEdit

I would like to "activate" the scrollbar when the lineedit text is too long to display on the window. I have already done it.
I want to move the cursor with the scrollbar. I also want to modify the scroll bar slider length with the increment/decrement of the text length.
.h
private:
Ui::MainWindow *ui;
QLineEdit* LineEdit;
QScrollBar* hScrollBar;
void HDScrollBar();
constructor:
resize(400,100);
LineEdit = new QLineEdit(this);
LineEdit->resize(400,100);
LineEdit->setFont(QFont("Times",20));
hScrollBar = new QScrollBar(Qt::Horizontal, LineEdit);
hScrollBar->resize(400,20);
hScrollBar->move(0,80);
hScrollBar->hide();
connect(LineEdit, &QLineEdit::textChanged, this, &MainWindow::HDScrollBar);
hide/display scrollbar
void MainWindow::HDScrollBar() {
QFont myFont(QFont("Times",20));;
QString str = LineEdit->text();
QFontMetrics fm(myFont);
int width = fm.horizontalAdvance(str);
(width >= 400) ? hScrollBar->show() : hScrollBar->hide();
}
As for the first part, you use can scrollbar's valueChanged signal, e.g. this way:
connect(ui->horizontalScrollBar, &QScrollBar::valueChanged, ui->lineEdit, [&](int v) {
auto scrollbarAt = static_cast<double>(v) / ui->horizontalScrollBar->maximum();
auto cursorTo = std::round(ui->lineEdit->text().length() * scrollbarAt);
ui->lineEdit->setCursorPosition(cursorTo);
});
EDIT:
as for the latter part:
you can either alter the PageStep of the scrollbar, or you can set it to 1 and alter its maximum value, then also the first part should simplify:
ui->horizontalScrollBar->setPageStep(1);
ui->horizontalScrollBar->setMaximum(ui->lineEdit.text().length());
connect(ui->horizontalScrollBar, &QScrollBar::valueChanged,
ui->lineEdit, &QLineEdit::setCursorPosition);
//this can also ben done on textChanged, however for the price
//of more frequent execution...
connect(ui->lineEdit, &QLineEdit::cursorPositionChanged,
ui->horizontalScrollBar, [&](int, int n) {
ui->horizontalScrollBar->setMaximum(ui->lineEdit->text().length());
//...one gets the easy way to track the cursor
//with the slider
ui->horizontalScrollBar->setValue(n);
});

equal row heights for QFormLayout

I am using QFormLayout with QLabels in the left column and various widgets in the right column. On the right, there are either labels, check boxes, combos or line edits. Unfortunately each of there controls has different natural height. But I would like to have each row in the form layout to have equal heights determined by the biggest one (I know in which row it is). Is there any simple way to achieve this? I cannot find anything like QFormLayout::setRowHeight().
One solution, just assign equal size to all widgets at runtime using the following function:
void setEqualRowHeight(QFormLayout *formLayout, int height)
{
QWidget *w;
for(int i = 0; i < formLayout->rowCount(); i++) {
QLayoutItem *item = formLayout->itemAt(i, QFormLayout::FieldRole);
if (item && (w = item->widget())) {
w->setFixedHeight(height);
}
}
}

How can we know the width and height of string?

I want to create a button exactly the same size as the string for this i want the width and height of the string.
To manually get the size of a string, you need to use the QFontMetrics class. This can be manually used like this:
QFont font("times", 24);
QFontMetrics fm(font);
int pixelsWide = fm.width("What's the width of this text?");
int pixelsHigh = fm.height();
If you want to calculate it for the font used in a given widget (which you may not know), then instead of constructing the fontmetrics, get it from the widget:
QFontMetrics fm(button->fontMetrics());
int pixelsWide = fm.width("What's the width of this text?");
int pixelsHigh = fm.height();
Then you can resize the widget to exactly this value.
Use QFontMetrics.
Example: http://www.developer.nokia.com/Community/Wiki/CS001349_-_Calculating_text_width_in_Qt

Layout with two tableviews problem

I have a widget containing two QTableViews in a horizontal layout. I would like them to resize to their preferred size (so that they don't have to show autoscrolls). I also don't want them to grow more than their preferred size and leave empty space to the right if there is any left. It should look like this:
I've tried to achieve it with a spacer on the right, but the views don't grow because of autoscrolls.
Can you propose any solution?
If I understood your question, you want the two QTableViews to resize to their PreferredSize if there is enough space (but no more than thier PreferredSize) and to shrink if there is not enough space. If there is too much space, it should be left empty. Here's an example that does it:
#include <QtGui>
int main(int argc, char **argv) {
QApplication app(argc, argv);
QMainWindow w;
QHBoxLayout *hbox = new QHBoxLayout;
QWidget *centralw = new QWidget;
centralw->setLayout(hbox);
w.setCentralWidget(centralw);
QTableView *t1 = new QTableView;
QTableView *t2 = new QTableView;
// Version one: the preferred size is the maximum size
// t1->setSizePolicy(QSizePolicy(QSizePolicy::Maximum, QSizePolicy::Preferred));
// t2->setSizePolicy(QSizePolicy(QSizePolicy::Maximum, QSizePolicy::Preferred));
// Version two: the preferred size is the only accepted size
// if you want the widgets not to change their size, change the two previous lines with
// t1->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
// t2->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
// hbox->addWidget(t1);
// hbox->addWidget(t2);
// add a stretch that will fill empty space
// hbox->addStretch(1);
// Version three: tables have a minimum and maximum width. They can be shrunk
// but they try to expand to take the maximum available space up to their maximum
// width.
t1->setMinimumWidth(150);
t1->setMaximumWidth(400);
t2->setMinimumWidth(100);
t2->setMaximumWidth(200);
t1->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));
t2->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));
hbox->addWidget(t1);
hbox->addWidget(t2);
hbox->setStretchFactor(t1, 1);
hbox->setStretchFactor(t2, 1); // tableviews have the same stretch factor
hbox->addStretch(0); // lowest stretch factor
w.show();
return app.exec();
}
You can reimplement parent's widget resizeEvent function and not to use a layout at all. So when the parent widget is resized you can manually set the sizes of your tables.
The other way you can try is to reimplement sizeHint or/and minimumSizeHint functions of the QTableView so they return a good for you size.
Also take a look at QSizePolicy - it may be usefull

How do I resize QTableView so that the area is not scrolled anymore

I want the size of the QTableView to be the same as the table it contains (and fixed) so that it does not have a scrollbar
What you could do is calculate your tableview columns widths according to the data they have (or you can just call resizeColumnToContents for each column to size it to its content). Then change the tableview width to be equal or more then total width of columns + vertical header if shown. You would also need to track model changes and adjust your tableview width + if horizontal header is shown you can track columns resize events and adjust them again. Below is some sample code for this:
initialization:
// add 3 columns to the tableview control
tableModel->insertColumn(0, QModelIndex());
tableModel->insertColumn(1, QModelIndex());
tableModel->insertColumn(2, QModelIndex());
...
// switch off horizonatal scrollbar; though this is not really needed here
ui->tableView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
// adjust size; see code below
adjustTableSize();
// connect to the horizontal header resize event (non needed if header is not shown)
connect(ui->tableView->horizontalHeader(),SIGNAL(sectionResized(int,int,int)), this,
SLOT(updateSectionWidth(int,int,int)));
// connect to the model's datachange event
connect(ui->tableView->model(), SIGNAL(dataChanged(QModelIndex,QModelIndex)),
this, SLOT(dataChanged(QModelIndex,QModelIndex)));
adjust tableview size:
void MainWindow::adjustTableSize()
{
ui->tableView->resizeColumnToContents(0);
ui->tableView->resizeColumnToContents(1);
ui->tableView->resizeColumnToContents(2);
QRect rect = ui->tableView->geometry();
rect.setWidth(2 + ui->tableView->verticalHeader()->width() +
ui->tableView->columnWidth(0) + ui->tableView->columnWidth(1) + ui->tableView->columnWidth(2));
ui->tableView->setGeometry(rect);
}
process model change
void MainWindow::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight)
{
adjustTableSize();
}
process horizontal header resize
void MainWindow::updateSectionWidth(int logicalIndex, int, int newSize)
{
adjustTableSize();
}
hope this helps, regards
sum(item.sizeHint()+headeroffset+border) doesn't work well for me, there's probably spacing between the items, even if grid is off. So I made adjustment this way:
view->resizeRowsToContents();
view->resizeColumnsToContents();
QAbstractItemModel* model = view->model();
QHeaderView* horHeader = view->horizontalHeader();
QHeaderView* verHeader = view->verticalHeader();
int rows = model->rowCount();
int cols = model->columnCount();
int x = horHeader->sectionViewportPosition(cols-1) + horHeader->offset()
+ horHeader->sectionSize(cols-1) + 1;
int y = verHeader->sectionViewportPosition(rows-1) + verHeader->offset()
+ verHeader->sectionSize(rows-1) + 1;
QPoint p = view->viewport()->mapToParent(QPoint(x,y));
QRect g = view->geometry();
g.setSize(QSize(p.x(),p.y()));
view->setGeometry(g);
Should work if the last column and last row is visible.
I tried serge_gubenko answer but I didn't work for me (Partly because I wanted to rezise both Height and Width)... so I altered it; To avoid the table being resized by layouts or parent widgets you will need this:
ui->tableView->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Fixed);
Then:
ui->tableView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
ui->tableView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
QRect rect = ui->tableView->geometry();
int width = 2,length = 2;
for(int col = 0;col<proxySortModel->columnCount();++col){
if(!ui->tableView->isColumnHidden(col))
width += ui->tableView->columnWidth(col);
}
for(int row =0;row<proxySortModel->rowCount();++row)
length += ui->tableView->rowHeight(row);
rect.setWidth(width);
rect.setHeight(length);
ui->tableView->setGeometry(rect);
I hope this helps someone.

Resources