Adjust QTableView Height to its content (few lines) - qt

Below a screenshot of my application. I want to get rid of the white spaces after the last tables lines marked by red rectangles :
The horizontal size policy is expanding and the vertical one is minimum and for other tables it is both set to expanding.
I'm using this method I found in another SO question but as you can see the result is not flawless.
void verticalResizeTableViewToContents(QTableView* tableView)
{
tableView->resizeRowsToContents();
// does it work ?
tableView->setSizeAdjustPolicy(QAbstractScrollArea::AdjustToContents);
int rowTotalHeight = 0;
// Rows height
int count = tableView->verticalHeader()->count();
for (int i = 0; i < count; ++i) {
// 2018-03 edit: only account for row if it is visible
if (!tableView->verticalHeader()->isSectionHidden(i)) {
rowTotalHeight += tableView->verticalHeader()->sectionSize(i);
}
}
// Check for scrollbar visibility
if (!tableView->horizontalScrollBar()->isHidden())
{
rowTotalHeight += tableView->horizontalScrollBar()->height();
}
// Check for header visibility
if (!tableView->horizontalHeader()->isHidden())
{
rowTotalHeight += tableView->horizontalHeader()->height();
}
tableView->setMaximumHeight(rowTotalHeight);
}
Somewhere, I'm using this code to setup one of the tables :
m_Internals->Ui.Measures->setModel(mm->getPh66MeasuresModel());
m_Internals->Ui.Measures->horizontalHeader()->setSectionsMovable(true);
m_Internals->Ui.Measures->horizontalHeader()->setHighlightSections(false);
m_Internals->Ui.Measures->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
m_Internals->Ui.Measures->horizontalHeader()->setStretchLastSection(true);
m_Internals->Ui.Measures->verticalHeader()->hide();
m_Internals->Ui.Measures->setSelectionBehavior(QAbstractItemView::SelectRows);
verticalResizeTableViewToContents(m_Internals->Ui.Measures);
I'm using Qt ModelView pattern to populate/update the tables.
Update : I made a small example to reproduce this issue with QTableView : https://github.com/embeddedmz/QTableViewAdjustPolicyNotWorkingProperly
Using the latest Qt version (from Qt official installer), there's no issue. However, using the Qt library provided by vcpkg (outdated for sure) the issue is there.
With Qt provided by vcpkg :
With the latest Qt provided by the Qt Company (update not the latest, it's 5.12.11) :

If you have something fully buildable on Ubuntu 20.04 LTS, post a link to the complete project (strip it down to just this part) and I will take an actual stab at it.
My gut, having worked with Qt for years, is telling me you are being burned by Margins.
https://doc.qt.io/qt-5/qwidget.html#contentsMargins
You probably need to set a bottom margin of Zero.
https://doc.qt.io/qt-5/qmargins.html#setBottom
If you retrieve the margins for those widgets you will probably find they are non-zero.

you can also fix your problem with one trick, this problem happens for you because your data is lower than the table size. I clone your project and change sizepolicy

Under Qt 5.12.11, the bug does not exist. So I took a look at the QAbstractScrollArea::sizeHint code of this version and compared it with the implementation used in recent versions of Qt and found that setting verticalScrollBarPolicy to "ScrollBarAlwaysOff" the "AdjustToContents" adjustment policy works. The default value was "ScrollBarAsNeeded", in fact we can see that this value is not handled but since in Qt 5.12.11 we only compare the vertical|horizontal]scrollBarPolicy to Qt::ScrollBarAlwaysOn it prevents this bug from appearing.

Related

Why is QLineWidth not taken into account?

In Qt3D certain properties of rendered objects are not just simply set on the renderer, but they are globally (per view) or locally (on the material of a rendered object) added to the renderPasses - or so is my comprehension at least. (I'm using PySide2 - but the code is almost the same in C++)
For example when adding a geometry-renderer and using its primitive type point (Qt3DRender.QGeometryRenderer.Point) instead of rendering triangle-faces it displays the points of the geometry.
Here is an example figure with the default type.
The same only showing the points (renderer.setPrimitiveType(Qt3DRender.QGeometryRenderer.Points))
Hard to guess, but here the point-size has been already been changed - using the following code:
material = Qt3DExtras.QPhongMaterial(e)
for t in material.effect().techniques():
for rp in t.renderPasses():
pointSize = Qt3DRender.QPointSize(rp)
pointSize.setSizeMode(Qt3DRender.QPointSize.SizeMode.Fixed)
pointSize.setValue(5.0)
rp.addRenderState(pointSize)
According to the documentation the same mechanism can be used to change the line-width when rendering the object with Lines (LineStrip) as primitive type. Adding
lineWidth = Qt3DRender.QLineWidth(rp)
lineWidth.setValue(5.)
lineWidth.setSmooth(True)
rp.addRenderState(lineWidth)
does not change the line-width.
Why? Where do I need to add QLineWidth? Is it the material I chose which ignores the QLineWidth-state?
I'm fighting with similar problems at the moment. I tried to reproduce the behaviour with Qt3D line width test. When setting format version to 4.6 with CoreProfile, the maximum of linewidth seems to be 1 (or equivalently width=3 displayed by the line test).
It might be possible that this is the maximum supported range.
See:
https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glLineWidth.xhtml
opengl glLineWidth() doesn't change size of lines
Note: I deliberately chose version 4.6 as that is the supported openGL version on my environment.
I ran into the same issue. It appears the problem is caused by Qt3DExtras::Qt3DWindow, which constructs a QSurfaceFormat with an OpenGL core profile. The glLineWidth function is not supported in the core profile.
Unfortunately there is no way to pass a QSurfaceFormat to Qt3DWindow. Setting a new format after the window is created also does not work.
The only way around this is to write your own window class with a QSurfaceFormat in compatibility mode. For example:
setSurfaceType(QSurface::OpenGLSurface);
QSurfaceFormat format = QSurfaceFormat::defaultFormat();
format.setVersion(4, 3);
format.setProfile(QSurfaceFormat::CompatibilityProfile);
format.setDepthBufferSize(24);
format.setSamples(4);
format.setStencilBufferSize(8);
setFormat(format);
QSurfaceFormat::setDefaultFormat(format);
Fortunately Qt3DExtras::Qt3DWindow does not actually contain a lot of functionality and you can easily write a similar class with the QSurfaceFormat changes mentioned above.
You can find the original source here for reference:
https://code.woboq.org/qt5/qt3d/src/extras/defaults/qt3dwindow.cpp.html

Qt OpenCV write video from capture frame, not saving

I can succesfully save video which I captured from c++ opencv there is no problem.
Bu similar code not capturing the video. Just opening out.avi . and only 6 kb.
I put the code in showframe func. there is no resizing fyi.
Anybody has experience with the opencv videowriter on the Qt?
void Widget::show_frame(Mat &image)
{
Mat resized_image = image.clone();
video.write(image);
int width_of_label = ui->label_camera->width();
int height_of_label = ui->label_camera->height();
Size size(width_of_label, height_of_label);
// cv::resize(image, resized_image, size);
cvtColor(image,image,CV_BGR2RGB);
cvtColor(resized_image, resized_image, CV_BGR2RGB);
ps : Platform MacOSX
I encountered the same problem with you, and I have tried many solutions, I think you can make the fifth parameter of videowriter() be false. That is, VideoWriter out = VideoWriter(video_name, CV_FOURCC('D', 'I', 'V', 'X'),frame_fps,Size(frame_width,frame_height),false). This works for me!
make sure that your application has access to the opencv_ffmpeg*.dll. For example place it in the working directory or the PATH variable.
Try different codecs, too. Afaik, MJPG did work on all tested machines/systems so far.

Qt-Application is killing characters accidentally (drawText produces bug)

I've got a really simple application for adding watermarks to pictures. So you can drop your pictures in a QListWidget which shows you a thumbnail and the path, adjust some things like the text, the transparency, the output format and so on.. and after pressing start it saves the copyrighted picture in a destination of your choice. This works with a QPainter which paints the logo and text on the picture.
Everything is able to work fine. But here's the misterious bug:
The application kills random letters. It's really strange, because I can't reproduce it. With every execution and combination of options it's different. For example:
Sometimes I can't write some letters in the QLineEdit of my interface (like E, 4 and 0 doesnt exist, or he changes the letters so some special signs).
The text of the items in the QListWidget aren't completly displayed, sometimes completley missing. But I can extract the text normally and use the path.
While execution I have a QTextBrowser as a log to display some interesting things like the font size. Although, the font is shown normaly on the resulting picture, it says " 4" or "6" instead of much higher and correct sizes. Betimes strange white blocks appear between some letters
When drawing text on the picture with a QPainter, there also letters missing. Sometimes, all the letters are printed over each other. It seems like this bug appears more often when using small pixelsizes (like 12):
//Text//
int fontSize = (watermarkHeight-(4*frame));
int fontX = 2*frame;
int fontY = (result.height()-(watermarkHeight-2*frame));
int fontWidth = watermarkWidth;
QRect place(fontX,fontY,fontWidth,fontSize);
QFont font("Helvetica Neue", QFont::Light);
font.setPixelSize(fontSize);
emit log(QString::number(fontSize));
pixPaint.setFont(font);
pixPaint.setPen(QColor(255,255,255,textOpacity));
pixPaint.drawText(place,text);
Not all of these bugs appear at once! Sometimes I haven't got any bugs...
Perhaps someone had a similar bug before. Unfortunately I didn't found something like this in the internet. I didn't post a lot of code snippets because I think (and hope) that this is a gerneral problem. If you need something specific to help me, please let me know =)
I've added a example picture:
In the lineEdit I simply wrote ABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890 (look what he has done with the 7 and 9)
This small square in the lower corner of the picture should be the "ABC..." thing
The "62" looks very strange in the textBrowser
I'm using Qt 5.0.1 on a Windows 7 64Bit computer.
EDIT: Everytime after adding the first picture to the list, he's finding these warnings:
QFontEngine::loadEngine: GetTextMetrics failed ()
QWindowsFontEngine: GetTextMetrics failed ()
But when I change the height (and with it the pointSize of the font) its not emitted anymore, even with the start-parameters.
EDIT 2: Thank you for your help! I corrected my code so that he only uses correct fonts and correct sizes, but it still doesn't work. When I remove the QPainter::drawText() function it works fine (without the text). But as soon as I am adding text everything is bugged. I have something like this now:
//Text//
QList<int> smoothSizes = fontDatabase->smoothSizes("Verdana","Standard");
int fontSize = (watermarkHeight-(4*frame))*0.75;
emit log("Requested: "+QString::number(fontSize));
if(!smoothSizes.contains(fontSize)){
for(int i = 0; i<smoothSizes.length(); i++){
if(smoothSizes.at(i) > fontSize && i>0){
fontSize = smoothSizes.at(i-1);
break;
}
}
}
int fontX = 2*frame;
int fontY = (result.height()-(watermarkHeight/2)+frame);
QFont font = fontDatabase->font("Verdana","Standard",fontSize);
QFontInfo info(font);
emit log("Corrected: "+QString::number(fontSize));
emit log("Okay?: "+QString::number(info.exactMatch()));
pixPaint.setFont(font);
const QFontMetrics fontMetrics = pixPaint.fontMetrics();
if(info.exactMatch()){
pixPaint.setPen(QColor(255,255,255,textOpacity));
pixPaint.drawText(fontX,fontY+(fontMetrics.height()-fontMetrics.ascent()),text);
}
It almost sounds like you are corrupting random memory in your process, or you have a badly broken Windows install. Possibly your font request is matched by a very poorly chosen system font.
Whatever is set on a QFont is merely a request. To obtain the parameters of the actual font that was selected, you must create a QFontInfo, and get your information from there.
Imagine that you request a QFont that doesn't exist on a system, or that can't be scaled to a particular size. At some point the font object would need to morph to reflect what really happened - this would be very confusing. Thus, the QFontInfo provides the information about the font that was actually used. Think of QFontInfo as a response, and QFont as a request.
I finally found a solution: I simply updated Qt from 5.0.1 to 5.2.1, now it works. Perhaps someone has a similar bug and this post helps him. Thank you for your help!

Multiple script/paperscripts in the same paperscope

I'm starting with paper.js. I like the fact that it introduces the possibility to have a script with a text/paperscript mime type, which runs in its on scope. However, scripts can become large pretty soon, so I want to be able to divide it in multiple scripts for readability. I thought I could just add more than one script tag and have them all run in the same scope, but apparently this isn't the case.
Both scripts are loaded and do run, but the second script doesn't seem to be in the paper scope.
I've set up an example here: http://barbata.nl/SO/Maps/ This example has some code, but I'll point out the important bits.
It contains two paperscripts:
Maps.js is the main script, which rasterizes the image and allows moving it around. You can ignore the code in this script, for it works fine so far.
Zoom.js is the script in which I wanted to isolate zooming functionality. It uses jq.mobi to capture the scroll wheel of the mouse, since Paper.js doesn't seem to have that event. It then translates that to a call to onMouseScroll, in a similar way Paper does it.
So far so good. The actual problem arises with the zoomIn and zoomOut functions in zoom.js.
It works if I explicity use the paper object to reference the view I want to zoom:
function zoomIn()
{
if (paper.view.zoom < 2)
{
paper.view.zoom = paper.view.zoom * 2;
}
}
But it fails when I remove paper and just reference the view:
function zoomIn()
{
if (view.zoom < 2)
{
view.zoom = view.zoom * 2;
}
}
This surprises me, as I expected the script to be a Paperscript, running in the Paperscope. It works fine if I put this code in Maps.js, so it seems that although zoom.js is loaded by Paper.js (the developer tools in the browser confirm this), it isn't run in the Paperscope.
My question is: are my findings correct? Am I doing something wrong? What is the right way to divide a Paper.js application into multiple units for readability?
Of course I can get it running, but I want to make sure I do it right.
This is indeed how it works. I've opened an issue on GitHub
I found that the "cleanest" way is to do it with this.install(window). It also makes error finding with Chrome developer tools easier since it is more adapted to reporting on the line errors in java-script than "paperscript".
in index.html (for example):
<script type="text/javascript" src='js/other_lib.js'></script>
<script type="text/paperscript" canvas="canvas">
this.install(window);
/*no code 'required' here */
</script>
<body>
<canvas id="canvas" width="1500" height="500"></canvas>
</body>
Then in the js/other_lib.js i just add code as normal:
var r = new Path.Rectangle([100,100],[200,200]);
r.fillColor = 'black';
/*more code here*/
This should generate a rectangle.
What DOES'T NOT WORK for me (as of Paper.js v0.10.2 Release Date: 9. July 2016) is the object operators. Such as adding vecrots pointc = pointa + pointb; for me this is giving a lot of NaN values.
I have had to edit a few libs to get this working, but the change is simple:
var pointc = new Point(pointa.x+pointb.x,pointa.y + pointb.y);

QTableWidget: How can I get tighter lines with less vertical spacing padding?

The QTableWdiget is fabulous for simple grid displays. Changing colors, fonts, etc is straightforward.
However, I did not manage to give the grid a 'tighter' look with less vertical whitespace. I see that the Qt documentation talks (eg here) about
margin
border
padding
around widgets, but when I set these I only get changes around the entire grid widget rather than inside.
How can I set this (with a style sheet, or hard-coded options) directly to make the QTableWidget display tighter?
The code getting 'h' might be unsound. It was just an example. Copy & paste the following rather rudimentary code. Change the value in "setDefaultSectionSize()", recompile, and run. You should see the difference. Setting this to 10 or 50 yields visible results. In the code above, it is possible QFontMetrics or QFont is messing something up.
You can use whatever you want to get the height, but font size makes the most sense.
#include <QtGui>
int main( int argc, char* argv[] )
{
QApplication app( argc, argv );
QDialog* my_dialog = new QDialog();
QHBoxLayout* layout = new QHBoxLayout();
QTableWidget* my_table_widget = new QTableWidget( my_dialog );
my_table_widget->setRowCount( 10 );
my_table_widget->setColumnCount( 10 );
my_table_widget->verticalHeader()->setDefaultSectionSize( 15 );
layout->addWidget( my_table_widget );
my_dialog->setLayout( layout );
my_dialog->resize( 500, 200 );
my_dialog->show();
return app.exec();
}
EDIT: I don't know how to format a block of code here... forgive me. :)
Edit 2: I fixed that, and the following simple tighterTable.pro file
helps along.
TEMPLATE = app
TARGET =
DEPENDPATH += .
INCLUDEPATH += .
SOURCES += tighterTable.cpp # if that is the filename
Thanks a big fat bunch for this. BTW: Editing as code is just indenting by four spaces, and/or hitting the button with the little '101010' in the formatting row.
What you're looking for has a very silly solution IMHO, but it works. You need to set the headers' defaultSectionSize() members. Accessed via verticalHeader() & horizontalHeader(). I never really set the column width's w/ this b/c most of my projects involve me adding rows, not columns, and I just call resizeColumnsToContents or do a manual resizing. However, the rows is irksome. I generally get the height of the font using QFontMetrics, and add 2. Any subsequent row added should have this height, and viola: tighter look.
Hope that helps.
EDIT:
Untested code:
QFontMetrics fm( my_font );
int h = fm.height() + 2;
my_table->verticalHeader()->setDefaultSectionSize( h );
QTableWidget is a convenience model and view. Typically, QAbstractItemModel's data() method provides a SizeHintRole that is used to tell the view what size each cell should be.
Since you're using QTableWidget, I don't think there's anything that you can do to change the size hint being returned by its internal model. Even the Qt style sheet documentation mentions nothing in that area.
QTableWidget -> verticalHeader -> setMinimumSectionSize() is the right way, and it can be set in ui.
I tried all the answers here without success. What worked for me though was setting both the following.
table->verticalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents)
table->verticalHeader()->setMaximumSectionSize(10)

Resources