-1
,当我有一个项目,其中我试图单击时将图像添加到QLabel将图片添加到一个QLabel。我阅读了一些关于如何制作可点击QLabel的文章,但添加图片似乎很棘手。任何方式做到这一点?点击
编辑1-
我想提出一个简单的井字游戏QT。所以我做了9个QLabels的网格布局。我想在单击时将图像添加到相应的QLabel(O或X)。 我做了一个2D阵列来检查获胜状态。 这里是mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
//QPixmap imageO("C:/Users/user/Documents/tictactoe/o.png");
//QPixmap imageX("C:/Users/user/Documents/tictactoe/x.png");
char a[3][3],turn_player='O';
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
int i,j;
ui->setupUi(this);
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
a[i][j]='-';
}
centralWidget = new QWidget(this);
ui->setupUi(this);
windowstart();
this->setCentralWidget(centralWidget);
grid = new QGridLayout(centralWidget);
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
labels[i][j]= new ClickableLabel("",this);
grid->addWidget(labels[i][j], i+1, j);
labels[i][j]->setAlignment(Qt::AlignCenter);
looks(i,j);
}
}
play();
}
void MainWindow::windowstart()
{
setWindowTitle("TIC-TAC-TOE");
setFixedSize(500,500);
QPixmap bkgnd("C:/Users/user/Documents/tictactoe/background.jpg");
bkgnd = bkgnd.scaled(this->size(), Qt::IgnoreAspectRatio);
QPalette palette;
palette.setBrush(QPalette::Background, bkgnd);
this->setPalette(palette);
}
void MainWindow::looks(int i,int j)
{
labels[i][j]->setStyleSheet("QLabel { background-color: #000000; color: white; font:20pt; font-weight:500; border-radius: 10px;}");
}
void MainWindow::play()
{
//int count=0;
for(; ;)
{
move_Player('O');
count++;
if(woncheck('O')==true)
{
QMessageBox::information(this,tr("Game Over"),tr("Player A(O) won."));
break;
}
if(count==9)
{
QMessageBox::information(this,tr("Game Over"),tr("Player A(O) won."));
break;
}
move_Player('X');
count++;
if(woncheck('X')==true)
{
QMessageBox::information(this,tr("Game Over"),tr("Player B(X) won."));
break;
}
}
}
void MainWindow::move_Player(char ch)
{
if(ch=='O')
//set picture of O
else
//set picture of X
}
bool MainWindow::woncheck (char test)
{
int i,j,counter1,counter2,counter3,counter4;
for(i=0;i<3;i+=1)
{
counter1=0;counter2=0;counter3=0,counter4=0;
for(j=0;j<3;j+=1)
{
if(a[i][j]==test)
counter1++;
if(a[j][i]==test)
counter2++;
if(a[j][j]==test)
counter3++;
if(a[j][4-j]==test)
counter4++;
}
if(counter1==3||counter2==3||counter3==3||counter4==3)
return true;
}
return false;
}
MainWindow::~MainWindow()
{
delete ui;
}
的代码我有一个类ClickableLabel为好,这从QLabel继承并发射所点击的信号,仅此而已。当QLabel被点击到ClickableLabel类中时,我还想添加添加图像的函数,但无法确定如何实际执行此操作。
我与呼叫使用下面的回答,但你的问题是短暂的详细信息。什么似乎是棘手的呢? – goug