Мы с моим другом в настоящее время пытаемся создать игру на C++ с помощью Qt. Наша текущая проблема заключается в том, что нам нужно получить текст с QGraphicsTextItem
на кнопке mousePressEvent
. В игровом меню можно выбрать, сколько игроков есть, поэтому мы разместили QGraphicsTextItem
в цикле for, чтобы все пользователи могли вводить имена. Из-за цикла for у нас нет имен для каждого объекта текстового элемента, поэтому мы можем хранить имена. Нам удалось сохранить все адреса памяти для объектов, используя QMap
, но мы не знаем, как получить текст этого. Мы даже не знаем, лучший ли это для этого.Извлечь текст из неназванного QGraphicsTextItem
GameInfo.h
class GameInfo {
public:
GameInfo();
int players;
QStringList names = (QStringList() // Default player names. This array should be overwritten by the custom names
<< "Player 1"
<< "Player 2"
<< "Player 3"
<< "Player 4"
<< "Player 5"
<< "Player 6"
<< "Player 7");
QMap<int, QGraphicsTextItem**> textBoxMap; // This is where we store all the addresses
};
Game.cpp
QGraphicsRectItem * overviewBox = new QGraphicsRectItem();
overviewBox->setRect(0, 0, 782, 686);
scene->addItem(overviewBox);
int faceNo = 0;
// Create the player selection section
for(int i = 1; i <= players; i++) { // "players" is defined another place in the code, and is an integer between 1 and 6
Container * selContainer = new Container();
selContainer->Selection(i, faceNo);
selContainer->setPos(50, 70 + 110 * (i - 1));
scene->addItem(selContainer);
Container * ovContainer = new Container(overviewBox);
ovContainer->Overview(i, faceNo);
ovContainer->setPos(0, 0 + 110 * (i - 1));
info->textBoxMap.insert(i, &selContainer->textBox->playerText); // This is where we save the addresses
}
Selection.cpp
extern Game * game;
Container::Container(QGraphicsItem * parent): QGraphicsRectItem(parent) {
}
void Container::Selection(int nPlayers, int sPiceNo, QGraphicsItem *parent) {
QString numName = QString::number(nPlayers);
setRect(0, 0, 672, 110);
this->setPen(Qt::NoPen); // Removes border
int posY = this->rect().height()/2;
QSignalMapper * signalMapper = new QSignalMapper(this);
arrowL = new Arrow(0, posY - 32, 0, this);
piece = new Piece(sPiceNo, 96, posY - 32, 1, 1, this);
arrowR = new Arrow(192, posY - 32, 1, this);
textBox = new TextBox(game->info->names[nPlayers - 1], true, this);
textBox->setPos(288, posY - 32);
lockBtn = new Button("Lock", 96, 32, this);
connect(lockBtn, SIGNAL(clicked()), signalMapper, SLOT(map()));
signalMapper->setMapping(lockBtn, nPlayers);
connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(lock(int)));
lockBtn->setPos(640, posY - 16);
}
void Container::Overview(int ovPlayers, int ovPiceNo, QGraphicsItem * parent) {
// Some code...
}
void Container::lock(int nPlayer) {
qDebug() << game->info->textBoxMap[nPlayer];
qDebug() << game->info->names[nPlayer - 1];
game->info->names[nPlayer - 1] = **game->info->textBoxMap[nPlayer].toPlainText(); // This line causes an error
}
Ошибка, которая возникает из-за последней строки выглядит следующим образом:
error: no match for 'operator=' (operand types are 'QString' and 'QGraphicsTextItem')
game->info->names[nPlayer - 1] = **game->info->textBoxMap[nPlayer];
^
TextBox.cpp
TextBox::TextBox(QString text, bool editable, QGraphicsItem * parent): QGraphicsRectItem(parent) {
this->editable = editable;
// Draw the textbox
setRect(0, 0, 320, 64);
if(!editable) {
this->setPen(Qt::NoPen); // Removes border
}
else if(editable) {
QBrush brush;
brush.setStyle(Qt::SolidPattern);
brush.setColor(QColor(255, 255, 255, 255));
setBrush(brush);
}
// Draw the text
playerText = new QGraphicsTextItem(text, this);
int fontId = QFontDatabase::addApplicationFont(":/fonts/built_titling_bd.ttf");
QString family = QFontDatabase::applicationFontFamilies(fontId).at(0);
QFont built(family, 25);
playerText->setFont(built);
int xPos = 0;
int yPos = rect().height()/2 - playerText->boundingRect().height()/2;
playerText->setPos(xPos,yPos);
}
Вопрос: как получить текст из QGraphicsTextItem
?
Я извиняюсь, если я сжег свои глаза, это не цель этого поста. В любом случае, я попробовал ваше предложение о toPlainText(), но это тоже не сработало. – Dromnes
Это нормально, я редактировал свою первую версию сообщения, немного грубо, может быть;). Не могли бы вы объяснить, как это не сработало? – Nox
Я не думаю, что это было грубо, просто весело :) Когда я попробовал toPlainText(), я получил эту ошибку: запрос для члена 'toPlainText' в '* game-> Game :: info-> GameInfo :: textBoxMap.QMap :: operator [] ((* (const int *) (& nPlayer))) ', который имеет тип указателя' QGraphicsTextItem * '(возможно, вы хотели использовать' -> '?) game-> info-> names [nPlayer - 1] = ** game-> info-> textBoxMap [nPlayer] -> toPlainText(); –
Dromnes