I am driving myself crazy trying use variables in another function in the same file:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
QLineEdit * street1BetSize = new QLineEdit("0"); // want to use these QLineEdit's
QLineEdit * street2BetSize = new QLineEdit("0");
QLineEdit * street3BetSize = new QLineEdit("0");
QLineEdit * street4BetSize = new QLineEdit("0");
QLineEdit * street5BetSize = new QLineEdit("0");
}
want to use thos variables here:
void MainWindow::runButtonClicked()
{
QVector<card> vDealt = cardDeck.deal_rand_cards(vDeck,3);
//qDebug()<<vStreetBets[0];
streetBetsList << street1BetSize << street2BetSize << street3BetSize << street4BetSize << street5BetSize;
QVector<int> vStreetBets;
for(int i=0;i<5;i++)
{
vStreetBets.append(streetBetsList[i]->text().toInt());
qDebug()<<"street bet: "<<vStreetBets[i];
}
}
As it is here, I am getting
warning: C4189:
‘street5BetSize’ : local variable is initialized but not referenced
and
error: C2065: 'street5BetSize' : undeclared identifier
for each one.
I tried adding extern QLineEdit * street1BetSize; to mainwindow.h, but this gives me an “unresolved external” error.
If you are going to have five
QLineEdits for eachMainWindow, then you want them to be members of your class. Just add them to your class definition:Now, each
MainWindowobject will have 5 pointers toQLineEdit. These make up part of the state of that object and can be accessed by any of its member functions. Now change your constructor to the following, so that you don’t redefine the names:In fact, you’d be better off using the member initialization list, as you have done for
QMainWindowandui:And now your constructor doesn’t need to do any work.
Now you can refer to
street1BetSizeand friends in the other member functions ofMainWindow. However, it’s always very suspect when you have variables that are numbered, likestreetXBetSize. This seems like a great place for an array or container. Why not try anstd::vector<QLineEdit>, and then you can add and removeQLineEdits as you wish. Your class definition would now have:And your constructor could now simply do: