QString string/text formatting - qt

I am trying to format a QString using the arg() function as follows:
QColor color = QColorDialog::getColor(Qt::blue, this);
....
QString tStr = QString("R: %1 G: %2 B: %3").arg( color.red(), color.green(), color.blue());
Here I get a 'integer division by zero exception'.
Background: using Qt add-in in VS 2010. Brand new to Qt framework.
Any suggestions?
Thanks

You should change that line to
QString tStr = QString("R: %1 G: %2 B: %3")
.arg(color.red()).arg(color.green()).arg(color.blue());
I can only assume that your code is mapping to this overload of arg()
QString QString::arg(int a, int fieldWidth = 0, int base = 10,
const QChar & fillChar = QLatin1Char( ' ' )) const
I'm surprised that it is resulting in a division by zero error because nobody performs division without checking for 0 first or catching the exception :) Anyway, I ran a test here of your code on Qt 4.7.4 / Windows 7 / MinGW without an error, just the wrong result string.

Related

OpenCL Kernel code compile error - Visual Studio 2019

I'm kind of new to OpenCL programming and am trying to run a simple vector addition code in VS 2019. However, I can't get the .cl code to compile. It's showing these 6 errors when trying to build the program:
Error C2144 syntax error: 'void' should be preceded by ';'
Error C4430 missing type specifier - int assumed. Note: C++ does not support default-int
Error C2065 '__global': undeclared identifier
Error C2146 syntax error: missing ')' before identifier 'float4'
Error C2143 syntax error: missing ';' before '{'
Error C2447 '{': missing function header (old-style formal list?)
This is my kernel code:
__kernel void add_numbers(__global float4* data,
__local float* local_result, __global float* group_result) {
float sum;
float4 input1, input2, sum_vector;
uint global_addr, local_addr;
global_addr = get_global_id(0) * 2;
input1 = data[global_addr];
input2 = data[global_addr + 1];
sum_vector = input1 + input2;
local_addr = get_local_id(0);
local_result[local_addr] = sum_vector.s0 + sum_vector.s1 +
sum_vector.s2 + sum_vector.s3;
barrier(CLK_LOCAL_MEM_FENCE);
if (get_local_id(0) == 0) {
sum = 0.0f;
for (int i = 0; i < get_local_size(0); i++) {
sum += local_result[i];
}
group_result[get_group_id(0)] = sum;
}
}
I have added the include and lib directories and linked them properly. I couldn't find many fixes for this error after googling. Please help me out...
UPDATE : I fixed it
Hello everyone,
I found the solution to this problem. I removed the .cl file from VS projects and then re-added it (optional). I also changed file open option to have "rb" instead of "r" ( fopen(filename,"rb") ). Now I'm able to run it!
Your issue was that the C++ compiler wanted to compile the OpenCL code. You can exclude the file from the VS project and read it with fstream at runtime to get the kernel code string, or you can embed the kernel code string right into the executable via stringification macro:
#include <string>
#define R(...) string(" "#__VA_ARGS__" ")
string get_opencl_code() { return R(
// put your OpenCL C code here
);}

String ^ MyString = gcnew String("abcd");

I was reading the c++'s foreach syntax on MSDN:
// for_each_string1.cpp
// compile with: /ZW
#include <stdio.h>
using namespace Platform;
ref struct MyClass {
property String^ MyStringProperty;
};
int main() {
String^ MyString = ref new String("abcd");
for each ( char c in MyString )
wprintf("%c", c);
wprintf("/n");
MyClass^ x = ref new MyClass();
x->MyStringProperty = "Testing";
for each( char c in x->MyStringProperty )
wprintf("%c", c);
}
I tried to find what the "^" means on google but I couldn't find anything (or my query wasn't correct)
What does it mean? Is it as a "*"? Is it as a "&"?
This syntax also applies to C#. Do they mean the same thing in both languages?
Piece of C# code:
using namespace System;
int main(){
array<int>^ arr = gcnew array<int>{0,1,2,5,7,8,11};
int even=0, odd=0;
for each (int i in arr) {
if (i%2 == 0)
even++;
else
odd++;
}
Console::WriteLine(“Found {0} Odd Numbers, and {1} Even Numbers.”,
odd, even);
}
The "^" denotes a managed reference, which is used for managed types. It's like a pointer, but for managed types. The syntax doesn't exist in C#. In C#, the equivalent is just a variable of a reference type (as opposed to a value type), or a boxed value type.
As others have said, this is C++/CLI syntax which means you have to compile with the /clr option. C++/CLI is basically C++ with features of C# (or more generally, .NET).
https://learn.microsoft.com/en-us/cpp/extensions/handle-to-object-operator-hat-cpp-component-extensions?view=vs-2019 hope this link can help you.
btw,^ is a special character and ignored by google search engine so you can not search that.

force call to QString(const char *) constructor in Qt 4.7

I am trying to compile a library written in Qt 4.6. On my current Linux machine I have only Qt 4.7 installed. The following code part:
/*file try.h*/
void fileOpen(QString s = NULL) ;
/*file try.cpp*/
void MainWindow::fileOpen(QString s) {
QString filename ;
if(s.isNull()) filename = QFileDialog::getOpenFileName(
this,
"Choose a file",
".",
"Source file (*.)");
else filename = s ;
}
compiles with the following error (I used cmake but the corresponding line code is the one listed above):
In member function ‘virtual int MainWindow::qt_metacall(QMetaObject::Call, int,
void**)’:
/homes/combi/hodorog/Developments/axelOld/build/axel/src/QGui/moc_MainWindow.cxx:141:26:
error: conversion from ‘long int’ to ‘QString’ is ambiguous
/homes/combi/hodorog/Developments/axelOld/build/axel/src/QGui/moc_MainWindow.cxx:141:26:
note: candidates are:
/usr/include/QtCore/qstring.h:426:43: note: QString::QString(const char*)
/usr/include/QtCore/qstring.h:105:14: note: QString::QString(const QChar*)
So I am guessing the problem is that in qt. 4.7. there are two QString constructors that can take a pointer as an argument (as listed in the compilation error), whereas in qt 4.6. there is only one QString constructor that can take a pointer as an argument. How can I force QString to call the constructor with const char * as an argument?
Thank a lot for your help in advance,
madalina
void fileOpen(QString s = NULL);
You are trying to construct a QString object with 0. It seems you are confusing the null of pointers with a null QString. A null QString is one which is created with the constructor QString(). Given how your function is implemented (referring to s.isNull()), you should change the function declaration to
void fileOpen(QString s = QString());

How to append this in Qt?

I want to add a new line in this. This is my sample code:
ui->button->setText(" Tips " + "\n" + TipsCount );
This is the error it shows:
invalid operands of types 'const char [7]' and 'const char [2]' to binary 'operator+'
But when I add to label it gets appended!
ui->label->setText(name + "\n" + City );
Can someone please help me?
This is a very common problem in C++ (in general, not just QT).
Thanks to the magic of operator overloading, name + "\n" gets turned into a method call (couldn't say which one since you don't list the type). In other words, because one of the two things is an object with + overloaded it works.
However when you try to do "abc" + "de", it blows up. The reason is because the compiler attempts to add two arrays together. It doesn't understand that you mean concatenation, and tries to treat it as an arithmetic operation.
To correct this, wrap your string literals in the appropriate string object type (std::string or QString most likely).
Here is a little case study:
QString h = "Hello"; // works
QString w = "World"; // works too, of course
QString a = h + "World"; // works
QString b = "Hello" + w; // also works
QString c = "Hello" + "World"; // does not work
String literals in C++ (text in quotes) are not objects and don't have methods...just like numeric values aren't objects. To make a string start acting "object-like" it has to get wrapped up into an object. QString is one of those wrapping objects, as is the std::string in C++.
Yet the behavior you see in a and b show we're somehow able to add a string literal to an object. That comes from the fact that Qt has defined global operator overloads for both the case where the left operand is a QString with the right a const char*:
http://doc.qt.nokia.com/latest/qstring.html#operator-2b-24
...as well as the other case where the left is a const char* and the right is a QString:
http://doc.qt.nokia.com/latest/qstring.html#operator-2b-27
If those did not exist then you would have had to write:
QString a = h + QString("World");
QString b = QString("Hello") + w;
You could still do that if you want. In that case what you'll cause to run will be the addition overload for both operands as QString:
http://doc.qt.nokia.com/latest/qstring.html#operator-2b-24
But if even that didn't exist, you'd have to call a member function. For instance, append():
http://doc.qt.nokia.com/latest/qstring.html#append
In fact, you might notice that there's no overload for appending an integer to a string. (There's one for a char, however.) So if your TipsCount is an integer, you'll have to find some way of turning it into a QString. The static number() methods are one way.
http://doc.qt.nokia.com/latest/qstring.html#number
So you might find you need:
ui->button->setText(QString(" Tips ") + "\n" + QString::number(TipsCount));

Appending number to QString with arg() , is there better ways?

I've been using QString::number () to convert numbers to string for long time , now i'm wondering if there's something better than following:
int i = 0;
QString msg = QString ("Loading %1").arg (QString::number (i));
How can i spare QString::number () ? i checked document , seems only "%1" is applicable , no other stuff like "%d" could work
QString's arg() function does indeed implement many different types and automatically detect what you provide it. Providing multiple parameters to a single arg() call like so
// Outputs "one two three"
QString s = QString("%1 %2 %3").arg("one", "two", "three")
is only implemented for QString (and hence const char*) parameters.
However, you can chain arg calls together and still use the numbering system:
int i = 5;
size_t ui = 6;
int j = 12;
// Outputs "int 5 size_t 6 int 12"
qDebug() << QString("int %1 size_t %2 int%3").arg(i).arg(ui).arg(j);
// Also outputs "int 5 size_t 6 int 12"
qDebug() << QString("int %1 int %3 size_t %2").arg(i).arg(j).arg(ui);
You can directly use arg() like this
int i = 0;
QString msg = QString ("Loading %1").arg(i);
Qt will automatically convert it for you
Take a look at QString documentation. You have plenty of ::arg method overloads, that take different types. QString doesn't need to know what type will be under %n, method replacing that %n will know it and put proper value.

Resources