[Solved] How to read sysfs entries from qt and put it into qprogressbar?



  • Hi,
    I have a small application in which I need to get the sysfs (say example '/sys/class/power_supply/modelgauge_battery/capacity') details and put that one into QProgressbar.
    Since, sysfs entries are treated as files under linux, I have tried with accessing the sysfs entries using QFile.
    i.e. QFile file("/sys/class/power_supply/modelgauge_battery/capacity");
    Now, I want to read the value of the file and that value I need to pass into QProgressbar's value as below
    progressBar->setValue(<value_read_from_file>)

    I tried some experiments, but nothing yield to the desired result. Could anyone can help me to figure out how to achieve this.
    PS: the value which I need in this case is integer (setValue( ) accepts integer).

    Looking forward to your reply.
    Thank you in advance,
    Ajith P V


  • Moderators

    Can you post your code?
    What is the content of /sys/class/power_supply/modelgauge_battery/capacity?
    Reading from a file is as simple as file.readAll() and converting the QByteArray to what ever you need.
    If the content of the file is an integer number then you can do: file.readAll().toInt()



  • @jsulm Thank you for your reply.
    /sys/class/power_supply/modelgauge_battery/capacity shows the battery percentage in number when we run it from a console (terminal) with cat command. I would like to know whether I can take the 'sysfs' entries like how I'm doing.
    Please see my code snippet below (I'm using Qt Creator):

    QFile file("/sys/class/power_supply/modelgauge_battery/capacity");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    return;
    QDataStream in(&file);
    int battery_value;
    in >> battery_value;
    ui->progressBar->setValue(battery_value);

    I also tried file.readAll( ).toInt( ) earlier but the Progressbar shown 0 always (meaning not taking or invalid value I guess) in all cases.


  • Moderators

    Well, there is probably a new-line at the end of the file content, try this:
    file.readAll( ).trimmed().toInt( );



  • @jsulm said:

    file.readAll( ).trimmed().toInt( );

    Wow! just wow! It got solved :)


  • Moderators

    Nice to hear that it works now :-)


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.