Visual C++ ListBox manipulation; add a string - c++

Language: Visual C++
I have two classes. TableColumnsItemType has two variables: visibleName, and dataName (both are string).
class ColumnsSortedType is a sorted linked list.
I want to use a function called UpdateListbox to add TableColumnsItemType item to the listBox in my Form1.h (item comes from my linkedList)
public: System::Void UpdateListBox() {
//***********************************************************************
//Purpose: To add items from ColumnsSortedType::list to Form1->ListBox1
//Input: list
//Pre: list is initialized and has data.
//List gets data before Form1 initilize call, or before System::UpdateListBox call
//Output: None.
//Post: listBox is filled with data from list
//*************************************************************************
TableColumnsItemType item;
ColumnsSortedType list;
string str = "This is a sample";
item.SetDataName(str);
item.SetVisibleName();
list.InsertItem(item);
str = "This is also a sample";
item.SetDataName(str);
item.SetVisibleName();
list.InsertItem(item);
list.InsertItem(item);
int length = list.LengthIs();
int pos;
for(pos = 0; pos < length; pos++)
{
list.GetNextItem(item);
str = item.ReturnVisibleName();
//add code to insert item into listbox
this->listBox1.AddString(item); //**Here is my issue!**
}
}
I really don't want to add items to list in this function; but I want to get this function working before I start adding extra arguments to pass item and list around.
I'm having trouble adding an item to ListBox1. What is a member function that would allow me to do this? I know that Visual Basic would be something like listBox1.Items.Add
VS doesn't give me function choices when I add the dot-notation after listBox1, so I'm guessing that my syntax is incorrect. I'm having difficulty finding examples for C++ code manipulation of listboxes.

Related

I'm using qt to design a program and need help because my code is not DRY [duplicate]

I have a gui form, where multiple text boxes are present. I want to put their values inside an array. One way of doing it is by writing something like this
{array element } = ui->text_1->text();
and repeat it for text_2,text_3 upto n.
What I want is to run a loop and replace number portion of text box name in each cycle.
something like this {array element } = ui->text_{This number getting changed }->text();
How can it be done in qt?
There are two ways of doing this.
When you create the UI, instead of using text1, text2, etc. you create an array of QLineEdits (eg. std::vector<QLineEdit>) and then when you want to retrieve their values then simply iterate over this array
Iterate over the children of the container widget. You can get the list of the children using the following (documentation):
QList<QObject *> list = parentWidget->children();
Another option to those listed would be to create an array using an initializer list. Depending on how big the array is (and how often it changes), this might be workable.
QLineEdit* entries[] = { ui->text_0, ui->text_1, ui=>text_2 };
QStringList answers;
for ( int i = 0; i < 3; ++i )
{
answers += entries[i]->text();
}
here is an expanded version of Matyas' solution:
class MyClass : public QWidget
{
QStringList answers;
void FillAnswersList(QObject *base)
{
QLineEdit *lineEdit = qobject_cast<QLineEdit>(base);
if(lineEdit)answers.append(lineEdit->text());
else
{
foreach(QObject *child, base->children())
FillAnswersList(child);
}
}
};
If it is just the number changing, and always incrementing, there is another possible solution using QObject::findChild, which takes a name as a parameter.
QString name_template("text_%1");
QStringList answers;
for(int i = 0; i < MAX_TEXTS; ++i)
{
QLineEdit *edit = ui->findChild<QLineEdit *>(name_template.arg(i));
answers += edit->text();
}

Unity / C#: using lists to store numbers, delete elements

I have been banging my head on a problem related to lists. I am a beginner, so sorry if this is a bit unclear..
My goal is to be able to write numbers from keyboard inputs, that will be displayed in a UI element in Unity.
To do so i decided to use a list, because i was wanting to add control to the display, (for example, to add a "." every 3 digits so that they would be more easily readable, like "3.489.498").
So basically, i store new inputs in this list, then i display this list with a display.text every time there is a new digit as an input.
This works actually very well, but then i wanted to be able to delete the last typed element. So i added a backspace hotkey with a List.Remove().
And this is where the nightmare starts. The thing seems to work when i press "1" and deletes right after, but for some reasons it does not work with 2.
Error message is : "Argument out of range, parameter name: index."
I just can't wrap my head around this problem :(
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
public class BoxCreateNumber : MonoBehaviour {
public Text textDisplayNumber;
public List<int> numberList = new List<int>();
void Start () {
}
void Update () {
CollectingNumberInput ();
}
void CollectingNumberInput(){
if (Input.GetKeyDown(KeyCode.Keypad1)){
numberList.Add (1);
//numberList.Insert (numberList.Count,1);
DisplayNumber ();
} else if (Input.GetKeyDown(KeyCode.Keypad2)) {
numberList.Add (2);
//numberList.Insert (numberList.Count,2);
DisplayNumber ();
} else if (Input.GetKeyDown(KeyCode.Backspace)) {
numberList.Remove(numberList.Count);
DisplayNumber ();
}
}
void DisplayNumber(){
textDisplayNumber.text = "";
for (int i = 0; i <= numberList.Count; i++) {
textDisplayNumber.text += numberList [i];
}
}
}
You just need to read the documentation.
public bool Remove(
T item
)
Parameters
item - The object to remove from the List. The value can be null for reference types.
Instead of passing the function the object to remove, you pass the number of elements in the list. This means that if the list contains element "1" as its only element, then it will work, but only by accident.
Calling RemoveAt(numberList.Count - 1) will do what you want. RemoveAt takes the index of the element to remove, and the indices are 0-based, so the last one is Count-1.
Try this to remove the last element
numberList.RemoveAt(numberList.Count-1);

Dynamic Link List RPG Inventory Program - Help (How do I link to classes ?)

I'm making a class-based inventory system using two classes: one for characters and one for items.
Code by Ryan Newell - NEW14136796 Uclan Student
(Need to put this in so plagarism monitors won't flag me for copying my own work)
Here's what I got so far.
///Code by Ryan Newell - NEW14136796 Runshaw College - Uclan
#include<iostream> //Base C++ required #
#include<string> //Allows input of strings
#include<iomanip> //Base C++ required #
#include <conio.h> //Getchar error workaround
#include <cstdlib> // Provides EXIT_SUCCESS
#include <fstream> // Allows output of txt files
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <utility>
#include <Windows.h>//ConsoleSleep
using namespace std;
class itemspell{
string itemname; //Name ((( what if items are the same name ? make difficult for finding statements ? maybe more char with same name item ?
string itemtype; // Spell/Weapon/Armour/Magic Misc?
string itemact; // What type of action does this item do ?
string itemdesc; // Some random ingame description
itemspell* inext; //The next pointer location
bool isspell; //Is Spell Boolean
bool isweapon; // Weapon
bool isarmour; // So on so forth
bool ismisc; // Misc
bool offensiveitem; //Offensive item
bool defensiveitem; // defensive item
bool passiveitem; // Passive effect
int damage;
int armour;
int magicbonus;
int magicresistance;
int cost;
void item_spellsearch(itemspell* ihead, itemspell* &ipast, itemspell* &icurrent)
{
string search;
if (ihead==NULL)
{
cout<<"There are no items on the list to search"<<endl;
}
else
{
cout<<"Enter the type item you are searching for :"<<endl;
getline(cin,search);
icurrent=ihead; //current pointer goes to -> header
cout<<icurrent<<" "<<search<<" "<<icurrent->itemtype<<endl;
while(icurrent!=NULL && search>icurrent->itemname)
{
cout<<"Item Type:"<<icurrent->itemtype<<" "<<cout<<icurrent->itemname<<endl;
ipast=icurrent; //Past = new current pointer
icurrent=icurrent->inext; //current pointer = next pointer
}
}
}
public:
itemspell()//Building a new item // -- Cannot put byref / by values in here remember, needs to be default constructor for some reason ??
{
cout<<"Enter Item Type: "<<endl;
getline(cin,itemtype);
cout<<"Enter Item Name: "<<endl;
getline(cin,itemname);
cout<<"Enter Item Description: "<<endl;
getline(cin,itemdesc);
cout<<"Enter Item Action :"<<endl;
getline(cin,itemact);
}
~itemspell()//Delete record output
{
cout<<"Item being deleted"<<endl;
Sleep(500);
cout<<"Item deleted"<<endl;
getch();
}
void additemspell(itemspell* &ihead) // Add record code
{
itemspell *icurrent;
itemspell *ipast;
itemspell *newitem;
newitem = new itemspell; // New itemspell
if (ihead == NULL || newitem->itemname<ihead->itemname) //If no header or itemname is null;
{
newitem->inext = ihead;
ihead = newitem;
}
else
{
icurrent= ihead;
while(icurrent !=NULL&&icurrent->itemname<newitem->itemname) // While the current char Does not equal NULL/"Nothing and charcurrent itemname = newitemitemname"
{
ipast=icurrent;
icurrent=icurrent->inext;
}
newitem->inext=icurrent; // Sets the next char to current and the past char to next to add in new record.
ipast->inext=newitem;
}
}
void deleteitemspell(itemspell* &ihead) /// Getting the address of the itemspell not the itemspell itself
{
itemspell *ipast=NULL, *icurrent=NULL;
item_spellsearch(ihead, ipast, icurrent);
if(ihead!=NULL)
if(icurrent==NULL)
{
cout<<"ERROR: No itemspell Found"<<endl;
Sleep(500);
cout<<"returning to menu... press enter"<<endl;
getch();
}
else
{
if (icurrent == ihead)
{
ihead = ihead->inext;
}
else
{
ipast->inext=icurrent->inext; //Resets the pointer and header's back to previous positions....
delete icurrent;// Calls the deletion of the itemspell entry.
cout<<"itemspell found was deleted press enter to confirm"<<endl;
getch();
}
}
}
class character
{
string forename;
string surname;
string nickname;
string race;
string alignment;
string alignment_type;
string character_class;
int Strength; //Strength
int Intelligence; //Magick 2
int Willpower; //Magick 1
int Endurance; //Health
int Agility; //Agility
int StartingWealth; //StartingWealth
character* char_itemp; // Character - Item pointer - Adress location of the characters items
character* char_next; // Next Pointer Value- Points to the location of the next person in the Dynamic Linked List
What I'm trying to do is when I create a new item, I want to be able to give that item to a character to use.
I know somewhere along the lines of I need to create a pointer value in the character class to point to the itemspell class but I am unsure what to do and could do with some help.
Essentially I want to get the character class to point to the item class when the item class is called from the constructor within the item class.
Please, if you can, don't give just code. Rather, please highlight areas where I should change and give suggestion examples. My degree program is strict about plagiarism.
Pseudo Code
When newitemspell created
get input charactername ()
:
if no current itemspell created for that character
add item to
character->charactername
else
add item to next pointer character->charactername
By looking at your code and looking at the descriptor of what you're trying to accomplish, why don't you just create an Inventory class to handle a users items? It should be able to handle 99% of anything you're wanting to do. Let me know if this example is anything like what you're trying to do.
To be completely honest, I have nary a clue what it is exactly you're trying to do in your code. As a previous user mentioned, "linking" two classes is a simple matter of giving the base class a variable of the required class. For example:
#include <vector> //I prefer to use vectors for just about any list of objects.
//It's just more convenient for me.
using std::vector;
class Inventory //A handler for all of your character's stuff.
{
private:
vector<object_class> objs; //To actually store an array of whatever objects
//you need to.
//Just some example functions to make the class useful.
public:
int MAX = -1; //The size limit for the inventory. This can be used as a useful
//statistic in the specific inventory, depending on how it's being
//used. My example shows the value at -1, which, at least for me,
//means that any maximum size checks being done won't bother it
//because I usually have a setting of -1 as being unlimited.
getItem(int slot); //Return item
removeItem(int slot) //Removing items
addItem(object_class object) //Adding items
}
This is just really simple programming from here. All you need to do is create variables with the type of Inventory. Any reference to an object_class is just a generic fill-in for the class type of whatever object you're wanting the Inventory to handle. This will most likely be a base class while you're using derivatives.
class Character //The character class with all kinds of stuff to needs to be handled
{
public:
Inventory items; //A regular inventory bag for items.
Inventory equip; //The items the character is currently using.
Inventory spells; //An alternate use for Inventory to be used as a handler for
//spell lists and other cool stuff.
}
And from here you should be able to understand what exactly is going on. Inventory isn't "linked" to Character. Character has three variables with the type Inventory and the Inventory class itself will handle all of the adding, removing, sorting and retrieving of items in its vector.
Now you can make everything work like so:
int main(int argc, char *argv[])
{
Character player;
Armor shield = new Armor(); //A dummy object
player.items.addItem(shield); //Assuming the Inventory is setup to handle Armor items.
//This will add the shield to the player's inventory.
player.items.MAX = 10; //Setting the maximum capacity of items to 10, obviously.
Armor A = player.items.getItem(0); //returns the piece of armor in the first spot in the vector.
}
I would normally write way more modular code for something like this, such as making Inventory a template class, but I digress. This was just to show you how to attach one class object to another.
I hope this was remotely like what you were searching for. If not, please try rewriting your question a little more specifically.

Why do i get a repeated QStringList?

I am writing a Qt application that deals with scheduling employees. The header data for the main QTableView is a pointer to a QStringList. The headerData() function works correctly, but when i add a string to the list elsewhere, it appends the entire list including the new string to the end of the list.
For example, if i have the list 1,2,3 and i append 4 to it, then iterating through the list based on the pointer gives the result 1,2,3,1,2,3,4. I don't know a better way than using pointers to have multiple classes access the same data. Does anyone know how to fix the repeating list?
Example Code
//function to save a new employee in memory
bool EmployeeViewDialog::saveEmployee(Employee *e)
{
employees->insert(e->name,e);
*employeeNames << e->name;
for (int i = 0; i < employeeNames->length(); i++) {
qDebug() << employeeNames->at(i);
}
QList<QStandardItem*> items;
items << new QStandardItem(e->name);
items << new QStandardItem(e->id);
items << new QStandardItem(e->phone);
items << new QStandardItem(e->email);
model->appendRow(items);
return true;
}
The append was just changed to the << method. It is the employeeNames << e->name; line.
The for loop iterates through the list and does the same thing as what happens in the external class.

How to run a loop using gui object names in qt?

I have a gui form, where multiple text boxes are present. I want to put their values inside an array. One way of doing it is by writing something like this
{array element } = ui->text_1->text();
and repeat it for text_2,text_3 upto n.
What I want is to run a loop and replace number portion of text box name in each cycle.
something like this {array element } = ui->text_{This number getting changed }->text();
How can it be done in qt?
There are two ways of doing this.
When you create the UI, instead of using text1, text2, etc. you create an array of QLineEdits (eg. std::vector<QLineEdit>) and then when you want to retrieve their values then simply iterate over this array
Iterate over the children of the container widget. You can get the list of the children using the following (documentation):
QList<QObject *> list = parentWidget->children();
Another option to those listed would be to create an array using an initializer list. Depending on how big the array is (and how often it changes), this might be workable.
QLineEdit* entries[] = { ui->text_0, ui->text_1, ui=>text_2 };
QStringList answers;
for ( int i = 0; i < 3; ++i )
{
answers += entries[i]->text();
}
here is an expanded version of Matyas' solution:
class MyClass : public QWidget
{
QStringList answers;
void FillAnswersList(QObject *base)
{
QLineEdit *lineEdit = qobject_cast<QLineEdit>(base);
if(lineEdit)answers.append(lineEdit->text());
else
{
foreach(QObject *child, base->children())
FillAnswersList(child);
}
}
};
If it is just the number changing, and always incrementing, there is another possible solution using QObject::findChild, which takes a name as a parameter.
QString name_template("text_%1");
QStringList answers;
for(int i = 0; i < MAX_TEXTS; ++i)
{
QLineEdit *edit = ui->findChild<QLineEdit *>(name_template.arg(i));
answers += edit->text();
}