Qt5.2/C++ Critical/Fatal error detection - c++

Good Day All,
I am using the following code to open and display html content.
void MyClass::playHtml(QString filePath, int w, int h) {
QUrl url = QUrl::fromLocalFile(filePath);
mWidget = new QWebView(this);
mWidget->page()->mainFrame()->setScrollBarPolicy(Qt::Horizontal, Qt::ScrollBarAlwaysOff);
mWidget->page()->mainFrame()->setScrollBarPolicy(Qt::Vertical, Qt::ScrollBarAlwaysOff);
mWidget->setGeometry(0, 0, width(), height());
float h_scale = (float) height() / h;
float w_scale = (float) width() / w;
float zoom = 1.0;
if (h_scale < w_scale) {
zoom = h_scale;
} else {
zoom = w_scale;
}
mWidget->setZoomFactor(zoom);
mWidget->load(url);
mWidget->show();
}
To copy to clipboard, switch view to plain text mode
This is inside the MyClass, which sets its own geometry and this function scales the QWebView appropriately to maintain aspect ratio. The Deletion for the mWidget(QWebView pointer) is being called when the MyClass object is deleted. Here is the process of how it is called.
1.) MyClass is instantiated as “mclass”.
2.) after instantiation, the playHtml method above is called on mclass object
3.) the playHtml method above takes the full path to an html file that resides in a self-contained folder, the w/h are the pre-determined dimensions of the html content are used in scaling
4.) after about 25 seconds, the mclass object is deleted
4a.) during those 25 seconds the playHtml method scales the html content appropriately, and loads the html file. A lot of javascript happens for animation, etc.
5.) after the deletion another instantiation of MyClass occurs and the process is repeated
this process can be repeated literally 3000 times in a day, one after another. Neither the cpu nor ram are taxed during this time. The only thing I left out of the process above is the logging. I installed a MessageHandler to log the qDebug and other messages.
Here is what I am seeing in the logs after the above process runs for a while (anywhere from a couple of hours to a few days).
A bunch of these per instance of “MyClass”:
CRITICAL: QWindowsBackingStore::flush: GetDC failed ()
followed by a bunch of these per instance of “MyClass”:
CRITICAL: QWindowsBackingStore::flush: BitBlt failed ()
Followed shortly by a crash.
In the event viewer, I get the crash “Error” message. It is always in one of these faulting modules MSVCR100.dll or one of the Qt5Webkit or Qt5WebkitWidget dlls.
I am not specifically drawing anything. I relying on the QWebView to do that — both for drawing itself and the content it contains. It does it well except when the above starts occurring. Nothing else is running on the machine except the software.
How would one go about detecting errors like this? At this point, I don’t know anything about them until they get to the log. I would like to detect and deal with them before that time but am unsure how. As a side note, I would like to take this opportunity to learn more about error detection in general for Qt and C++. Primarily, how do I detect errors like this that seem to be occurring further up the food chain. I fear I have been spoiled by the stack traces provided by Java/C#.
Environment information:
Windows 7 professional 64bit
Qt 5.2.1 (32 bit)
Compiled using VS2010
Thanks!
-Jason

Related

QTableView slow scrolling when many cells are visible at once

Background: I'm developing application using Qt 5.5.1, compiling with msvc2013. In this app I use my own implementation of QTableView, along with custom QStyledItemDelegate (needed custom cell editing) and QAbstractTableModel. I intend this view to work with massive amount of data that I wrap inside mentioned model. I allow the user few data editing options, custom sorting, 'invalid' rows windup etc.
The problem: scrolling speed of my QTableView subclass is slow - it gets slower the more table is shown (by resizing window), e.g. ~250 cells shown (in fullscreen) = slow, ~70 cells shown (small window) = fast.
Whad did I try so far:
First was to check if my model is slowing things down - I have measured times (using QTime::elapsed()) reading 10k samples and it shown 0 or 1ms. Then I have simply altered QTableView::data method to always return predefined string and not acquire any real data.
QVariant DataSet_TableModel::data(const QModelIndex &index, int role) const
{
if (role == Qt::ItemDataRole::DisplayRole) {
return QVariant("aRatherLongString"); //results in slow scrolling
//return QVariant("a"); // this instead results in fast scrolling
}
else return QVariant();
}
As you can see, the speed seems to be affected by number of characters vieved per cell, and not by underlying connections to data source.
In my custom implementation of QStyledItemDelegate I have tried same 'trick' as above - this time overriging displayText method:
QString DataSet_TableModel_StyledItemDelegate::displayText(const QVariant &value, const QLocale &locale) const
{
return "a" //fast
// return "aRatherLongString"; //slow
// return QStyledItemDelegate::displayText(value, locale); //default
}
After some thought with a friend we concluded that maybe we could disable drawing/painting/updating of cells until whole scroll action is done. It might cause some flickering, but it's worth a try. Unfortunately we dont really know how to aproach this. We have everriden QTableView methods: scrollContentsBy(int dx, int dy) and verticalScrollbarAction(int action) - we have captured scroll action properly (either method intercepts it) and tried to somehow disable repainting like this:
void DataSet_TableView::verticalScrollbarAction(int action) {
this->setUpdatesEnabled(false);
QTableView::verticalScrollbarAction(action);
this->setUpdatesEnabled(true);
}
...but it did not have any visible effect.
How should we approach it? Do we need to use setUpdatesEnabled() on items that are put inside cells directly? (not sure what those are - widgets?)
Here are screenshots taken as part of testing this problem:
Predefined text, no calls to underlying data structure - slow scrolling, 'full screen'
Predefined text, no calls to underlying data structure - fast scrolling, windowed
Request: Could you kindly help me pinpoint the cause of this and suggest solution if possible? Is it limitation of the classes that I use?
First of all, you should also run your application in release mode to check your perfomance, in my experience, the performance decreases greatly when using debug mode.
Secondly, you need to be aware that the model data method and delegates methods are called every time you resize, scroll, focus out, right click etc. These actions trigger those methods to be called for each displayed cell, therefore you would need to make sure that you don't do any unnecessary processing.
The items inside cells are delegates that call their own methods (eg: paint).
Some C++ specific optimisations would be helpful in the implementation of these methods, like using a switch instead of an if statement, see explanation here and here. The usage of Conditional (Ternary) Operators might also speed up the things, more information here, here and some information about expensive checkings here.
Also, QVariant handles text in different ways, as exemplified below, you should try both ways and check if there is any difference in speed. Some conversions are more expensive than others.
v = QVariant("hello"); // The variant now contains a QByteArray
v = QVariant(tr("hello")); // The variant now contains a QString

Reordering MFC control IDs automatically

I've got a pretty old MFC application that's been touched by many people over the years (most of them probably not even CS guys) and it follows, what I like to call the "anarchy design pattern."
Anyway, one of the dialogs has a series of 56 vertical sliders and check boxes. However, there are additional sliders and checkboxes on the dialog as shown below.
Now, the problem is that the additional sliders and checkboxes take on IDs that are in sequence with the slider/checkbox series of the dialog. My task is to add more sliders and checkboxes to the series (in the blank space in the Slider Control group box) Unfortunately, since IDC_SLIDER57 through IDC_SLIDER61 are already in the dialog (same goes for the checkboxes), existing code, such as the snippet below will break:
pVSlider = (CSliderCtrl *)GetDlgItem(IDC_SLIDER1+i);
Is there a better way to modify the resource file without doing it manually? I've seen a third party tool called ResOrg that looks like it'll help do what I want, but the software is a bit pricey, especially since I'll only use it once. I guess I can give the demo a try, but the limitations might restrict me.
FYI, I'm using Visual C++ 6.0 (yes...I know, don't laugh, it's being forced upon me).
Instead of writing:
pVSlider = (CSliderCtrl *)GetDlgItem(IDC_SLIDER1+i);
you could write:
pVSlider = (CSliderCtrl *)GetDlgItem(GetSliderID(i));
where GetSlider is a function that returns the id of slider number i.
GetSlider function
int GetSliderID(int nslider)
{
static int sliderids[] = {IDC_SLIDER1, IDC_SLIDER2, IDC_SLIDER3, .... IDC_SLIDERn};
ASSERT(nslider < _countof(sliderids));
return sliderids[nslider];
}
With this method the IDC_SLIDERn symbols dont need to have sequential values.

How to show "waiting" while files are loaded in a Qt application?

I'm selecting and loading some big Dicom files on my program. The whole loading process takes a long time(depends on the number of files, but the whole process can take more than minutes if the files are many). I want show a "waiting symbol" or something like that when the file uploading is going on. I searched for it, but I didn't get anything definite.
My code for the selection and uploading part is as below:
void MainWindow::showTheSelectedList()
{
QFileDialog * fileDialog = new QFileDialog(this);
fileDialog->setFileMode(QFileDialog::ExistingFiles);
QListView* list = fileDialog->findChild<QListView*>("listView");
if(list)
{
list->setSelectionMode(QAbstractItemView::MultiSelection);
}
QTreeView* tree = fileDialog->findChild<QTreeView*>();
if(tree)
{
tree->setSelectionMode(QAbstractItemView::MultiSelection);
}
if(fileDialog->exec())
{
if(fileDialog->selectedFiles().size()>0)
{
int listsize=stringList.size();
for(int i=0;i<listsize;i++)
{
// get the name of the file
// check if the file is dicom
// upload if the file is dicom
// after uploading, get the pixel data of that file
// use the pixel data and make a icon out of it
//then insert the icon in an a QTablewView
}
}
}
//show the QtableView
}
Could you please instruct me where and how I can show the waiting sign or symbol while the uploading part is running?
Thanks
I think you are looking for the QProgressBar class. The documentation makes it clear below. You will need to set up the minimum and maximum values, and it will do the job for you.
The QProgressBar widget provides a horizontal or vertical progress bar.
A progress bar is used to give the user an indication of the progress of an operation and to reassure them that the application is still running.
The progress bar uses the concept of steps. You set it up by specifying the minimum and maximum possible step values, and it will display the percentage of steps that have been completed when you later give it the current step value. The percentage is calculated by dividing the progress (value() - minimum()) divided by maximum() - minimum().
You can specify the minimum and maximum number of steps with setMinimum() and setMaximum. The current number of steps is set with setValue(). The progress bar can be rewound to the beginning with reset().
If minimum and maximum both are set to 0, the bar shows a busy indicator instead of a percentage of steps. This is useful, for example, when using QNetworkAccessManager to download items when they are unable to determine the size of the item being downloaded.
I do not think much more details can be provided based on the question as the worker loop seems to be commented without actual code being provided in there, but this documentation should make it clear either way.
Note that I would personally even move the worker loop into an own worker thread if it is that hefty that it deserves a progressbar. As for the progressbar, you would probably write something like this:
QProgressBar bar(this);
bar.setRange(maximum, maximum);
bar.setValue(minimum);
bar.show();
Dialog box:
My novice suggestion would be to use progress bar inside your for loop and increment the progress bar as each file finishes loading.
Let me know if you need more detail.

SDL2 Memory Leaks C++

So when I run the app, at the biginning every thing runs smooth, but the more it goes, the slower it is. I looked at the memory it was using and when it reaches 400 mb it completely stops for 30 secs and then drop back to 200.
I am pretty new to SDL2, and I assume it is because each frame I call:
optionsTS = TTF_RenderText_Blended(font, "Options.", blanc);
optionsT = SDL_CreateTextureFromSurface(renderer, optionsTS);
for example and I have plenty of them.
The problem is that I don't know how to delete properly the object each frame, because if I do a SDL_FreeSurface I get an error.
I won't publish my whole code because it's a mess, but if you want it, feel free to ask.
Do you know how to fix that?
Just thought I would turn my comment into an answer.
In your code you call
optionsTS = TTF_RenderText_Blended(font, "Options.", blanc);
optionsT = SDL_CreateTextureFromSurface(renderer, optionsTS);
every frame, I suspect that if you remove them from there, initialise them outwith of the render loop and simply pass them in as arguments, you should lose the memory leak: the reason being that you will create only one in-memory instance of each and then you can repeatedly use them as needed. On looking at it again, I suspect that you could destroy optionTS once you have made optionT, that way you will save even more memory. (not tested yet as my main machine just crashed this weekend, and I am still re-installing drivers and VS2010)
As a general rule, try and not create/destroy any objects in the render loop, tends to get big and messy fast.
Consider taking advantage of RAII in C++ if possible.
For example, create a class that wraps an SDL_Surface and calls SDL_FreeSurface in the destructor.
class MySurface
{
public:
MySurface(SDL_Surface & surface) : m_surface(surface) {}
~MySurface() {SDL_FreeSurface(m_surface);}
SDL_Surface & GetSDLSurface() {return m_surface;}
private:
SDL_Surface & m_surface;
};
You would then create an instance of MySurface every time you grabbed an SDL_Surface from the SDL API, and you won't have to worry about when or whether to free that surface. The surface will be freed as soon as your instance of MySurface goes out of scope.
I'm certain better implementations can be written and tailored to your needs, but at a minimum something similar to this may prevent you from having leaks in the future.

Qt User customizable hotkeys

I'm trying to design a Qt GUI application with user customize-able hotkeys. The main issue I'm running into is how to synchronize the hotkeys across the application since a particular hotkey (for example, copy) may be used by multiple widgets/components.
My current strategy is to use a reference class which holds a list of QKeySequence objects for each different hotkey. Each widget would have to have a way to reference this master list and have custom implementations of low-level the keyPressEvent which would compare inputted keys vs. the hotkeys. I don't particularly like this strategy, though, as it requires significant re-implimentation in each widget and feels like I'm trying to re-invent the wheel.
I also tried using QAction objects which can hold QKeySequence shortcuts internally, then use these to trigger higher-level events which I can handle using slots & signals. However, the main issue I have here is how to manage which slots signals get routed to.
For example, say I have 2 open widgets which can both receive a copy action signal. I can connect a slot for both of these to the same signal and take advantage of the single update point for shortcuts, but then things get messy since only the active widget should act on the copy signal, not both widgets. I can re-implement the focusOutEvent and focusInEvent handlers to connect/disconnect slots manually, but this also seems to run into the same issue above where I'm trying to re-invent the wheel and doing more work than is necessary.
Is there an easier way around this problem?
I don't think there is a particularly easy/non-tedious solution to this problem, but when I needed to add user-customizable hotkeys to my application, here is how I did it:
1) Start with your application that has hard-coded key shortcuts, e.g. code like this:
QMenu * editMenu = new QMenu;
QAction * copyItem = menu->addAction(tr("Copy"), this, SLOT(CopyData()));
copyItem->setShortcut(tr("Ctrl+C"));
2) Create a GetKeySequence() function that looks something like this:
static QHash<QString, QKeySequence> _usersKeyPreferences;
static bool _usersKeyPreferencesLoaded = false;
QKeySequence GetKeySequence(const QString & keySequence, const QString & contextStr)
{
if (_usersKeyPreferencesLoaded == false)
{
// Oops, time to load in the user's saved custom-key settings from a file somewhere
_usersKeyPreferences = LoadUsersKeyPreferencesFromFile();
_usersKeyPreferencesLoaded = true; // so we'll only try to load the file once
}
if (_usersKeyPreferences.contains(contextStr))
{
return _usersKeyPreferences[contextStr];
}
else
{
// No user preference specified? Okay, fall back to using the
// hard-coded default key sequence instead.
return QKeySequence(qApp->translate(contextStr, keySequence));
}
}
3) Now the tedious part: grovel over all of your code, and anywhere you've specified a key-sequence explicitly (like in the third line of the code shown for step 1), wrap it with a call to GetKeySequence(), like this:
copyItem->setShortcut(GetKeySequence(tr("Ctrl+C"), tr("Edit_Menu|Copy")));
4) At this point, your program's key-sequences will be customizable; just make sure that the key-settings-file is present on disk before GUI-creation code runs. Here's an excerpt from my program's key-mappings file (which I store as a simple ASCII text file):
Edit_Menu|Copy = Ctrl+C
Edit_Menu|Cut = Ctrl+X
Edit_Menu|Paste = Ctrl+V
[... and so on for all other menu items, etc...]
... of course one downside to this approach is that once the GUI is created, the key-bindings can't be modified "on the fly" (at least, not without a lot of additional coding). My program gets around this simply by closing and then re-creating all windows after the user clicks "Save and Apply" in the Edit Key Bindings dialog.
5) An optional further step (which is some extra work up front but saves time in the long run) is to write a program (or script) that greps all the .cpp files in your program's codebase looking for calls GetKeySequence() in the code. When it finds a GetKeySequence() call, it parses out the two arguments to the call and prints them as a line in a key-bindings file with the default settings. This is useful because you can make this script part of your autobuild, and thereafter you'll never have to remember to manually update the default key-settings-file whenever you add a new menu item (or other key-sequence specifier) to your program.
This worked well for me, anyway. The advantage is that you don't have to refactor your existing program at all; you can just go through it inserting GetKeySequence() as necessary while leaving the larger logic/structure of the program intact.