Thank you to see:When Dialog has hide, the QPixmap is empty,why???
and This way is too inefficient...help me
、、、
#include "webKitDialog.h"
#include "ui_webKitDialog.h"
#include <QWebEngineView>
#include <QWebEnginePage>
#include "HiWebEnginePage.h"
#include <QTimer>
#include <QThread>
#include <QScreen>
#include <QGuiApplication>
#include <QPixmap>
webKitDialog::webKitDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::webKitDialog)
{
ui->setupUi(this);
m_view = new QWebEngineView(this);
m_page = new HiWebEnginePage(m_view);
m_view->setPage(m_page);
ui->lineEdit->setText("http://www.youku.com");
ui->verticalLayout->addWidget(m_view, 1);
on_lineEdit_editingFinished();
QTimer *time = new QTimer;
connect(time, &QTimer::timeout, this, &webKitDialog::onTimeOut);
//
time->start(1000);
}
webKitDialog::~webKitDialog()
{
delete ui;
}
void webKitDialog::showEvent(QShowEvent *event)
{
m_view->reload();
m_view->show();
QDialog::showEvent(event);
}
void webKitDialog::onTimeOut()
{
emit onImageUpdate(createThumbnail(m_view->size()));
}
void webKitDialog::on_pushButton_close_clicked()
{
this->hide();
m_view->showNormal();
}
void webKitDialog::on_pushButton_max_clicked()
{
qreal factor = m_view->zoomFactor();
factor += 0.25;
if(factor > 5)
{
factor = 5;
}
m_page->setZoomFactor(factor);
}
void webKitDialog::on_pushButton_refresh_clicked()
{
m_view->reload();
}
void webKitDialog::on_lineEdit_editingFinished()
{
QString strUrl = ui->lineEdit->text();
m_page->load(QUrl(strUrl));
}
void webKitDialog::on_pushButton_zoonout_clicked()
{
qreal factor = m_view->zoomFactor();
factor -= 0.25;
if(factor < 0.25)
{
factor = 0.25;
}
m_page->setZoomFactor(factor);
}
QPixmap webKitDialog::createThumbnail(const QSize &size)
{
QPixmap pixMap(size);
qDebug() << "size" << size << endl;
QRegion rg(0, 0, size.width(), size.height());
QPainter painter(&pixMap);
m_view->page()->view()->render(&painter, QPoint(), rg);
painter.end();
return pixMap;
}
、、、
Related
Why isn't my code working??? What does this error mean? FYI: I wanted to create a top down shooter game. all my code was basically just copied from different sources(some I just solved on my own).
I intended to put the player class in the game loop or game class. here's the code:
game.cpp
#include "Player.h"
//Private Functions
void game::intVariables()
{
this->window = nullptr;
this->points = 0;
this->enemySpawnTimerMax = 1000.f;
this->enemySpawnTimer = this->enemySpawnTimerMax;
this->maxEnemies = 8;
}
void game::intWindow()
{
this->videoMode.height = 1080;
this->videoMode.width = 1780;
this->window = new sf::RenderWindow(this->videoMode, "Top Down Shooter", sf::Style::Close | sf::Style::Titlebar);
this->window->setFramerateLimit(60);
this->window->setKeyRepeatEnabled(true);
Player player("player.png");
}
void game::intEnemies()
{
this->enemy.setPosition(30.f, 30.f);
this->enemy.setSize(sf::Vector2f(50.f, 50.f));
this->enemy.setFillColor(sf::Color(0, 128, 128));
this->enemy.setOutlineColor(sf::Color::Black);
this->enemy.setOutlineThickness(-4.f);
}
//Constructors or Destructors
game::game()
{
this->intVariables();
this->intWindow();
this->intEnemies();
}
//prevents memory leak
game::~game()
{
delete this->window;
}
//Accessors
const bool game::running() const
{
return this->window->isOpen();
}
//functions
void game::player1()
{
player.drawPlayer(*this->window);
}
void game::spawnEnemy()
{
/*
#return void
Spawns enemies and sets their color and positions.
- select random position
- select random color
- add enemy to vector
*/
this->enemy.setPosition(
static_cast<float>(rand() % static_cast<int>(this->window->getSize().x - this->enemy.getSize().x)),
static_cast<float>(rand() % static_cast<int>(this->window->getSize().y - this->enemy.getSize().y))
);
this->enemy.setFillColor(sf::Color(0, 128, 128));
//spawns the enemy
this->enemies.push_back(this->enemy);
}
void game::pollEvents()
{
//event polling
while (this->window->pollEvent(this->evnt))
{
switch (this->evnt.type)
{
case sf::Event::Closed:
this->window->close();
break;
case sf::Event::KeyPressed:
if (this->evnt.key.code == sf::Keyboard::Escape)
this->window->close();
break;
}
}
}
void game::updateEnemies()
{
/*
#return void
updates the enemy spawn timer and spawns enemies
when the total amount of enemies is smaller than the maximum.
removes the enemies at the edge of the screen. //to do
*/
//Updating the timer for enemy spawning
if (this->enemies.size() < this->maxEnemies)
{
if (this->enemySpawnTimer >= this->enemySpawnTimerMax)
{
//spawn the enemy and reset the timer
this->spawnEnemy();
this->enemySpawnTimer = 0.f;
}
else
this->enemySpawnTimer += 1.f;
}
// Move the enemies
for (auto &e : this->enemies)
{
e.move(0.f, 1.f);
}
}
void game::update()
{
this->pollEvents();
this->updateMousePositions();
this->updateEnemies();
}
void game::renderEnemies()
{
for (auto &e : this->enemies)
{
this->window->draw(e);
}
}
void game::render()
{
/*
- clears old frame
- renders objects
- display frames on window
renders game objects.
*/
this->window->clear(sf::Color(128, 128, 128));
//draw game objects
this->renderEnemies();
this->player1();
this->window->display();
}
void game::updateMousePositions()
{
/*
#return void
updates the mouse position
*mouse postion relative to window (vector2i)*
*/
this->mousePosWindow = sf::Mouse::getPosition(*this->window);
}
game.h
#include <iostream>
#include <vector>
#include <ctime>
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <SFML/System.hpp>
#include <SFML/Audio.hpp>
#include <SFML/Network.hpp>
/* class acts as the game engine
wrapper class.
*/
class game
{
protected:
//variables
//window
sf::RenderWindow* window;
sf::VideoMode videoMode;
sf::Event evnt;
//mouse positions
sf::Vector2i mousePosWindow;
//game logic
int points;
float enemySpawnTimer;
float enemySpawnTimerMax;
int maxEnemies;
//game objects
std::vector<sf::RectangleShape> enemies;
sf::RectangleShape enemy;
Player player;
// Private Functions
void intVariables();
void intWindow();
void intEnemies();
public:
// Constructors or Destructors
game();
virtual ~game();
// Accessors
const bool running() const;
// Functions
void player1();
void spawnEnemy();
void pollEvents();
void updateEnemies();
void update();
void renderEnemies();
void render();
void updateMousePositions();
};
Player.h
#include <iostream>
#include <SFML/Graphics.hpp>
#include "game.h"
class Player
{
public:
Player() {
//default
}
Player(std::string imgDirectory) {
if (!playerTexture.loadFromFile(imgDirectory)) {
std::cerr << "Error\n";
}
playerSprite.setTexture(playerTexture);
}
void drawPlayer(sf::RenderWindow& window) {
window.draw(playerSprite);
}
void movePlayer(char direction, float moveSpeed) {
if (direction == 'u')
{
playerSprite.move(0, -moveSpeed);
}
else if (direction == 'd')
{
playerSprite.move(0, -moveSpeed);
}
else if (direction == 'l')
{
playerSprite.move(-moveSpeed, 0);
}
else if (direction == 'r')
{
playerSprite.move(moveSpeed, 0);
}
}
private:
sf::Texture playerTexture;
sf::Sprite playerSprite;
};
I can connect to open wifi via "connmanctl" using dbus via Qt,. I would like to connect secured wife using connmanctl via dbus. there is an API to regiser an agent( interactive mode, to enter passphrase) called "RegisterAgent(object path)"
, In this, I am not sure what is mean by object path. I have tried object path with ""/net/connman/technology/wifi", but it was not working. I think I am wrong on something. I have added Qt compiled code below. Can some one help me to connect to secured network through connmanctl via dbus ?
//------------tocker.h------------------
#ifndef TOCKER_H
#define TOCKER_H
#include <QObject>
#include <QDBusMessage>
#include <QDBusError>
class Tocker : public QObject
{
Q_OBJECT
public:
explicit Tocker(QObject *parent = 0);
signals:
public slots:
void onAgentRegisterRequested(QDBusMessage);
void onErrorResponse(QDBusError);
};
#endif // TOCKER_H
//----------------------
//talker.cpp................
#include <QDBusInterface>
#include <QDBusConnection>
#include <QList>
#include <QVariant>
#include <QtDebug>
#include "tocker.h"\
Tocker::Tocker(QObject *parent) : QObject(parent)
{
QDBusInterface interfaceObj("net.connman", "/", "net.connman.Manager", QDBusConnection::systemBus());
bool isScucess = false;
do
{
if(interfaceObj.isValid())
{
QList<QVariant> params;
params << "/net/connman/technology/wifi"; //I am not sure is this path is correct
if( interfaceObj.callWithCallback("RegisterAgent", params, this, SLOT(onAgentRegisterRequestedd(QDBusMessage)), SLOT(onErrorResponse(QDBusError)) ))
{
qDebug()<< Q_FUNC_INFO << "callWithCallback is success";
isScucess = true;
}
else
{
isScucess = false;
}
break;
}
}
while(false);
if( !isScucess )
{
qDebug()<< Q_FUNC_INFO << interfaceObj.lastError().message();
}
else
{
qDebug() << Q_FUNC_INFO << "Callback is success.";
}
}
void Tocker::onAgentRegisterRequested(QDBusMessage msg)
{
qDebug()<< Q_FUNC_INFO << msg;
}
void Tocker::onErrorResponse(QDBusError errorMsg )
{
qDebug()<< Q_FUNC_INFO << errorMsg;
}
-----------main.cpp........
#include <QCoreApplication>
#include "tocker.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Tocker tocker;
return a.exec();
}
I have simple code:
#include <SFML\Graphics.hpp>
sf::RenderWindow *mainWindow;
void changeMainWindowParameters()
{
while(mainWindow->isOpen())
{
sf::Event event;
while (mainWindow->pollEvent(event))
{
if(event.type == sf::Event::Closed)
{
mainWindow->close();
return;
}
}
mainWindow->clear();
mainWindow->draw(sf::CircleShape(50.0F, 30));
mainWindow->display();
}
}
int main()
{
mainWindow = new sf::RenderWindow(
sf::VideoMode(100, 100), "Window");
changeMainWindowParameters();
}
But if I want to do it with threads, it does not work as in previous example:
#include <SFML\Graphics.hpp>
sf::RenderWindow *mainWindow;
void changeMainWindowParameters()
{
while(mainWindow->isOpen())
{
sf::Event event;
while (mainWindow->pollEvent(event))
{
if(event.type == sf::Event::Closed)
{
mainWindow->close();
return;
}
}
mainWindow->clear();
mainWindow->draw(sf::CircleShape(50.0F, 30));
mainWindow->display();
}
}
int main()
{
mainWindow = new sf::RenderWindow(
sf::VideoMode(100, 100), "Window");
sf::Thread th(changeMainWindowParameters);
th.launch();
//code
th.wait();
}
I can't close the window/move it etc.
I want the program to do something (drawing images on this window etc.) and so I could close/move this window.
Where is wrong?
I solve this problem:
#include <SFML\Graphics.hpp>
#include <thread>
#include <iostream>
sf::RenderWindow *mainWindow = nullptr;
void changeMainWindowParameters()
{
if (mainWindow == nullptr)
mainWindow = new sf::RenderWindow(sf::VideoMode(100, 100), "Window");
while(mainWindow->isOpen())
{
sf::Event event;
while (mainWindow->pollEvent(event))
{
if(event.type == sf::Event::Closed)
{
mainWindow->close();
return;
}
}
mainWindow->clear();
mainWindow->draw(sf::CircleShape(50.0F, 30));
mainWindow->display();
}
}
int main()
{
sf::Thread th(changeMainWindowParameters);
th.launch();
for(;;)
std::cout << '.';
th.wait();
}
We must remember that the event loop (more precisely, the pollEvent or waitEvent function) must be called in the same thread that created the window.
The code below triggers the error:
Error 1 error C2248: 'std::promise<_Ty>::promise' : cannot access private member declared in class 'std::promise<_Ty>'
How can I fix it?
Thanks a lot !
#define _parallel_qick_sort
#ifdef _parallel_qick_sort
#include <boost/shared_ptr.hpp>
#include <thread>
#include <vector>
#include <list>
#include <future>
#include <atomic>
#include "ThreadSafeStack.hpp"
using namespace std;
template<typename T>
struct sorter
{
struct chunk_to_sort
{
std::list<T> data_m;
std::promise<std::list<T> > promise_m;
};
threadsafe_stack<chunk_to_sort> chunks_m;
std::vector<std::thread> threads_m;
unsigned const max_thread_count_m;
std::atomic<bool> end_of_data_m;
sorter():
max_thread_count_m(std::thread::hardware_concurrency()-1),
end_of_data_m(false)
{}
~sorter()
{
end_of_data_m=true;
for(unsigned i=0;i<threads_m.size();++i)
{
threads_m[i].join();
}
}
void try_sort_chunk()
{
boost::shared_ptr<chunk_to_sort > chunk=chunks.pop();
if(chunk)
{
sort_chunk(chunk);
}
}
std::list<T> do_sort(std::list<T>& chunk_data)
{
if(chunk_data.empty())
{
return chunk_data;
}
std::list<T> result;
result.splice(result.begin(),chunk_data,chunk_data.begin());
T const& partition_val=*result.begin();
typename std::list<T>::iterator divide_point = std::partition(chunk_data.begin(),chunk_data.end(),[&](T const& val){return val<partition_val;});
chunk_to_sort new_lower_chunk;
new_lower_chunk.data_m.splice(new_lower_chunk.data_m.end(),chunk_data,chunk_data.begin(),divide_point);
std::future<std::list<T> > new_lower = new_lower_chunk.promise_m.get_future();
chunks_m.push(std::move(new_lower_chunk));
if(threads_m.size()<max_thread_count_m)
{
threads_m.push_back(std::thread(&sorter<T>::sort_thread,this));
}
std::list<T> new_higher(do_sort(chunk_data));
result.splice(result.end(),new_higher);
while(new_lower.wait_for(std::chrono::seconds(0)) !=
std::future_status::ready)
{
try_sort_chunk();
}
result.splice(result.begin(),new_lower.get());
return result;
}
void sort_chunk(boost::shared_ptr<chunk_to_sort > const& chunk)
{
chunk->promise_m.set_value(do_sort(chunk->data));
}
void sort_thread()
{
while(!end_of_data)
{
try_sort_chunk();
std::this_thread::yield();
}
}
};
template<typename T>
std::list<T> parallel_quick_sort(std::list<T> input)
{
if(input.empty())
{
return input;
}
sorter<T> s;
return s.do_sort(input);
}
int main()
{
list<int> l;
l.push_back(4);
l.push_back(3);
l.push_back(1);
l.push_back(2);
parallel_quick_sort(l);
return 0;
}
#endif
Below is threadsafe_stack class:
#ifndef __ThreadSafeStack_hpp__
#define __ThreadSafeStack_hpp__
#include "stdafx.h"
#include <exception>
#include <memory>
#include <mutex>
#include <stack>
#include <thread>
#include <iostream>
#include <functional>
#include <future>
using namespace std;
struct empty_stack : std::exception
{
const char* what() const throw()
{
return "empty stack";
}
};
template <typename T>
class threadsafe_stack
{
std::stack<T> data_m;
mutable std::mutex mutex_m;
threadsafe_stack& operator = (const threadsafe_stack&);
public:
typedef void (threadsafe_stack<T>:: * ext_push) (T);
typedef shared_ptr<T> (threadsafe_stack<T>:: *ext_pop)();
typedef void (threadsafe_stack<T>:: *ext_pop_void)(T& );
typedef bool (threadsafe_stack<T>:: *ext_empty) () const;
threadsafe_stack()
{
int i=0;
}
threadsafe_stack(const threadsafe_stack& other)
{
std::lock_guard<std::mutex> lock(other.mutex_m);
for(int i=0; i<3; ++i)
cout << "threadsafe_stack ctor "<< i << endl;
data_m = other.data_m;
}
void push(T new_value)
{
std::lock_guard<std::mutex> lock(mutex_m);
for(int i=0; i<3; ++i)
cout << "push "<< i << endl;
data_m.push(new_value);
}
std::shared_ptr<T> pop()
{
std::lock_guard<std::mutex> lock(mutex_m);
for(int i=0; i<3; ++i)
cout << "pop "<< i << endl;
if(data_m.empty())
throw empty_stack();
std::shared_ptr<T> const res(std::make_shared<T>(data_m.top()));
data_m.pop();
return res;
}
void pop(T& value)
{
std::lock_guard<std::mutex> lock(mutex_m);
for(int i=0; i<3; ++i)
cout << "pop "<< i << endl;
if(data_m.empty())
throw empty_stack();
value = data_m.top();
data_m.pop();
}
bool empty() const
{
//std::lock_guard<std::mutex> lock(mutex_m);
for(int i=0; i<3; ++i)
cout << "empty "<< i << endl;
return data_m.empty();
}
};
#endif __ThreadSafeStack_hpp__
I need to process each frame of a ONI file. For now I want just to save each frame of a file.oni in file.pcd. I follow this code but it works only with PCL 1.7 and I'm using v1.6.
So I changed a bit the code in this manner
#include <pcl/io/openni_grabber.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/oni_grabber.h>
#include <pcl/io/pcd_io.h>
#include <vector>
int i = 0;
char buf[4096];
class SimpleOpenNIViewer
{
public:
SimpleOpenNIViewer () : viewer ("PCL OpenNI Viewer") {}
void cloud_cb_ (const pcl::PointCloud<pcl::PointXYZ>::ConstPtr &cloud)
{
//if (!viewer.wasStopped())
//{
// viewer.showCloud (cloud);
pcl::PCDWriter w;
sprintf (buf, "frame_%06d.pcd", i);
w.writeBinaryCompressed (buf, *cloud);
PCL_INFO ("Wrote a cloud with %zu (%ux%u) points in %s.\n",cloud->size (), cloud->width, cloud->height, buf);
++i;
//}
}
void run ()
{
pcl::Grabber* interface = new pcl::OpenNIGrabber("file.oni");
boost::function<void (const pcl::PointCloud<pcl::PointXYZ>::ConstPtr&)> f = boost::bind (&SimpleOpenNIViewer::cloud_cb_, this, _1);
interface->registerCallback (f);
interface->start ();
while (!viewer.wasStopped())
{
boost::this_thread::sleep (boost::posix_time::seconds (1));
}
PCL_INFO ("Successfully processed %d frames.\n", i);
interface->stop ();
}
pcl::visualization::CloudViewer viewer;
};
int main ()
{
SimpleOpenNIViewer v;
v.run ();
return 0;
}
But it crash when I run it. Why?
I solved my problem about getting each frame from a ONI file. I need to use the ONIGrabber function set in the trigger mode.
This is the modified code:
#include <pcl/io/openni_grabber.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/oni_grabber.h>
#include <pcl/io/pcd_io.h>
#include <vector>
class SimpleOpenNIViewer
{
public:
SimpleOpenNIViewer () : viewer ("PCL OpenNI Viewer") {}
void cloud_cb_ (const pcl::PointCloud<pcl::PointXYZ>::ConstPtr &cloud)
{
//if (!viewer.wasStopped())
//{
// viewer.showCloud (cloud);
pcl::PCDWriter w;
sprintf (buf, "frame_%06d.pcd", i);
w.writeBinaryCompressed (buf, *cloud);
PCL_INFO ("Wrote a cloud with %zu (%ux%u) points in %s.\n",cloud->size (),
cloud->width, cloud->height, buf);
++i;
//}
}
void run ()
{
pcl::Grabber* interface = new pcl::ONIGrabber("file.oni",false,false); //set for trigger
boost::function<void (const pcl::PointCloud<pcl::PointXYZ>::ConstPtr&)> f = boost::bind (&SimpleOpenNIViewer::cloud_cb_, this, _1);
interface->registerCallback (f);
interface->start ();
while (!viewer.wasStopped())
{
interface->start()//to update each frame from the oni file
boost::this_thread::sleep (boost::posix_time::seconds (1));
}
PCL_INFO ("Successfully processed %d frames.\n", i);
interface->stop ();
}
pcl::visualization::CloudViewer viewer;
};
int main ()
{
SimpleOpenNIViewer v;
v.run ();
return 0;
}`