PDA

View Full Version : Creating Pushbutton dynamically using xml



Narthan
2nd July 2015, 10:57
Hi all am new to Qt and i want to create a push buttons dynamically using xml without hard coding , i searched in internet, but i didnt get anything related to this.,
what all the things i have to read for this or if you have any example program for this please give it,
Thank you

d_stranz
2nd July 2015, 18:27
You need to give a little more detail. "Create push buttons dynamically using XML" Where? In a dialog, a widget, floating in space in front of your monitor? When? At the time your program starts up, or any time while your program is running? How? From XML in a file? XML generated on the fly?

Since you've done your searching, your must have come across the fact that Qt's own Qt Designer creates XML files (.ui) that the MOC compiler parses to create C++ code that creates the UI dynamically during program startup. You probably also came across the fact that Qt's QML and QtQuick also create UIs dynamically during program execution using a UI description contained in a javascript .qml file.

You could use either of those tools. Or do you want to invent your own wheel?

Narthan
3rd July 2015, 07:15
Thank you.,
I need to load Xml file to Qmainwindow using parsing like QXmlStreamReader , based on xml file, dynamically i need to generate pushbuttons in mainwindow and name name to that push buttons without hard coding at the start of execution

For example

<Dorms>
<Dorm ID="0" Name="Dorm Building 0">
<Room ID="0" Name="Room 0"/>
<Room ID="1" Name="Room 1"/>
<Room ID="2" Name="Room 2"/>
</Dorm>
</Dorms>

above is the xml file , i need to read this file and i want to dynamically create a Qpushbutton and for that pushbuttons it is dynamically named as Name of the room, like room 0 room 1,

d_stranz
4th July 2015, 00:54
I would use QDomDocumentfor this instead of QXmlStreamReader.

In your MainWindow constructor, create a simple QWidget instance and set it as the central widget. Add a layout of whatever type you want (grid, horizontal box, vertical box) depending on how you want the buttons laid out. If there are a lot of buttons, then you might want to use a QScrollArea as the central widget, and put the QWidget and layout inside that.

Read the XML into the QDomDocument (QDomDocument::setContent()), then use QDomDocument::elementsByTagName() to get a list of all of the "Room" nodes. Go through the list of room nodes, retrieve the ID and Name for each one. Create a QPushButton with the room name and insert it into the layout. Connect the button's clicked() signal to whatever slot you want to execute when the button is clicked. You can connect them all to the same slot, bcause you can use the sender() method to determine which button invoked the slot.