View Full Version : QLabel ui->name_pc->setText(nam);

13th July 2012, 17:25
Hi All,
Apologies for the simple issue, but this is my first "outing" with Qt, and I haven't written any C code for about 7 years.
Not sure if I have a C problem or a Qt usage problem.

I'm getting the PC netbios name and then wanting to display it on mu ui.
When I use hostname, I get an error relating to incorrect data type. The debugger does show that hostname contains my PC name.
I then (think that I) point a QSting variable to the address of hostname, and only the first character of hostname appears on my ui.

Please can someone spot my deliberate mistake.

Thanks & regards,

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "windows.h"

MainWindow::MainWindow(QWidget *parent) :
ui(new Ui::MainWindow)
WCHAR hostname[12];
QString nam = "";
DWORD len;
len = 12;
hostname[11] = '\0';
nam = (char *)&hostname[0];

delete ui;

14th July 2012, 01:00
You are mixing wide characters (WCHAR) and 8-bit characters (char). Casting the point from WCHAR* to char* does not change the data in the array. So, the name "FRED" appears in the hostname memory as bytes (chars and hex):

F R E D \0
46 00 52 00 45 00 44 00 00 00

if you treat that as an 8-bit char string the best you will get is "F". You need to produce your QString from the WCHAR array: try QString::fromWCharArray().

You may also find that QHostInfo::localHostName() gives you a usable name (though different) for your purpose.