Change Display index of gridview column - silverlight-5.0

we are using Telerik version = 2012.2.725.1050
Here i am face one gridview problem while change DisplayIndex of gridview column
Click on column, after when click on Left button focus and colum is moved perfectly but when we click on Right button colum is moved but focus is not moved focus must be moved. here i am add my sample project code
thanks in advance for your help
<UserControl x:Class="GridTest.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">
<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="50" />
</Grid.RowDefinitions>
<telerik:RadGridView HorizontalAlignment="Left" x:Name="grdFormList" VerticalAlignment="Top" Grid.Column="0" Grid.Row="0" />
<StackPanel Orientation="Horizontal" Grid.Column="0" Grid.Row="1">
<Button Content="Left" Height="23" HorizontalAlignment="Left" Name="btnleft" Width="75" Margin="5,0,0,0" Click="btnleft_Click" />
<Button Content="Right" Height="23" HorizontalAlignment="Left" Name="btnright" Width="75" Margin="5,0,0,0" Click="btnright_Click" />
</StackPanel>
</Grid>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.GridView;
using Telerik.Windows;
using System.ComponentModel;
using System.Globalization;
using System.Threading;
namespace GridTest
{
public partial class MainPage : UserControl
{
public GridViewCellBase ClickedCell { get; set; }
public MainPage()
{
InitializeComponent();
this.grdFormList.AddHandler(GridViewCellBase.MouseLeftButtonDownEvent, new MouseButtonEventHandler(MouseDownOnCell), true);
grdFormList.Columns.Clear();
for (Int32 attributelength = 0; attributelength < 10; attributelength++)
{
GridViewColumn textColumn = new GridViewColumn();
// DataGridTextColumn textColumn = new DataGridTextColumn();
textColumn.Header = string.Format("Column{0}", attributelength + 1);
textColumn.UniqueName = string.Format("Uname{0}", attributelength + 1);
textColumn.MinWidth = 5;
textColumn.Width = 100;
grdFormList.Columns.Add(textColumn);
}
}
private void MouseDownOnCell(object sender, MouseEventArgs args)
{
if (((UIElement)args.OriginalSource).ParentOfType<GridViewCellBase>() != null)
{
var aa = ((GridViewHeaderRow)(((GridViewCellBase)((UIElement)args.OriginalSource).ParentOfType<GridViewCellBase>()).ParentOfType<GridViewHeaderRow>())).Cells;
for (int i = 0; i < aa.Count; i++)
{
((GridViewCellBase)aa[i]).Background = new SolidColorBrush(Colors.Transparent);
}
this.ClickedCell = null;
this.ClickedCell = (GridViewCellBase)((UIElement)args.OriginalSource).ParentOfType<GridViewCellBase>();
LinearGradientBrush brush = new LinearGradientBrush();
brush.StartPoint = new Point(0.5, 0);
brush.EndPoint = new Point(0.5, 1);
GradientStop g1 = new GradientStop();
g1.Color = Color.FromArgb(255, 227, 153, 54);
brush.GradientStops.Add(g1);
GradientStop g2 = new GradientStop();
g2.Color = Color.FromArgb(255, 254, 211, 125);
brush.GradientStops.Add(g2);
((GridViewCellBase)((UIElement)args.OriginalSource).ParentOfType<GridViewCellBase>()).Background = brush;
}
}
private void btnleft_Click(object sender, RoutedEventArgs e)
{
if (ClickedCell != null)
{
if (ClickedCell.Column != null)
{
int i = ClickedCell.Column.DisplayIndex;
if (i >= 1)
{
ClickedCell.Column.DisplayIndex = i - 1;
}
}
}
}
private void btnright_Click(object sender, RoutedEventArgs e)
{
if (ClickedCell != null)
{
if (ClickedCell.Column != null)
{
int k = ClickedCell.Column.DisplayIndex;
if (k <= grdFormList.Columns.Count - 1)
{
ClickedCell.Column.DisplayIndex = k + 1;
}
}
}
}
}
}

i am use LayoutUpdated event of gridview and reassign a property and it's working perfect but don't know is this right approach to do it or not
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.GridView;
namespace GridTest
{
public partial class MainPage : UserControl
{
public GridViewCellBase ClickedCell { get; set; }
private GridViewHeaderRow GVHeaderRow { get; set; }
private string CellHeader { get; set; }
public MainPage()
{
InitializeComponent();
this.DataContext = this;
this.grdFormList.AddHandler(GridViewCellBase.MouseLeftButtonDownEvent, new MouseButtonEventHandler(MouseDownOnCell), true);
grdFormList.Columns.Clear();
for (Int32 attributelength = 0; attributelength < 10; attributelength++)
{
GridViewColumn textColumn = new GridViewColumn();
// DataGridTextColumn textColumn = new DataGridTextColumn();
textColumn.Header = string.Format("Column{0}", attributelength + 1);
textColumn.UniqueName = string.Format("Uname{0}", attributelength + 1);
textColumn.MinWidth = 5;
textColumn.Width = 100;
grdFormList.Columns.Add(textColumn);
}
}
private void MouseDownOnCell(object sender, MouseEventArgs args)
{
if (((UIElement)args.OriginalSource).ParentOfType<GridViewCellBase>() != null)
{
var aa = ((GridViewHeaderRow)(((GridViewCellBase)((UIElement)args.OriginalSource).ParentOfType<GridViewCellBase>()).ParentOfType<GridViewHeaderRow>())).Cells;
GVHeaderRow = ((GridViewHeaderRow)(((GridViewCellBase)((UIElement)args.OriginalSource).ParentOfType<GridViewCellBase>()).ParentOfType<GridViewHeaderRow>()));
for (int i = 0; i < aa.Count; i++)
{
((GridViewCellBase)aa[i]).Background = new SolidColorBrush(Colors.Transparent);
}
this.ClickedCell = null;
this.ClickedCell = (GridViewCellBase)((UIElement)args.OriginalSource).ParentOfType<GridViewCellBase>();
CellHeader = ClickedCell.Column.Header.ToString();
LinearGradientBrush brush = new LinearGradientBrush();
brush.StartPoint = new Point(0.5, 0);
brush.EndPoint = new Point(0.5, 1);
GradientStop g1 = new GradientStop();
g1.Color = Color.FromArgb(255, 227, 153, 54);
brush.GradientStops.Add(g1);
GradientStop g2 = new GradientStop();
g2.Color = Color.FromArgb(255, 254, 211, 125);
brush.GradientStops.Add(g2);
((GridViewCellBase)((UIElement)args.OriginalSource).ParentOfType<GridViewCellBase>()).Background = brush;
}
}
private void btnleft_Click(object sender, RoutedEventArgs e)
{
if (ClickedCell != null)
{
if (ClickedCell.Column != null)
{
int i = ClickedCell.Column.DisplayIndex;
if (i >= 1)
{
ClickedCell.Column.DisplayIndex = i - 1;
}
}
}
}
private void btnright_Click(object sender, RoutedEventArgs e)
{
if (ClickedCell != null)
{
if (ClickedCell.Column != null)
{
int k = ClickedCell.Column.DisplayIndex;
if (k < grdFormList.Columns.Count - 1)
{
ClickedCell.Column.DisplayIndex = k + 1;
}
}
}
}
private void grdFormList_LayoutUpdated(object sender, EventArgs e)
{
if (GVHeaderRow != null)
{
var aa = GVHeaderRow.Cells;
for (int i = 0; i < aa.Count; i++)
{
((GridViewCellBase)aa[i]).Background = new SolidColorBrush(Colors.Transparent);
}
////this.ClickedCell = null;
////this.ClickedCell = (GridViewCellBase)((UIElement)args.OriginalSource).ParentOfType<GridViewCellBase>();
LinearGradientBrush brush = new LinearGradientBrush();
brush.StartPoint = new Point(0.5, 0);
brush.EndPoint = new Point(0.5, 1);
GradientStop g1 = new GradientStop();
g1.Color = Color.FromArgb(255, 227, 153, 54);
brush.GradientStops.Add(g1);
GradientStop g2 = new GradientStop();
g2.Color = Color.FromArgb(255, 254, 211, 125);
brush.GradientStops.Add(g2);
ClickedCell = null;
ClickedCell = GVHeaderRow.Cells.Where(a => a.Column.Header.ToString() == CellHeader).ToList()[0];
ClickedCell.Background = brush;
}
}
}
}

Related

SDL: How to render multiple different textures based on mouse event

I'm trying to make a simple menu with 3 different options. Play, Options, Exit.
I want them to change colors when you hover over them and when you mouse up on them. I tried using lazy foo's reference for mouse events, but I'm confused on how to do it with different "buttons". It would be one thing if they were saying all the same thing.
Here is my code:
#include "Menu.h"
#include <iostream>
std::string tmpCap;
SDL_Color tmpColor;
SDL_Color colorW = { 255, 255, 255, 255 };
SDL_Color colorG1 = { 65, 65, 65, 255 };
SDL_Color colorG2 = { 85, 85, 85, 255 };
SDL_Color colorG3 = { 125, 125, 125, 255 };
SDL_Texture* currentPlaySet[3];
SDL_Texture* currentOptionsSet[3];
SDL_Texture* currentExitSet[3];
SDL_Texture* currentPlay;
SDL_Texture* currentOptions;
SDL_Texture* currentExit;
SDL_Texture* currentTexboo[3];
enum mMenuNum
{
PLAY_MOUT = 0,
PLAY_MON = 1,
PLAY_MUP = 2,
OPTIONS_MOUT = 3,
OPTIONS_MON = 4,
OPTIONS_MUP = 5,
EXIT_MOUT = 6,
EXIT_MON = 7,
EXIT_MUP = 8,
MENUNUM_TOTAL = 9
};
enum mCheckButton
{
B_OUT = 0,
B_ON = 1,
B_UP = 2,
B_TOTAL = 3
};
int xCenter = 1024 / 2;
int yCenter = 768 / 2;
SDL_Rect rtmp[3];
SDL_Texture* btmp[9];
class Button
{
public:
//Initializes internal variables
Button();
//Sets top left position
void setPosition( int x, int y );
void setSize(int x, int y, int w, int h);
//Handles mouse event
void handleEvent(SDL_Event* e);
//Shows button sprite
void renderButtons();
private:
//Top left position
SDL_Point mPosition;
SDL_Rect mSize;
//Currently used global sprite
mCheckButton mCurrentSprite;
};
void Menu::init()
{
const char* buttonCaptions[3] = {
" Play ", " Options ", " Exit "
};
for (int i = 0; i < 9; i++)
{
if(i < 3)
{
tmpCap = buttonCaptions[0];
}
if(i < 6 && i > 2)
{
tmpCap = buttonCaptions[1];
}
if(i < 9 && i > 5)
{
tmpCap = buttonCaptions[2];
}
if(i == 0 || i == 3 || i == 6)
{
tmpColor = colorG1;
}
if(i == 1 || i == 4 || i == 7)
{
tmpColor = colorG2;
}
if(i == 2 || i == 5 || i == 8)
{
tmpColor = colorG3;
}
btmp[i] = TextureManager::TextTexture("../src/assets/Arial Black.ttf", tmpCap, 40, tmpColor);
//std::cout << tmpCap << " " << i << std::endl;
}
currentPlaySet[0] = btmp[0];
currentOptionsSet[0] = btmp[3];
currentExitSet[0] = btmp[6];
currentPlaySet[1] = btmp[1];
currentOptionsSet[1] = btmp[4];
currentExitSet[1] = btmp[7];
currentPlaySet[2] = btmp[2];
currentOptionsSet[2] = btmp[5];
currentExitSet[2] = btmp[8];
Menu::getSize();
}
Button::Button()
{
currentPlay = btmp[0];
currentOptions = btmp[3];
currentExit = btmp[6];
mCurrentSprite = B_OUT;
}
Button f[9];
void Button::setPosition(int x, int y)
{
mPosition.x = x;
mPosition.y = y;
}
void Button::setSize(int x, int y, int w, int h)
{
mSize.x = x;
mSize.y = y;
mSize.w = w;
mSize.h = h;
}
void Menu::getSize()
{
SDL_QueryTexture(btmp[0], NULL, NULL, &rtmp[0].w, &rtmp[0].h);
int aX = xCenter - (rtmp[0].w / 2);
int aY = (yCenter - (rtmp[0].h / 2)) - 100;
int aW = rtmp[0].w;
int aH = rtmp[0].h;
f[0].setPosition(aX, aY);
f[0].setSize(aX, aY, aW, aH);
SDL_QueryTexture(btmp[3], NULL, NULL, &rtmp[1].w, &rtmp[1].h);
int bX = xCenter - (rtmp[1].w / 2);
int bY = (yCenter - (rtmp[1].h / 2));
int bW = rtmp[1].w;
int bH = rtmp[1].h;
f[1].setPosition(bX, bY);
f[1].setSize(bX, bY, bW, bH);
SDL_QueryTexture(btmp[6], NULL, NULL, &rtmp[2].w, &rtmp[2].h);
int cX = xCenter - (rtmp[2].w / 2);
int cY = (yCenter - (rtmp[2].h / 2)) + 100;
int cW = rtmp[2].w;
int cH = rtmp[2].h;
f[2].setPosition(cX, cY);
f[2].setSize(cX, cY, cW, cH);
}
void Button::handleEvent(SDL_Event* e)
{
if( e->type == SDL_MOUSEMOTION || e->type == SDL_MOUSEBUTTONDOWN || e->type == SDL_MOUSEBUTTONUP )
{
int x, y;
SDL_GetMouseState(&x, &y);
//Check if mouse is in button
bool inside = true;
//Mouse is left of the button
if( x < mPosition.x )
{
inside = false;
}
//Mouse is right of the button
else if( x > mPosition.x + mSize.w )
{
inside = false;
}
//Mouse above the button
else if( y < mPosition.y )
{
inside = false;
}
//Mouse below the button
else if( y > mPosition.y + mSize.h )
{
inside = false;
}
//Mouse is outside button
if( !inside )
{
std::cout << "Outside " << " " << mCurrentSprite << std::endl;
//currentPlay = currentPlaySet[mCurrentSprite];
//currentOptions = currentOptionsSet[mCurrentSprite];
//currentExit = currentExitSet[mCurrentSprite];
mCurrentSprite = B_OUT;
}
//Mouse is inside button
else
{
switch( Game::event.type )
{
case SDL_MOUSEMOTION:
mCurrentSprite = B_ON;
//currentPlay = btmp[(mCurrentSprite/3)+1];
//currentOptions = btmp[(mCurrentSprite/3)+1];
//currentExit = btmp[(mCurrentSprite/3)+1];
//currentPlay = currentPlaySet[mCurrentSprite];
//currentOptions = currentOptionsSet[mCurrentSprite];
//currentExit = currentExitSet[mCurrentSprite];
std::cout << "In " << mCurrentSprite << std::endl;
break;
case SDL_MOUSEBUTTONDOWN:
//currentPlay = currentPlaySet[mCurrentSprite];
//currentOptions = currentOptionsSet[mCurrentSprite];
//currentExit = currentExitSet[mCurrentSprite];
//mCurrentSprite = B_DOWN;
//currentTex = mTex3;
break;
case SDL_MOUSEBUTTONUP:
//currentPlay = currentPlaySet[mCurrentSprite];
//currentOptions = currentOptionsSet[mCurrentSprite];
//currentExit = currentExitSet[mCurrentSprite];
mCurrentSprite = B_UP;
//currentTex = mTex4;
break;
}
}
}
}
void Button::renderButtons()
{
while( SDL_PollEvent( &Game::event ) != 0 )
{
for( int i = 0; i < 3; ++i )
{
f[i].handleEvent(&Game::event);
//isMouseOverText();
}
}
SDL_RenderCopy(Game::mRenderer, btmp[mCurrentSprite], nullptr, &mSize);
//SDL_RenderCopy(Game::mRenderer, currentOptionsSet[mCurrentSprite], nullptr, &mSize);
//SDL_RenderCopy(Game::mRenderer, currentExitSet[mCurrentSprite], nullptr, &mSize);
}
void Menu::render()
{
for( int i = 0; i < 3; ++i )
{
f[i].renderButtons();
}
}
I was able to figure it out using an old SDL tutorial code from here.
Is it viable to delete and create these textures on interact?
I've updated my code to avoid deleting textures every time at the bottom. Is there a better way to do this? It seems clean to me but I'm concerned about resource usage.
Any insight is appreciated.
My code:
const int NUMMENU = 2;
const char* labels[NUMMENU] = {"Continue","Exit"};
SDL_Texture* menus[NUMMENU];
bool selected[NUMMENU] = {0,0};
SDL_Color color[2] = {{0,0,0,255},{255,0,0,255}};
SDL_Rect pos[NUMMENU];
int x,y;
const char* font = "../assets/Arial Black.ttf";
void MainMenu::init()
{
menus[0] = TextureManager::CreateFontTexture(font, labels[0], 40, color[0]);
menus[1] = TextureManager::CreateFontTexture(font, labels[1], 40, color[0]);
SDL_QueryTexture(menus[0], NULL, NULL, &pos[0].w, &pos[0].h);
SDL_QueryTexture(menus[1], NULL, NULL, &pos[1].w, &pos[1].h);
pos[0].x = (1024/2) - (pos[0].w / 2);
pos[0].y = (768/2) - (pos[0].h / 2) - 100;
pos[1].x = (1024/2) - (pos[1].w / 2);
pos[1].y = (768/2) - (pos[1].h / 2);
}
void MainMenu::render()
{
SDL_RenderCopy(App::appRenderer, menus[0], NULL, &pos[0]);
SDL_RenderCopy(App::appRenderer, menus[1], NULL, &pos[1]);
if( App::event.type == SDL_MOUSEMOTION || App::event.type == SDL_MOUSEBUTTONDOWN || App::event.type == SDL_MOUSEBUTTONUP )
{
switch(App::event.type)
{
case SDL_MOUSEMOTION:
x = App::event.motion.x;
y = App::event.motion.y;
for(int i = 0; i < NUMMENU; i += 1) {
if(x>=pos[i].x && x<=pos[i].x+pos[i].w && y>=pos[i].y && y<=pos[i].y+pos[i].h)
{
if(!selected[i])
{
selected[i] = 1;
SDL_DestroyTexture(menus[i]);
menus[i] = TextureManager::CreateFontTexture(font, labels[i], 40, color[1]);
}
}
else
{
if(selected[i])
{
selected[i] = 0;
SDL_DestroyTexture(menus[i]);
menus[i] = TextureManager::CreateFontTexture(font, labels[i], 40, color[0]);
}
}
}
break;
case SDL_MOUSEBUTTONDOWN:
x = App::event.button.x;
y = App::event.button.y;
for(int i = 0; i < NUMMENU; i += 1) {
if(x>=pos[i].x && x<=pos[i].x+pos[i].w && y>=pos[i].y && y<=pos[i].y+pos[i].h)
{
SDL_DestroyTexture(menus[0]);
SDL_DestroyTexture(menus[1]);
}
}
break;
}
}
}
UPDATED code without deleting textures every time:
const int NUMMENU = 3;
const char* labels[NUMMENU] = {"New Game", "Options","Exit"};
SDL_Texture* menus[NUMMENU];
SDL_Texture* selectedMenus[NUMMENU];
SDL_Texture* toRender[NUMMENU];
bool selected[NUMMENU] = {0,0};
SDL_Color color[2] = {{0,0,0,255},{125,125,125,255}};
SDL_Rect pos[NUMMENU];
int x,y;
const char* font = "../assets/Arial Black.ttf";
int aOne = 0;
void MainMenu::init()
{
for(int i = 0; i < NUMMENU; i++)
{
menus[i] = TextureManager::CreateFontTexture(font, labels[i], 40, color[0]);
toRender[i] = menus[i];
selectedMenus[i] = TextureManager::CreateFontTexture(font, labels[i], 40, color[1]);
SDL_QueryTexture(menus[i], NULL, NULL, &pos[i].w, &pos[i].h);
}
pos[0].x = (1024/2) - (pos[0].w / 2);
pos[0].y = (768/2) - (pos[0].h / 2) - 100;
pos[1].x = (1024/2) - (pos[1].w / 2);
pos[1].y = (768/2) - (pos[1].h / 2);
pos[2].x = (1024/2) - (pos[2].w / 2);
pos[2].y = (768/2) - (pos[2].h / 2) + 100;
}
void MainMenu::inputD()
{
aOne++;
std::cout << aOne << std::endl;
switch(App::event.type)
{
case SDL_MOUSEMOTION:
x = App::event.motion.x;
y = App::event.motion.y;
for(int i = 0; i < NUMMENU; i += 1)
{
if(x>=pos[i].x && x<=pos[i].x+pos[i].w && y>=pos[i].y && y<=pos[i].y+pos[i].h)
{
if(!selected[i])
{
selected[i] = 1;
toRender[i] = selectedMenus[i];
}
}
else
{
if(selected[i])
{
selected[i] = 0;
toRender[i] = menus[i];
}
}
}
break;
case SDL_MOUSEBUTTONDOWN:
x = App::event.button.x;
y = App::event.button.y;
for(int i = 0; i < NUMMENU; i += 1)
{
if(x>=pos[i].x && x<=pos[i].x+pos[i].w && y>=pos[i].y && y<=pos[i].y+pos[i].h)
{
std::cout << labels[i] << " button clicked" << std::endl;
}
}
break;
}
}
void MainMenu::render()
{
for(int i = 0; i < NUMMENU; i++)
SDL_RenderCopy(App::appRenderer, toRender[i], NULL, &pos[i]);
}

Call another widget application on QPushButton

I want call another widget application calculator on pushbutton. Till this time I get success but it overlap on parent widget.
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QWidget>
class QLineEdit;
class QComboBox;
class calculator;
namespace Ui {
class MainWindow;
}
class MainWindow : public QWidget
{
Q_OBJECT
public:MainWindow();
public slots:
void calcButtonPressed();
private:
calculator *calc;
};
#endif // MAINWINDOW_H
and mainwindow.cpp
MainWindow::MainWindow(){
....
QPushButton *calcButton = new QPushButton(tr("Calc"));
connect(calcButton,SIGNAL(clicked(bool)),this,SLOT(calcButtonPressed()));
....
}
void MainWindow::calcButtonPressed(){
calc = new calculator(this);
calc->show();
}
calculator.cpp
#include<QtWidgets>
#include<cmath>
#include "button.h"
#include "calculator.h"
calculator::calculator(QWidget *parent): QWidget(parent)
{
sumInMemory=0.0;
sumSoFar=0.0;
factorSoFar=0.0;
waitingForOperand=true;
display=new QLineEdit("0");
display->setReadOnly(true);
display->setAlignment(Qt::AlignRight);
display->setMaxLength(15);
QFont font=display->font();
font.setPointSize(font.pointSize()+8);
display->setFont(font);
for (int i = 0; i < NumDigitButton; ++i) {
digitButton[i] = createButton(QString::number(i), SLOT(digitClicked()));
}
button *pointButton =createButton(tr("."),SLOT(pointClicked()));
button *changeSignButton=createButton(tr("\30\261"),SLOT(changeSignClicked()));
button *backspaceButton=createButton(tr("Backspace"),SLOT(backspaceClicked()));
button *clearButton=createButton(tr("Clear"),SLOT(clear()));
button *clearAllButton=createButton(tr("Clear All"),SLOT(clearAll));
button *clearMemoryButton=createButton(tr("MC"),SLOT(clearMemory()));
button *readMemoryButton=createButton(tr("MR"),SLOT(readMemory()));
button *setMemoryButton=createButton(tr("MS"),SLOT(setMemory()));
button *addToMemoryButton=createButton(tr("M+"),SLOT(addToMemory()));
button *divisionButton = createButton(tr("\303\267"), SLOT(multiplicativeOperatorClicked()));
button *timesButton = createButton(tr("\303\227"), SLOT(multiplicativeOperatorClicked()));
button *minusButton = createButton(tr("-"), SLOT(additiveOperatorClicked()));
button *plusButton = createButton(tr("+"), SLOT(additiveOperatorClicked()));
button *squareRootButton = createButton(tr("Sqrt"), SLOT(unaryOperatorClicked()));
button *powerButton = createButton(tr("x\302\262"), SLOT(unaryOperatorClicked()));
button *reciprocalButton = createButton(tr("1/x"), SLOT(unaryOperatorClicked()));
button *equalButton = createButton(tr("="), SLOT(equalClicked()));
QGridLayout *mainLayout = new QGridLayout;
mainLayout->setSizeConstraint(QLayout::SetFixedSize);
mainLayout->addWidget(display, 0, 0, 1, 6);
mainLayout->addWidget(backspaceButton, 1, 0, 1, 2);
mainLayout->addWidget(clearButton, 1, 2, 1, 2);
mainLayout->addWidget(clearAllButton, 1, 4, 1, 2);
mainLayout->addWidget(clearMemoryButton, 2, 0);
mainLayout->addWidget(readMemoryButton, 3, 0);
mainLayout->addWidget(setMemoryButton, 4, 0);
mainLayout->addWidget(addToMemoryButton, 5, 0);
for (int i = 1; i < NumDigitButton; ++i) {
int row = ((9 - i) / 3) + 2;
int column = ((i - 1) % 3) + 1;
mainLayout->addWidget(digitButton[i], row, column);
}
mainLayout->addWidget(digitButton[0], 5, 1);
mainLayout->addWidget(pointButton, 5, 2);
mainLayout->addWidget(changeSignButton, 5, 3);
mainLayout->addWidget(divisionButton, 2, 4);
mainLayout->addWidget(timesButton, 3, 4);
mainLayout->addWidget(minusButton, 4, 4);
mainLayout->addWidget(plusButton, 5, 4);
mainLayout->addWidget(squareRootButton, 2, 5);
mainLayout->addWidget(powerButton, 3, 5);
mainLayout->addWidget(reciprocalButton, 4, 5);
mainLayout->addWidget(equalButton, 5, 5);
setLayout(mainLayout);
setWindowTitle(tr("calculator"));
}
void calculator::digitClicked()
{
button *clickedButton = qobject_cast<button *>(sender());
int digitValue = clickedButton->text().toInt();
if (display->text() == "0" && digitValue == 0.0)
return;
if (waitingForOperand) {
display->clear();
waitingForOperand = false;
}
display->setText(display->text() + QString::number(digitValue));
}
void calculator::unaryOperatorClicked()
{
button *clickedButton = qobject_cast<button *>(sender());
QString clickedOperator = clickedButton->text();
double operand = display->text().toDouble();
double result = 0.0;
if (clickedOperator == tr("Sqrt")) {
if (operand < 0.0) {
abortOperation();
return;
}
result = std::sqrt(operand);
} else if (clickedOperator == tr("x\302\262")) {
result = std::pow(operand, 2.0);
} else if (clickedOperator == tr("1/x")) {
if (operand == 0.0) {
abortOperation();
return;
}
result = 1.0 / operand;
}
display->setText(QString::number(result));
waitingForOperand = true;
}
void calculator::additiveOperatorClicked()
{
button *clickedButton = qobject_cast<button *>(sender());
QString clickedOperator = clickedButton->text();
double operand = display->text().toDouble();
if (!pendingMultiplicativeOperator.isEmpty()) {
if (!calculate(operand, pendingMultiplicativeOperator)) {
abortOperation();
return;
}
display->setText(QString::number(factorSoFar));
operand = factorSoFar;
factorSoFar = 0.0;
pendingMultiplicativeOperator.clear();
}
if (!pendingAdditiveOperator.isEmpty()) {
if (!calculate(operand, pendingAdditiveOperator)) {
abortOperation();
return;
}
display->setText(QString::number(sumSoFar));
} else {
sumSoFar = operand;
}
pendingAdditiveOperator = clickedOperator;
waitingForOperand = true;
}
void calculator::multiplicativeOperatorClicked()
{
button *clickedButton = qobject_cast<button *>(sender());
QString clickedOperator = clickedButton->text();
double operand = display->text().toDouble();
if (!pendingMultiplicativeOperator.isEmpty()) {
if (!calculate(operand, pendingMultiplicativeOperator)) {
abortOperation();
return;
}
display->setText(QString::number(factorSoFar));
} else {
factorSoFar = operand;
}
pendingMultiplicativeOperator = clickedOperator;
waitingForOperand = true;
}
void calculator::equalClicked()
{
double operand = display->text().toDouble();
if (!pendingMultiplicativeOperator.isEmpty()) {
if (!calculate(operand, pendingMultiplicativeOperator)) {
abortOperation();
return;
}
operand = factorSoFar;
factorSoFar = 0.0;
pendingMultiplicativeOperator.clear();
}
if (!pendingAdditiveOperator.isEmpty()) {
if (!calculate(operand, pendingAdditiveOperator)) {
abortOperation();
return;
}
pendingAdditiveOperator.clear();
} else {
sumSoFar = operand;
}
display->setText(QString::number(sumSoFar));
sumSoFar = 0.0;
waitingForOperand = true;
}
void calculator::pointClicked()
{
if (waitingForOperand)
display->setText("0");
if (!display->text().contains('.'))
display->setText(display->text() + tr("."));
waitingForOperand = false;
}
void calculator::changeSignClicked()
{
QString text = display->text();
double value = text.toDouble();
if (value > 0.0) {
text.prepend(tr("-"));
} else if (value < 0.0) {
text.remove(0, 1);
}
display->setText(text);
}
void calculator::backspaceClicked()
{
if (waitingForOperand)
return;
QString text = display->text();
text.chop(1);
if (text.isEmpty()) {
text = "0";
waitingForOperand = true;
}
display->setText(text);
}
void calculator::clear()
{
display->setText("0");
waitingForOperand = true;
}
void calculator::clearAll()
{
sumSoFar = 0.0;
factorSoFar = 0.0;
pendingAdditiveOperator.clear();
pendingMultiplicativeOperator.clear();
display->setText("0");
waitingForOperand = true;
}
void calculator::clearMemory()
{
sumInMemory = 0.0;
}
void calculator::readMemory()
{
display->setText(QString::number(sumInMemory));
waitingForOperand = true;
}
void calculator::setMemory()
{
equalClicked();
sumInMemory = display->text().toDouble();
}
void calculator::addToMemory()
{
equalClicked();
sumInMemory += display->text().toDouble();
}
button *calculator::createButton(const QString &text, const char *member)
{
button *button1 = new button(text);
connect(button1, SIGNAL(clicked()), this, member);
return button1;
}
void calculator::abortOperation()
{
clearAll();
display->setText(tr("####"));
}
bool calculator::calculate(double rightOperand, const QString &pendingOperator)
{
if (pendingOperator == tr("+")) {
sumSoFar += rightOperand;
} else if (pendingOperator == tr("-")) {
sumSoFar -= rightOperand;
} else if (pendingOperator == tr("\303\227")) {
factorSoFar *= rightOperand;
} else if (pendingOperator == tr("\303\267")) {
if (rightOperand == 0.0)
return false;
factorSoFar /= rightOperand;
}
return true;
}
I get output as calculator overlaps on mainwindow widget.
Can I get separate window for calculator?
You must change calc = new calculator(this) to calc = new calculator().
From Qt documentation
QWidget::QWidget ( QWidget * parent = 0, Qt::WindowFlags f = 0 )
Constructs a widget which is a child of parent, with widget flags set
to f.
If parent is 0, the new widget becomes a window. If parent is another
widget, this widget becomes a child window inside parent. The new
widget is deleted when its parent is deleted.
Do not supply parent when constructing calculator, then it would become separate top-level window

SDL2 'Bullet' movement not working?

I am attempting to make a simple scrolling shooter game with SDL2. I have a moving player on a screen, and I am trying to make the player shoot a bullet using an array (so they can shoot multiple bullets) however, when I press the space bar, nothing happens, and instead the bullet image sort of flashes in the top left corner.
Heres the same code in codepad: http://codepad.org/rOhE1AqY
#include <SDL.h>
#include <stdio.h> //use for things like printf, same as cout
#include <iostream>
#include <string>
#include <time.h>
using namespace std;
//screend dimensions& sprtie dimensions
const int SCREEN_HEIGHT = 600;
const int SCREEN_WIDTH = 400;
const int SPRITE_WIDTH = 60;
const int SPRITE_HEIGHT = 80;
const int MAX_BULLETS = 50;
SDL_Window* Window = NULL;//the window rendering to
SDL_Surface* ScreenSurface = NULL;//surface contained by window
SDL_Surface* Background = NULL;
SDL_Surface* Player = NULL;
SDL_Surface* Enemy = NULL;
SDL_Surface* Bullet = NULL;
SDL_Surface* newBullet = NULL;
SDL_Rect posPlayer, posEnemy, posBullet, posnewBullet;
const Uint8* keystate = SDL_GetKeyboardState(NULL);
SDL_Event event;
class thePlayer
{
public:
thePlayer();
void player_movement();
void show_player();
private:
};
class theBullet
{
public:
theBullet();
bool isActive;
int x_position;
int y_position;
void bullet_movement();
void add_new_bullet();
void show_bullet();
private:
};
theBullet arrayofBullets[MAX_BULLETS];
class theEnemy
{
public:
theEnemy();
void enemy_movement();
void show_enemy();
private:
};
thePlayer::thePlayer()
{
posPlayer.x = 170;
posPlayer.y = SCREEN_HEIGHT;
posPlayer.w = 20;
posPlayer.h = 30;
}
void thePlayer::player_movement()
{
if(keystate[SDL_SCANCODE_LEFT])
{
posPlayer.x -= 2;
}
if(keystate[SDL_SCANCODE_RIGHT])
{
posPlayer.x += 2;
}
if(keystate[SDL_SCANCODE_UP])
{
posPlayer.y -= 2;
}
if(keystate[SDL_SCANCODE_DOWN])
{
posPlayer.y += 2;
}
if ((posPlayer.x + SPRITE_WIDTH) > SCREEN_WIDTH)
{
posPlayer.x = (SCREEN_WIDTH - SPRITE_WIDTH);
}
if ((posPlayer.y + SPRITE_HEIGHT) > SCREEN_HEIGHT)
{
posPlayer.y = (SCREEN_HEIGHT - SPRITE_HEIGHT);
}
}
void thePlayer::show_player()
{
SDL_BlitSurface(Player, NULL, ScreenSurface, &posPlayer);
SDL_SetColorKey(Player, SDL_TRUE, SDL_MapRGB(Player->format, 255, 255, 255));
}
theBullet::theBullet()
{
/*posBullet.x;
posBullet.y;
posBullet.w = 10;
posBullet.h = 15;*/
}
void theBullet::bullet_movement()
{
/*if(keystate[SDL_SCANCODE_SPACE])
{
posBullet.x = posPlayer.x + 25;
posBullet.y = posPlayer.y + 10;
}
posBullet.y -= 2;
if(posBullet.y < 0)
{
posBullet.y = -50;
}*/
}
void theBullet::show_bullet()
{
//SDL_BlitSurface(Bullet, NULL, ScreenSurface, &posBullet);
//SDL_SetColorKey(Bullet, SDL_TRUE, SDL_MapRGB(Player->format, 255, 255, 255));//removes white background
}
theEnemy::theEnemy()
{
srand (time(NULL));
posEnemy.x = rand() % 300 + 50;
posEnemy.y =0;
posEnemy.w = 35;
posEnemy.h = 60;
}
void theEnemy::enemy_movement()
{
posEnemy.y += 1;
if(posEnemy.y > SCREEN_HEIGHT)
{
posEnemy.y = SCREEN_HEIGHT +50;
}
}
void theEnemy::show_enemy()
{
SDL_BlitSurface(Enemy, NULL, ScreenSurface, &posEnemy);
SDL_SetColorKey(Enemy, SDL_TRUE, SDL_MapRGB(Player->format, 255, 255, 255));
}
bool initialise()
{
bool success = true;
if (SDL_Init(SDL_INIT_EVERYTHING) !=0)
{
cout<<"SDL_Init Error."<<SDL_GetError()<<endl;
success = false;
}
else
{
//create the window for game
Window = SDL_CreateWindow("Scrolling Shooter Game", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
if (Window == NULL)
{
cout<<"Window Error"<<SDL_GetError()<<endl;
success = false;
}
else
{
//get window surface
ScreenSurface = SDL_GetWindowSurface(Window);
}
}
return success;
}
bool LoadingMedia()
{
bool success = true;
Background = SDL_LoadBMP("background.bmp");
if (Background == NULL)
{
cout<<"Error in loading background."<<SDL_GetError()<<endl;
success = false;
}
Player = SDL_LoadBMP("spaceship.bmp");
if (Player == NULL)
{
cout<<"Error in loading player."<<SDL_GetError()<<endl;
success = false;
}
Enemy = SDL_LoadBMP("enemy.bmp");
if (Enemy == NULL)
{
cout<<"Error in loading enemy."<<SDL_GetError()<<endl;
success = false;
}
Bullet = SDL_LoadBMP("bullet.bmp");
if (Bullet == NULL)
{
cout<<"Error in loading bullet."<<SDL_GetError()<<endl;
success = false;
}
return success;
}
void closedown()
{
SDL_FreeSurface(Background);
Background = NULL;
SDL_FreeSurface(Player);
Player = NULL;
SDL_FreeSurface(Enemy);
Enemy = NULL;
SDL_DestroyWindow(Window);
Window = NULL;
SDL_Quit();
}
int main(int argc, char** argv)
{
bool quit = false;
thePlayer myPlayer;
theEnemy myEnemy;
theBullet myBullet;
if (!initialise())
{
cout<<"Failed to initialise"<<SDL_GetError()<<endl;
}
else
{
if (!LoadingMedia())
{
cout<<"Error loading media"<<SDL_GetError()<<endl;
}
}
//makes all bullets false
for (int i=0; i<MAX_BULLETS; i++)
{
arrayofBullets[i].isActive = false;
}
//GAME LOOP
while (quit == false)
{
SDL_BlitSurface(Background, NULL, ScreenSurface, NULL);
myPlayer.show_player();
myPlayer.player_movement();
while (SDL_PollEvent(&event))
{
if( event.type == SDL_QUIT )
{
quit = true;
break;
}
if(keystate[SDL_SCANCODE_SPACE])
{
for (int i=0; i<MAX_BULLETS; i++)
{
if (arrayofBullets[i].isActive == false)
{
arrayofBullets[i].x_position = posPlayer.x + 25;
arrayofBullets[i].y_position = posPlayer.y + 10;
arrayofBullets[i].isActive = true;
break;
}
}
}
//update game objects
for (int i=0; i<MAX_BULLETS; i++)
{
if (arrayofBullets[i].isActive == true)
{
arrayofBullets[i].y_position -= 2;
if (arrayofBullets[i].y_position < 0)
{
arrayofBullets[i].isActive = false;
}
}
}
for (int i=0; i<MAX_BULLETS; i++)
{
if (arrayofBullets[i].isActive == true)
{
SDL_BlitSurface(Bullet, NULL, ScreenSurface, NULL);
}
}
}
//myPlayer.show_player();
//myBullet.show_bullet();
//myEnemy.show_enemy();
//myPlayer.player_movement();
//myBullet.bullet_movement();
//myEnemy.enemy_movement();
SDL_UpdateWindowSurface(Window); //updates screen
}
closedown();
return 0;
}
SDL_BlitSurface(Bullet, NULL, ScreenSurface, NULL);
You haven't specified destination rect, so it will blit on left-top corner.
It should be
SDL_Rect dstrect;
dstrect.x = arrayofBullets[i].x_position;
dstrect.y = arrayofBullets[i].y_position;
dstrect.w = Bullet->w;
dstrect.h = Bullet->h;
SDL_BlitSurface(Bullet, NULL, ScreenSurface, &dstrect);

Vala/Clutter texture loading with thread

I am trying to load image files in vala/clutter while running a timeout animation, using "image.set_load_async" stops the animation for a while when the file loads are requested. This is the source:
// valac --thread --pkg clutter-1.0 --pkg=gio-2.0 test_1.vala -o test_1
using Clutter;
class SlideImage : Clutter.Actor {
protected Texture image = new Texture ();
public int loaded = 0;
public SlideImage (string file) {
try {
loaded = 1;
image.set_load_async (true);
image.load_finished.connect((t, a) => {
loaded = 2;
this.add_actor (image);
});
image.set_from_file (file);
} catch (Error e) {
warning("Error setting SlideImageReflected gradient : %s", e.message);
}
}
}
class ClutterSlideShow {
protected Stage stage;
protected int width = 800;
protected int height =700;
protected string[] file_names = {};
private int file_pointer = 0;
private int counter = 0;
private SlideImage showA = null;
private SlideImage showB = null;
private SlideImage showC = null;
private SlideImage showD = null;
private SlideImage showE = null;
public ClutterSlideShow (string folder) {
try {
var directory = File.new_for_path (folder);
var enumerator = directory.enumerate_children (FileAttribute.STANDARD_NAME,0);
FileInfo file_info;
while ((file_info = enumerator.next_file ()) != null) {
file_names += folder+"/"+file_info.get_name ();
}
} catch (Error e) {
stderr.printf ("Error ClutterSlideShow listing files: %s\n", e.message);
}
stage = Stage.get_default ();
stage.hide.connect (Clutter.main_quit);
stage.color = Color () { red = 0, green = 0, blue = 0, alpha = 255 };;
stage.set_size (width, height);
stage.show_all ();
}
protected string get_next_file () {
file_pointer++;
if (file_pointer > file_names.length) file_pointer = 1;
return file_names[file_pointer-1];
}
public void start () {
Timeout.add (15, run);
}
private bool run () {
if (showA == null) {
showA = new SlideImage (get_next_file ());
showA.set_x (0);
showA.set_y (0);
} else if (showA.loaded == 2) {
stage.add_actor (showA);
showA.loaded = 3;
} else if (showA.loaded == 3) {
showA.set_y (showA.get_y () + 1);
counter++;
if (counter==100) {
showB = new SlideImage (get_next_file ());
showB.set_x (100);
showB.set_y (0);
stage.add_actor (showB);
showC = new SlideImage (get_next_file ());
showC.set_x (200);
showC.set_y (0);
stage.add_actor (showC);
showD = new SlideImage (get_next_file ());
showD.set_x (300);
showD.set_y (0);
stage.add_actor (showD);
showE = new SlideImage (get_next_file ());
showE.set_x (400);
showE.set_y (0);
stage.add_actor (showE);
}
}
return true;
}
}
int main (string[] args) {
if (Thread.supported () == false) {
stderr.printf ("Threads are not supported!\n");
return -1;
}
var result = init (ref args);
if (result != Clutter.InitError.SUCCESS) {
stderr.printf("Error: %s\n", result.to_string());
return 1;
}
var slide_show = new ClutterSlideShow ("/usr/share/backgrounds/");
slide_show.start ();
Clutter.main ();
return 0;
}
I have also tried to use "threads" but I get a "Segmentation fault (core dumped)" that I don't know how to debug or fix. This is the example:
// valac --thread --pkg clutter-1.0 --pkg=gio-2.0 test_2.vala -o test_2
using Clutter;
class SlideImage : Clutter.Actor {
protected Texture image = new Texture ();
public int loaded = 0;
public SlideImage (string file) {
loaded = 1;
load_image_in_background.begin(file, (obj, res) => {
try {
loaded = 2;
this.add_actor (image);
} catch (ThreadError e) {
string msg = e.message;
stderr.printf(#"Thread error: $msg\n");
}
});
}
async void load_image_in_background (string file) throws ThreadError {
SourceFunc callback = load_image_in_background.callback;
ThreadFunc<void*> run = () => {
try {
// Help ! The next line results in "Segmentation fault"
image.set_from_file (file);
} catch (Error e) {
warning("Error setting SlideImage texture : %s", e.message);
}
Idle.add((owned) callback);
return null;
};
Thread.create<void*>(run, false);
yield;
}
}
class ClutterSlideShow {
protected Stage stage;
protected int width = 800;
protected int height =700;
protected string[] file_names = {};
private int file_pointer = 0;
private int counter = 0;
private SlideImage showA = null;
private SlideImage showB = null;
private SlideImage showC = null;
private SlideImage showD = null;
private SlideImage showE = null;
public ClutterSlideShow (string folder) {
try {
var directory = File.new_for_path (folder);
var enumerator = directory.enumerate_children (FileAttribute.STANDARD_NAME,0);
FileInfo file_info;
while ((file_info = enumerator.next_file ()) != null) {
file_names += folder+"/"+file_info.get_name ();
}
} catch (Error e) {
stderr.printf ("Error ClutterSlideShow listing files: %s\n", e.message);
}
stage = Stage.get_default ();
stage.hide.connect (Clutter.main_quit);
stage.color = Color () { red = 0, green = 0, blue = 0, alpha = 255 };;
stage.set_size (width, height);
stage.show_all ();
}
protected string get_next_file () {
file_pointer++;
if (file_pointer > file_names.length) file_pointer = 1;
return file_names[file_pointer-1];
}
public void start () {
Timeout.add (15, run);
}
private bool run () {
if (showA == null) {
showA = new SlideImage (get_next_file ());
showA.set_x (0);
showA.set_y (0);
} else if (showA.loaded == 2) {
stage.add_actor (showA);
showA.loaded = 3;
} else if (showA.loaded == 3) {
showA.set_y (showA.get_y () + 1);
counter++;
if (counter==100) {
showB = new SlideImage (get_next_file ());
showB.set_x (100);
showB.set_y (0);
stage.add_actor (showB);
showC = new SlideImage (get_next_file ());
showC.set_x (200);
showC.set_y (0);
stage.add_actor (showC);
showD = new SlideImage (get_next_file ());
showD.set_x (300);
showD.set_y (0);
stage.add_actor (showD);
showE = new SlideImage (get_next_file ());
showE.set_x (400);
showE.set_y (0);
stage.add_actor (showE);
}
}
return true;
}
}
int main (string[] args) {
if (Thread.supported () == false) {
stderr.printf ("Threads are not supported!\n");
return -1;
}
var result = init (ref args);
if (result != Clutter.InitError.SUCCESS) {
stderr.printf("Error: %s\n", result.to_string());
return 1;
}
var slide_show = new ClutterSlideShow ("/usr/share/backgrounds/");
slide_show.start ();
Clutter.main ();
return 0;
}
The execution "stop" is produced due two reasons:
The file load (can be threaded)
The image/actor creation (can't be threaded but improved)
I received help from an expert (thanks Victor), the next code improves it with:
Threads the file load
Scales the image to its final "clutter" size
This is the code:
/**
* Build with:
* valac --thread --pkg clutter-1.0 --pkg gio-2.0 --pkg gdk-3.0 --target-glib=2.32 test_2.vala -o test_2
*/
const string SLIDESHOW_PATH = "/usr/share/backgrounds";
public class SlideImage : Clutter.Actor {
public bool ready { get; private set; default = false; }
private Clutter.Image image;
private Thread thread;
public SlideImage (File file, int width, int height) {
load_image_async.begin (file, width, height, (obj, res) => {
if (image == null)
return;
set_size (width, height);
set_content_scaling_filters (Clutter.ScalingFilter.TRILINEAR,
Clutter.ScalingFilter.LINEAR);
set_content_gravity (Clutter.ContentGravity.CENTER);
set_content (image);
ready = true;
});
}
private async void load_image_async (File file, int width, int height) {
var pixbuf = yield load_pixbuf_from_file_async (file);
if (pixbuf != null) {
image = new Clutter.Image ();
try {
float relation_w = pixbuf.get_width () / width;
float relation_h = pixbuf.get_height () / height;
float offset_x = 0.0f;
float offset_y = 0.0f;
float scale = 1.0f;
if (relation_w > relation_h) {
scale = (float) height / (float) pixbuf.get_height ();
if (pixbuf.get_width () > width)
offset_x = -((float) ((pixbuf.get_width () * scale) - width)) / 2.0f;
} else {
scale = (float) width / (float) pixbuf.get_width ();
if (pixbuf.get_height () > height)
offset_y = -((float) ((pixbuf.get_height () * scale) - height)) / 2.0f;
}
var pixbuf_scaled = new Gdk.Pixbuf (pixbuf.get_colorspace (),
pixbuf.get_has_alpha (),
pixbuf.get_bits_per_sample (),
width,
height);
pixbuf.scale (pixbuf_scaled, 0, 0, width, height, offset_x, offset_y, scale, scale, Gdk.InterpType.BILINEAR);
image.set_data (pixbuf_scaled.get_pixels (),
pixbuf_scaled.get_has_alpha () ? Cogl.PixelFormat.RGBA_8888 : Cogl.PixelFormat.RGB_888,
pixbuf_scaled.get_width (),
pixbuf_scaled.get_height (),
pixbuf_scaled.get_rowstride ());
} catch (Error err) {
warning ("Could not set image from pixbuf: %s", err.message);
image = null;
}
}
}
private async Gdk.Pixbuf? load_pixbuf_from_file_async (File file) {
SourceFunc callback = load_pixbuf_from_file_async.callback;
Gdk.Pixbuf? pixbuf = null;
ThreadFunc<void*> thread_func = () => {
try {
pixbuf = new Gdk.Pixbuf.from_file (file.get_path ());
message ("loaded pixbuf");
} catch (Error e) {
warning ("Error loading pixbuf: %s", e.message);
}
Idle.add ((owned) callback);
return null;
};
thread = new Thread<void*> ("load-pixbuf-in-background", thread_func);
yield;
return pixbuf;
}
}
public class ClutterSlideShow {
private const int WIDTH = 800;
private const int HEIGHT = 600;
private int counter = 0;
private List<File> files;
private Clutter.Stage stage;
private SlideImage showA;
private SlideImage showB;
private SlideImage showC;
private SlideImage showD;
private SlideImage showE;
public ClutterSlideShow (string folder) {
load_files (File.new_for_path (folder));
init_stage ();
}
public void start () {
Timeout.add (15, run);
}
protected File? get_next_file () {
var file = files.nth_data (0);
if (file != null)
files.remove (file);
return file;
}
private void load_files (File directory) {
files = new List<File> ();
try {
var enumerator = directory.enumerate_children (FileAttribute.STANDARD_NAME,0);
FileInfo file_info;
while ((file_info = enumerator.next_file ()) != null) {
var child_file = directory.get_child (file_info.get_name ());
files.prepend (child_file);
}
} catch (Error e) {
warning (e.message);
}
}
private void init_stage () {
stage = new Clutter.Stage ();
stage.background_color = Clutter.Color () { red = 0, green = 0, blue = 0, alpha = 255 };
stage.set_size (WIDTH, HEIGHT);
stage.show ();
stage.hide.connect (Clutter.main_quit);
}
private bool run () {
if (showA == null) {
showA = new SlideImage (get_next_file (), 400, 400);
showA.x = 0;
showA.y = 0;
} else if (showA.get_parent () != stage) {
stage.add_child (showA);
} else if (showA.ready) {
showA.set_y (showA.get_y () + 1);
counter++;
if (counter == 50) {
showB = new SlideImage (get_next_file (), 400, 400);
showB.set_x (100);
showB.set_y (0);
stage.add_child (showB);
showC = new SlideImage (get_next_file (), 400, 400);
showC.set_x (200);
showC.set_y (0);
stage.add_child (showC);
showD = new SlideImage (get_next_file (), 400, 400);
showD.set_x (300);
showD.set_y (0);
stage.add_child (showD);
showE = new SlideImage (get_next_file (), 400, 400);
showE.set_x (400);
showE.set_y (0);
stage.add_child (showE);
}
}
return true;
}
}
void main (string[] args) {
var result = Clutter.init (ref args);
if (result != Clutter.InitError.SUCCESS)
error ("Failed to init clutter: %s", result.to_string ());
var slide_show = new ClutterSlideShow (SLIDESHOW_PATH);
slide_show.start ();
Clutter.main ();
}

Form Glass Pane in LWUIT

I'm trying to make a waiting screen using Form Glass Pane in LWUIT, the following is the code that I'm using
public class LoadingGlassPane implements Painter {
public static boolean isShown = false;
public static IForm form;
public void paint(Graphics g, Rectangle rect) {
System.out.println("paint LoadingGlassPane");
Font font = g.getFont();
int color = g.getColor();
g.setColor(0);
g.setFont(Font.getDefaultFont());
g.drawString("Loading...", 20, 120);
g.setColor(color);
g.setFont(font);
}
public void installPane(IForm f) {
f.setGlassPane(this);
}
public void uninstallPane(IForm f) {
f.setGlassPane(null);
}
public static IForm getForm() {
return form;
}
public static void setForm(IForm form) {
LoadingGlassPane.form = form;
}
public static boolean isIsShown() {
return isShown;
}
public static void setIsShown(boolean isShown) {
LoadingGlassPane.isShown = isShown;
}
}
and
public class ProgressGlassPane extends LoadingGlassPane implements Animation, Runnable {
int spacing = 20;
int fontSpacing = 10;
String loadMsg = "Loading...";
//HTMLComponent htmlC;
// Dialog loading;
// public ProgressGlassPane(Dialog loading) {
// this.loading = loading;
// }
public ProgressGlassPane() {
}
public void paint(Graphics g, Rectangle rect) {
//while (isShown == true) {
System.out.println("paint ProgressGlassPane");
int color = g.getColor();
Font font = g.getFont();
int pos = (int) ((System.currentTimeMillis() % 2700) / 300);
Font f = Font.getDefaultFont();
//int startX = loading.getAbsoluteX() + (loading.getWidth() / 2) - spacing;
int startX = (LGB.width / 2) - spacing;
//int fontStartX = loading.getAbsoluteX() + (loading.getWidth() - f.stringWidth(loadMsg)) / 2;
int fontStartX = (LGB.width - f.stringWidth(loadMsg)) / 2;
//int startY = loading.getAbsoluteY() + (loading.getHeight() / 2) - spacing - (f.getHeight() + fontSpacing) / 2;
int startY = (LGB.height / 2) - spacing - (f.getHeight() + fontSpacing) / 2;
int i = 0;
g.setColor(0xffffff);
g.fillRect(Math.min(startX - 3, fontStartX), startY - 3, Math.max(spacing * 2 + 7, f.stringWidth(loadMsg)) + 1, spacing * 2 + 7 + f.getHeight() + fontSpacing);
g.setColor(0);
g.setFont(f);
g.drawString(loadMsg, fontStartX, startY);
startY += f.getHeight() + fontSpacing;
for (int y = 0; y < 3; y++) {
for (int x = 0; x < 3; x++) {
int thickness = 3;
if (i == pos) {
thickness = 7;
} else if (i == pos - 1) {
thickness = 5;
}
g.fillRect(startX + x * spacing - (thickness / 2), startY + y * spacing - (thickness / 2), thickness, thickness);
i++;
}
}
g.setColor(color);
g.setFont(font);
// }
}
public boolean animate() {
return true;
}
public void paint(Graphics g) {
paint(g, null);
}
//void installPane(Form f) {
public void installPane(IForm f) {
super.installPane(f);
//f.setGlassPane(this);
f.registerAnimated(this);
}
//void uninstallPane(Form f) {
public void uninstallPane(IForm f) {
super.uninstallPane(f);
//f.setGlassPane(this);
f.deregisterAnimated(this);
}
public void run() {
System.out.println("I'm running");
if (isShown == true && form != null) {
installPane(form);
}
else
{
uninstallPane(form);
}
}
}
and from within my form
public static ProgressGlassPane progressPane;
progressPane = new ProgressGlassPane();
progressPane.setForm(this);
progressPane.setIsShown(true);
progressPane.run();
//Some Webservice code I want to run
progressPane.setIsShown(false);
What I want to do exactly is to open the glass pan while I'm loading my data and hide it when I finish, but what Happen it send the request and after get the response show the glass pane , I have tried to put my glass pane in different thread to run independently from the main thread, and it is also not working.
Is the webservice code blocking?
If you are on the EDT then that just wouldn't work. You need to uninstall from the completion.