Beispiel #1
0
void LogScene::createBackground() {
    QBrush brush(QColor("white"));
    QPen pen(QColor("white"));
    // Background color
    QList<QGraphicsView*> views = this->views();
    int maxWidth = 0;
    double minuteSize = (double)BLOCKSIZE / (double)60;
    int maxHeight = minuteSize * 25 * 60;
    for (QList<QGraphicsView*>::iterator iter = views.begin(); iter != views.end(); iter++) {
        QGraphicsView* view = *iter;
//        int viewHeight = view->height();
        int viewWidth = view->width();
//        if (viewHeight > maxHeight) {
//            maxHeight = viewHeight;
//        }
        if (viewWidth > maxWidth) {
            maxWidth = viewWidth;
        }
    }
//    if (_viewSizeHeight > maxHeight) {
//        maxHeight = _viewSizeHeight;
//    }
    if (_viewSizeWidth > maxWidth) {
        maxWidth = _viewSizeWidth;
    }
    _viewSizeHeight = BLOCKSIZE*25;
    _viewSizeWidth = maxWidth;

    this->addRect(0, 0, maxWidth, maxHeight, pen, brush);

    //    int columnSize = geometry().width() / NU_COLS;
    int textSize = 30;
    int margin = 15;
    int cols = _totalDays;

    if ((cols * dayWidth()) < maxWidth) {
        cols = (maxWidth / dayWidth()) + 10;
        _totalDays = cols;
    }
    DateTime startDate = this->_startDate;
    DateTime today;
    today.setHour(0);
    today.setMin(0);
    today.setSecs(0);
    for (int x = 0; x < (cols + 1); x++) {
        QColor barcolor;
        if ((x % 2) > 0) {
            barcolor = QColor("white");
        } else {
            barcolor = QColor(240, 240, 240);
        }
        QBrush brushBar(barcolor);
        QPen penBar(barcolor);
        int left = (x* dayWidth()) + 0;
        int top = 0;
        int heigth = maxHeight;
        addRect(left, top, dayWidth(), heigth, penBar, brushBar);

        QPen pen(QColor(200, 200, 200));
        pen.setStyle(Qt::DashLine);

        addLine(x*dayWidth(), 0 , x*dayWidth(), heigth, pen);
        if (startDate == today) {
            barcolor = QColor(230, 230, 250);
            addRect(left, top, dayWidth(), heigth, penBar, QBrush(barcolor));
        }
        startDate = startDate.addDays(1);
    }
}
Beispiel #2
0
void IntroScene::close(QGraphicsView view)
{
    view.close();
}
Beispiel #3
0
CardEditor::CardEditor(QWidget *parent) :
	QMainWindow(parent)
{
	setWindowTitle(tr("Card editor"));

	QHBoxLayout *layout = new QHBoxLayout;
	QGraphicsView *view = new QGraphicsView;

	view->setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform | QPainter::HighQualityAntialiasing);

	card_scene = new CardScene;
	connect(card_scene, SIGNAL(avatar_snapped(QRectF)), this, SLOT(saveAvatar(QRectF)));

	view->setScene(card_scene);
	view->setFixedSize(card_scene->sceneRect().width() + 2,
					   card_scene->sceneRect().height() + 2);

	layout->addWidget(createLeft());
	layout->addWidget(view);

	QWidget *central_widget = new QWidget;
	central_widget->setLayout(layout);
	setCentralWidget(central_widget);

	QMenuBar *menu_bar = new QMenuBar;
	setMenuBar(menu_bar);

	QMenu *file_menu = new QMenu(tr("File"));
	QAction *import = new QAction(tr("Import ..."), file_menu);
	import->setShortcut(Qt::CTRL + Qt::Key_O);
	QAction *save = new QAction(tr("Save ..."), file_menu);
	save->setShortcut(Qt::CTRL + Qt::Key_S);
	QAction *exit = new QAction(tr("Exit"), file_menu);
	exit->setShortcut(Qt::CTRL + Qt::Key_Q);

	file_menu->addAction(import);
	file_menu->addAction(save);
	file_menu->addSeparator();
	file_menu->addAction(exit);

	menu_bar->addMenu(file_menu);

	connect(import, SIGNAL(triggered()), this, SLOT(import()));
	connect(save, SIGNAL(triggered()), this, SLOT(saveImage()));
	connect(exit, SIGNAL(triggered()), this, SLOT(close()));

	QMenu *tool_menu = new QMenu(tr("Tool"));

	QAction *making_big = new QAction(tr("Make big avatar"), tool_menu);
	making_big->setShortcut(Qt::ALT + Qt::Key_B);
	connect(making_big, SIGNAL(triggered()), card_scene, SLOT(makeBigAvatar()));
	tool_menu->addAction(making_big);

	QAction *making_small = new QAction(tr("Make small avatar"), tool_menu);
	making_small->setShortcut(Qt::ALT + Qt::Key_M);
	connect(making_small, SIGNAL(triggered()), card_scene, SLOT(makeSmallAvatar()));
	tool_menu->addAction(making_small);

	QAction *making_tiny = new QAction(tr("Make tiny avatar"), tool_menu);
	making_tiny->setShortcut(Qt::ALT + Qt::Key_T);
	connect(making_tiny, SIGNAL(triggered()), card_scene, SLOT(makeTinyAvatar()));
	tool_menu->addAction(making_tiny);

	QAction *hiding_rect = new QAction(tr("Hide avatar rect"), tool_menu);
	hiding_rect->setShortcut(Qt::ALT + Qt::Key_H);
	connect(hiding_rect, SIGNAL(triggered()), card_scene, SLOT(hideAvatarRects()));
	tool_menu->addAction(hiding_rect);

	tool_menu->addSeparator();

	QAction *reset_photo = new QAction(tr("Reset photo"), tool_menu);
	reset_photo->setShortcut(Qt::ALT + Qt::Key_R);
	connect(reset_photo, SIGNAL(triggered()), card_scene, SLOT(resetPhoto()));
	tool_menu->addAction(reset_photo);

	QAction *copy_photo = new QAction(tr("Copy photo to clipboard"), tool_menu);
	copy_photo->setShortcut(Qt::CTRL + Qt::Key_C);
	connect(copy_photo, SIGNAL(triggered()), this, SLOT(copyPhoto()));
	tool_menu->addAction(copy_photo);

	menu_bar->addMenu(tool_menu);

	card_scene->setMenu(tool_menu);
}
Beispiel #4
0
 void init_scene(QGraphicsView& v)
 {
     auto s = new QGraphicsScene;
     v.setScene(s);
     ENSURE(v.scene());
 }
Beispiel #5
0
//create all sub-widgets and display everything
void PlayScreen::display(int screenWidth, int screenHeight, int gridSize)
{
    this->screenWidth = screenWidth;
    this->screenHeight = screenHeight;

    grid = gridSize;
    numMoves = 0;
    seconds = 0;
    percentComplete = grid*grid;
    QFont font("Helvectica", 13);

    //set up scene and view
    QGraphicsScene *gScene = new QGraphicsScene(this);
    QGraphicsView *gView = new QGraphicsView(gScene);
    gView->setFixedSize(screenWidth, screenHeight);
    gScene->setBackgroundBrush(Qt::black);

    //set up all GridLayouts
    QGridLayout *layout = new QGridLayout(gView);
    playGrid = new QGridLayout();
    QGridLayout *menuGrid = new QGridLayout();
    layout->setContentsMargins(0,0,0,0);
    playGrid->setContentsMargins(0,0,0,0);
    menuGrid->setContentsMargins(0,0,0,0);
    gView->setLayout(layout);
    layout->addLayout(playGrid, 0, 0);
    layout->addLayout(menuGrid, 1, 0);

    //timer and move labels
    movesLabel = new QLabel("Moves: " + QString::number(numMoves));
    timerLabel = new QLabel("Time: 0:0");
    percentLabel = new QLabel("Percent: 0%");
    menuGrid->addWidget(movesLabel,0,0);
    menuGrid->addWidget(timerLabel,1,0);
    menuGrid->addWidget(percentLabel,2,0);
    movesLabel->setFont(font);
    timerLabel->setFont(font);
    percentLabel->setFont(font);

    //menu buttons
    QPushButton *winButton = new QPushButton("DEBUG WIN");
    QPushButton *pauseButton = new QPushButton("Pause/Play");
    QPushButton *giveUpButton = new QPushButton("Give Up");
    menuGrid->addWidget(winButton, 0, 1);
    menuGrid->addWidget(pauseButton, 1, 1);
    menuGrid->addWidget(giveUpButton, 2, 1);
    winButton->setFont(font);
    pauseButton->setFont(font);
    giveUpButton->setFont(font);
    connect(winButton, SIGNAL(clicked()), this, SLOT(winButtonClicked()));
    connect(pauseButton, SIGNAL(clicked()), this, SLOT(pauseButtonClicked()));
    connect(giveUpButton, SIGNAL(clicked()), this, SLOT(giveUpButtonClicked()));

    //import image
    QImageReader reader(imgPath);
    reader.setScaledSize(QSize(screenWidth, screenWidth));
    QImage image = reader.read();
    int eHeight = image.height();
    int eWidth = image.width();

    //cut image into tiles and position them
    for(int i = 0; i < grid; i++){
        for(int j = 0; j < grid; j++){
            if(!(i==grid-1 && j==grid-1)){
                QPixmap pixmap = QPixmap::fromImage(image.copy(i*(eWidth/grid), j*(eHeight/grid), eWidth/grid, eHeight/grid));
                QIcon icon(pixmap);
                Tile *button = new Tile(i, j, icon);
                button->setIconSize(QSize(eWidth/grid, eHeight/grid));

                playGrid->addWidget(button, j, i);
                connect(button, SIGNAL(tileClicked(Tile*)), this, SLOT(handleTileClick(Tile*)));
            }
        }
    }
Beispiel #6
0
int main(int argc, char **argv)
{
    // Qt requires that we construct the global QApplication before creating any widgets.
    QApplication app(argc, argv);

    // use an ArgumentParser object to manage the program arguments.
    osg::ArgumentParser arguments(&argc,argv);

    // true = run osgViewer in a separate thread than Qt
    // false = interleave osgViewer and Qt in the main thread
    bool useFrameLoopThread = false;
    if (arguments.read("--no-frame-thread")) useFrameLoopThread = false;
    if (arguments.read("--frame-thread")) useFrameLoopThread = true;

    // true = use QWidgetImage
    // false = use QWebViewImage
    bool useWidgetImage = false;
    if (arguments.read("--useWidgetImage")) useWidgetImage = true;

    // true = use QWebView in a QWidgetImage to compare to QWebViewImage
    // false = make an interesting widget
    bool useBrowser = false;
    if (arguments.read("--useBrowser")) useBrowser = true;

    // true = use a QLabel for text
    // false = use a QTextEdit for text
    // (only applies if useWidgetImage == true and useBrowser == false)
    bool useLabel = false;
    if (arguments.read("--useLabel")) useLabel = true;

    // true = make a Qt window with the same content to compare to
    // QWebViewImage/QWidgetImage
    // false = use QWebViewImage/QWidgetImage (depending on useWidgetImage)
    bool sanityCheck = false;
    if (arguments.read("--sanityCheck")) sanityCheck = true;

    // Add n floating windows inside the QGraphicsScene.
    int numFloatingWindows = 0;
    while (arguments.read("--numFloatingWindows", numFloatingWindows));

    // true = Qt widgets will be displayed on a quad inside the 3D scene
    // false = Qt widgets will be an overlay over the scene (like a HUD)
    bool inScene = true;
    if (arguments.read("--fullscreen")) {
        inScene = false;
    }


    osg::ref_ptr<osg::Group> root = new osg::Group;

    if (!useWidgetImage)
    {
        //-------------------------------------------------------------------
        // QWebViewImage test
        //-------------------------------------------------------------------
        // Note: When the last few issues with QWidgetImage are fixed,
        // QWebViewImage and this if() {} section can be removed since
        // QWidgetImage can display a QWebView just like QWebViewImage. Use
        // --useWidgetImage --useBrowser to see that in action.

        if (!sanityCheck)
        {
            osg::ref_ptr<osgQt::QWebViewImage> image = new osgQt::QWebViewImage;

            if (arguments.argc()>1) image->navigateTo((arguments[1]));
            else image->navigateTo("http://www.youtube.com/");

            osgWidget::GeometryHints hints(osg::Vec3(0.0f,0.0f,0.0f),
                                           osg::Vec3(1.0f,0.0f,0.0f),
                                           osg::Vec3(0.0f,0.0f,1.0f),
                                           osg::Vec4(1.0f,1.0f,1.0f,1.0f),
                                           osgWidget::GeometryHints::RESIZE_HEIGHT_TO_MAINTAINCE_ASPECT_RATIO);

            osg::ref_ptr<osgWidget::Browser> browser = new osgWidget::Browser;
            browser->assign(image.get(), hints);

            root->addChild(browser.get());
        }
        else
        {
            // Sanity check, do the same thing as QGraphicsViewAdapter but in
            // a separate Qt window.
            QWebPage* webPage = new QWebPage;
            webPage->settings()->setAttribute(QWebSettings::JavascriptEnabled, true);
            webPage->settings()->setAttribute(QWebSettings::PluginsEnabled, true);

            QWebView* webView = new QWebView;
            webView->setPage(webPage);

            if (arguments.argc()>1) webView->load(QUrl(arguments[1]));
            else webView->load(QUrl("http://www.youtube.com/"));

            QGraphicsScene* graphicsScene = new QGraphicsScene;
            graphicsScene->addWidget(webView);

            QGraphicsView* graphicsView = new QGraphicsView;
            graphicsView->setScene(graphicsScene);

            QMainWindow* mainWindow = new QMainWindow;
            //mainWindow->setLayout(new QVBoxLayout);
            mainWindow->setCentralWidget(graphicsView);
            mainWindow->setGeometry(50, 50, 1024, 768);
            mainWindow->show();
            mainWindow->raise();
        }
    }
    else
    {
        //-------------------------------------------------------------------
        // QWidgetImage test
        //-------------------------------------------------------------------
        // QWidgetImage still has some issues, some examples are:
        //
        // 1. Editing in the QTextEdit doesn't work. Also when started with
        //    --useBrowser, editing in the search field on YouTube doesn't
        //    work. But that same search field when using QWebViewImage
        //    works... And editing in the text field in the pop-up getInteger
        //    dialog works too. All these cases use QGraphicsViewAdapter
        //    under the hood, so why do some work and others don't?
        //
        //    a) osgQtBrowser --useWidgetImage [--fullscreen] (optional)
        //    b) Try to click in the QTextEdit and type, or to select text
        //       and drag-and-drop it somewhere else in the QTextEdit. These
        //       don't work.
        //    c) osgQtBrowser --useWidgetImage --sanityCheck
        //    d) Try the operations in b), they all work.
        //    e) osgQtBrowser --useWidgetImage --useBrowser [--fullscreen]
        //    f) Try to click in the search field and type, it doesn't work.
        //    g) osgQtBrowser
        //    h) Try the operation in f), it works.
        //
        // 2. Operations on floating windows (--numFloatingWindows 1 or more).
        //    Moving by dragging the titlebar, clicking the close button,
        //    resizing them, none of these work. I wonder if it's because the
        //    OS manages those functions (they're functions of the window
        //    decorations) so we need to do something special for that? But
        //    in --sanityCheck mode they work.
        //
        //    a) osgQtBrowser --useWidgetImage --numFloatingWindows 1 [--fullscreen]
        //    b) Try to drag the floating window, click the close button, or
        //       drag its sides to resize it. None of these work.
        //    c) osgQtBrowser --useWidgetImage --numFloatingWindows 1 --sanityCheck
        //    d) Try the operations in b), all they work.
        //    e) osgQtBrowser --useWidgetImage [--fullscreen]
        //    f) Click the button so that the getInteger() dialog is
        //       displayed, then try to move that dialog or close it with the
        //       close button, these don't work.
        //    g) osgQtBrowser --useWidgetImage --sanityCheck
        //    h) Try the operation in f), it works.
        //
        // 3. (Minor) The QGraphicsView's scrollbars don't appear when
        //    using QWidgetImage or QWebViewImage. QGraphicsView is a
        //    QAbstractScrollArea and it should display scrollbars as soon as
        //    the scene is too large to fit the view.
        //
        //    a) osgQtBrowser --useWidgetImage --fullscreen
        //    b) Resize the OSG window so it's smaller than the QTextEdit.
        //       Scrollbars should appear but don't.
        //    c) osgQtBrowser --useWidgetImage --sanityCheck
        //    d) Try the operation in b), scrollbars appear. Even if you have
        //       floating windows (by clicking the button or by adding
        //       --numFloatingWindows 1) and move them outside the view,
        //       scrollbars appear too. You can't test that case in OSG for
        //       now because of problem 2 above, but that's pretty cool.
        //
        // 4. (Minor) In sanity check mode, the widget added to the
        //    QGraphicsView is centered. With QGraphicsViewAdapter, it is not.
        //
        //    a) osgQtBrowser --useWidgetImage [--fullscreen]
        //    b) The QTextEdit and button are not in the center of the image
        //       generated by the QGraphicsViewAdapter.
        //    c) osgQtBrowser --useWidgetImage --sanityCheck
        //    d) The QTextEdit and button are in the center of the
        //       QGraphicsView.


        QWidget* widget = 0;
        if (useBrowser)
        {
            QWebPage* webPage = new QWebPage;
            webPage->settings()->setAttribute(QWebSettings::JavascriptEnabled, true);
            webPage->settings()->setAttribute(QWebSettings::PluginsEnabled, true);

            QWebView* webView = new QWebView;
            webView->setPage(webPage);

            if (arguments.argc()>1) webView->load(QUrl(arguments[1]));
            else webView->load(QUrl("http://www.youtube.com/"));

            widget = webView;
        }
        else
        {
            widget = new QWidget;
            widget->setLayout(new QVBoxLayout);

            QString text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque velit turpis, euismod ac ultrices et, molestie non nisi. Nullam egestas dignissim enim, quis placerat nulla suscipit sed. Donec molestie elementum risus sit amet sodales. Nunc consectetur congue neque, at viverra massa pharetra fringilla. Integer vitae mi sem. Donec dapibus semper elit nec sollicitudin. Vivamus egestas ultricies felis, in mollis mi facilisis quis. Nam suscipit bibendum eros sed cursus. Suspendisse mollis suscipit hendrerit. Etiam magna eros, convallis non congue vel, faucibus ac augue. Integer ante ante, porta in ornare ullamcorper, congue nec nibh. Etiam congue enim vitae enim sollicitudin fringilla. Mauris mattis, urna in fringilla dapibus, ipsum sem feugiat purus, ac hendrerit felis arcu sed sapien. Integer id velit quam, sit amet dignissim tortor. Sed mi tortor, placerat ac luctus id, tincidunt et urna. Nulla sed nunc ante.Sed ut sodales enim. Ut sollicitudin ultricies magna, vel ultricies ante venenatis id. Cras luctus mi in lectus rhoncus malesuada. Sed ac sollicitudin nisi. Nunc venenatis congue quam, et suscipit diam consectetur id. Donec vel enim ac enim elementum bibendum ut quis augue. Nulla posuere suscipit dolor, id convallis tortor congue eu. Vivamus sagittis consectetur dictum. Duis a ante quis dui varius fermentum. In hac habitasse platea dictumst. Nam dapibus dolor eu felis eleifend in scelerisque dolor ultrices. Donec arcu lectus, fringilla ut interdum non, tristique id dolor. Morbi sagittis sagittis volutpat. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Duis venenatis ultrices euismod.Nam sit amet convallis libero. Integer lectus urna, eleifend et sollicitudin non, porttitor vel erat. Vestibulum pulvinar egestas leo, a porttitor turpis ullamcorper et. Vestibulum in ornare turpis. Ut nec libero a sem mattis iaculis quis id purus. Praesent ante neque, dictum vitae pretium vel, iaculis luctus dui. Etiam luctus tellus vel nunc suscipit a ullamcorper nisl semper. Nunc dapibus, eros in sodales dignissim, orci lectus egestas felis, sit amet vehicula tortor dolor eu quam. Vivamus pellentesque convallis quam aliquet pellentesque. Phasellus facilisis arcu ac orci fringilla aliquet. Donec sed euismod augue. Duis eget orci sit amet neque tempor fringilla. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; In hac habitasse platea dictumst. Duis sollicitudin, lacus ac pellentesque lacinia, lacus magna pulvinar purus, pulvinar porttitor est nibh quis augue.Duis eleifend, massa sit amet mattis fringilla, elit turpis venenatis libero, sed convallis turpis diam sit amet ligula. Morbi non dictum turpis. Integer porttitor condimentum elit, sit amet sagittis nibh ultrices sit amet. Mauris ac arcu augue, id aliquet mauris. Donec ultricies urna id enim accumsan at pharetra dui adipiscing. Nunc luctus rutrum molestie. Curabitur libero ipsum, viverra at pulvinar ut, porttitor et neque. Aliquam sit amet dolor et purus sagittis adipiscing. Nam sit amet hendrerit sem. Etiam varius, ligula non ultricies dignissim, sapien dui commodo urna, eu vehicula enim nunc molestie augue. Fusce euismod, erat vitae pharetra tempor, quam eros tincidunt lorem, ut iaculis ligula erat vitae nibh. Aenean eu ultricies dolor. Curabitur suscipit viverra bibendum.Sed egestas adipiscing mi in egestas. Proin in neque in nibh blandit consequat nec quis tortor. Vestibulum sed interdum justo. Sed volutpat velit vitae elit pulvinar aliquam egestas elit rutrum. Proin lorem nibh, bibendum vitae sollicitudin condimentum, pulvinar ut turpis. Maecenas iaculis, mauris in consequat ultrices, ante erat blandit mi, vel fermentum lorem turpis eget sem. Integer ultrices tristique erat sit amet volutpat. In sit amet diam et nunc congue pellentesque at in dolor. Mauris eget orci orci. Integer posuere augue ornare tortor tempus elementum. Quisque iaculis, nunc ac cursus fringilla, magna elit cursus eros, id feugiat diam eros et tellus. Etiam consectetur ultrices erat quis rhoncus. Mauris eu lacinia neque. Curabitur suscipit feugiat tellus in dictum. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Sed aliquam tempus ante a tempor. Praesent viverra erat quis sapien pretium rutrum. Praesent dictum scelerisque venenatis.Proin bibendum lectus eget nisl lacinia porta. Morbi eu erat in sapien malesuada vulputate. Cras non elit quam. Ut dictum urna quis nisl feugiat ac sollicitudin libero luctus. Donec leo mauris, varius at luctus eget, placerat quis arcu. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Etiam tristique, mauris ut lacinia elementum, mauris erat consequat massa, ac gravida nisi tellus vitae purus. Curabitur consectetur ultricies commodo. Cras pulvinar orci nec enim adipiscing tristique. Ut ornare orci id est fringilla sit amet blandit libero pellentesque. Vestibulum tincidunt sapien ut enim venenatis vestibulum ultricies ipsum tristique. Mauris tempus eleifend varius. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse vitae dui ac quam gravida semper. In ac enim ac ligula rutrum porttitor.Integer dictum sagittis leo, at convallis sapien facilisis eget. Etiam cursus bibendum tortor, faucibus aliquam lectus ullamcorper sed. Nulla pulvinar posuere quam, ut sagittis ligula tincidunt ut. Nulla convallis velit ut enim condimentum pulvinar. Quisque gravida accumsan scelerisque. Proin pellentesque nisi cursus tortor aliquet dapibus. Duis vel eros orci. Sed eget purus ligula. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ullamcorper porta congue. Nunc id velit ut neque malesuada consequat in eu nisi. Nulla facilisi. Quisque pellentesque magna vitae nisl euismod ac accumsan tellus feugiat.Nulla facilisi. Integer quis orci lectus, non aliquam nisi. Vivamus varius porta est, ac porttitor orci blandit mattis. Sed dapibus facilisis dapibus. Duis tincidunt leo ac tortor faucibus hendrerit. Morbi sit amet sapien risus, vel luctus enim. Aliquam sagittis nunc id purus aliquam lobortis. Duis posuere viverra dui, sit amet convallis sem vulputate at. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque pellentesque, lectus id imperdiet commodo, diam diam faucibus lectus, sit amet vestibulum tortor lacus viverra eros.Maecenas nec augue lectus. Duis nec arcu eget lorem tempus sollicitudin suscipit vitae arcu. Nullam vitae mauris lectus. Vivamus id risus neque, dignissim vehicula diam. Cras rhoncus velit sed velit iaculis ac dignissim turpis luctus. Suspendisse potenti. Sed vitae ligula a ligula ornare rutrum sit amet ut quam. Duis tincidunt, nibh vitae iaculis adipiscing, dolor orci cursus arcu, vel congue tortor quam eget arcu. Suspendisse tellus felis, blandit ac accumsan vitae, fringilla id lorem. Duis tempor lorem mollis est congue ut imperdiet velit laoreet. Nullam interdum cursus mollis. Pellentesque non mauris accumsan elit laoreet viverra ut at risus. Proin rutrum sollicitudin sem, vitae ultricies augue sagittis vel. Cras quis vehicula neque. Aliquam erat volutpat. Aliquam erat volutpat. Praesent non est erat, accumsan rutrum lacus. Pellentesque tristique molestie aliquet. Cras ullamcorper facilisis faucibus. In non lorem quis velit lobortis pulvinar.Phasellus non sem ipsum. Praesent ut libero quis turpis viverra semper. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. In hac habitasse platea dictumst. Donec at velit tellus. Fusce commodo pharetra tincidunt. Proin lacus enim, fringilla a fermentum ut, vestibulum ut nibh. Duis commodo dolor vel felis vehicula at egestas neque bibendum. Phasellus malesuada dictum ante in aliquam. Curabitur interdum semper urna, nec placerat justo gravida in. Praesent quis mauris massa. Pellentesque porttitor lacinia tincidunt. Phasellus egestas viverra elit vel blandit. Sed dapibus nisi et lectus pharetra dignissim. Mauris hendrerit lectus nec purus dapibus condimentum. Sed ac eros nulla. Aenean semper sapien a nibh aliquam lobortis. Aliquam elementum euismod sapien, in dapibus leo dictum et. Pellentesque augue neque, ultricies non viverra eu, tincidunt ac arcu. Morbi ut porttitor lectus.");

            if (useLabel)
            {
                QLabel* label = new QLabel(text);
                label->setWordWrap(true);
                label->setTextInteractionFlags(Qt::TextEditorInteraction);

                QPalette palette = label->palette();
                palette.setColor(QPalette::Highlight, Qt::darkBlue);
                palette.setColor(QPalette::HighlightedText, Qt::white);
                label->setPalette(palette);

                QScrollArea* scrollArea = new QScrollArea;
                scrollArea->setWidget(label);

                widget->layout()->addWidget(scrollArea);
            }
            else
            {
                QTextEdit* textEdit = new QTextEdit(text);
                textEdit->setReadOnly(false);
                textEdit->setTextInteractionFlags(Qt::TextEditable);

                QPalette palette = textEdit->palette();
                palette.setColor(QPalette::Highlight, Qt::darkBlue);
                palette.setColor(QPalette::HighlightedText, Qt::white);
                textEdit->setPalette(palette);

                widget->layout()->addWidget(textEdit);
            }

            QPushButton* button = new MyPushButton("Button");
            widget->layout()->addWidget(button);

            widget->setGeometry(0, 0, 800, 600);
        }

        QGraphicsScene* graphicsScene = 0;

        if (!sanityCheck)
        {
            osg::ref_ptr<osgQt::QWidgetImage> widgetImage = new osgQt::QWidgetImage(widget);
#if (QT_VERSION >= QT_VERSION_CHECK(4, 5, 0))
            widgetImage->getQWidget()->setAttribute(Qt::WA_TranslucentBackground);
#endif
            widgetImage->getQGraphicsViewAdapter()->setBackgroundColor(QColor(0, 0, 0, 0));
            //widgetImage->getQGraphicsViewAdapter()->resize(800, 600);
            graphicsScene = widgetImage->getQGraphicsViewAdapter()->getQGraphicsScene();

            osg::Camera* camera = 0;        // Will stay NULL in the inScene case.
            osg::Geometry* quad = osg::createTexturedQuadGeometry(osg::Vec3(0,0,0), osg::Vec3(1,0,0), osg::Vec3(0,1,0), 1, 1);
            osg::Geode* geode = new osg::Geode;
            geode->addDrawable(quad);

            osg::MatrixTransform* mt = new osg::MatrixTransform;

            osg::Texture2D* texture = new osg::Texture2D(widgetImage.get());
            texture->setResizeNonPowerOfTwoHint(false);
            texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
            texture->setWrap(osg::Texture::WRAP_S, osg::Texture::CLAMP_TO_EDGE);
            texture->setWrap(osg::Texture::WRAP_T, osg::Texture::CLAMP_TO_EDGE);
            mt->getOrCreateStateSet()->setTextureAttributeAndModes(0, texture, osg::StateAttribute::ON);

            osgViewer::InteractiveImageHandler* handler;
            if (inScene)
            {
                mt->setMatrix(osg::Matrix::rotate(osg::Vec3(0,1,0), osg::Vec3(0,0,1)));
                mt->addChild(geode);

                handler = new osgViewer::InteractiveImageHandler(widgetImage.get());
            }
            else    // fullscreen
            {
                // The HUD camera's viewport needs to follow the size of the
                // window. MyInteractiveImageHandler will make sure of this.
                // As for the quad and the camera's projection, setting the
                // projection resize policy to FIXED takes care of them, so
                // they can stay the same: (0,1,0,1) with a quad that fits.

                // Set the HUD camera's projection and viewport to match the screen.
                camera = new osg::Camera;
                camera->setProjectionResizePolicy(osg::Camera::FIXED);
                camera->setProjectionMatrix(osg::Matrix::ortho2D(0,1,0,1));
                camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
                camera->setViewMatrix(osg::Matrix::identity());
                camera->setClearMask(GL_DEPTH_BUFFER_BIT);
                camera->setRenderOrder(osg::Camera::POST_RENDER);
                camera->addChild(geode);
                camera->setViewport(0, 0, 1024, 768);

                mt->addChild(camera);

                handler = new osgViewer::InteractiveImageHandler(widgetImage.get(), texture, camera);
            }

            mt->getOrCreateStateSet()->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
            mt->getOrCreateStateSet()->setMode(GL_BLEND, osg::StateAttribute::ON);
            mt->getOrCreateStateSet()->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
            mt->getOrCreateStateSet()->setAttribute(new osg::Program);

            osg::Group* overlay = new osg::Group;
            overlay->addChild(mt);

            root->addChild(overlay);

            quad->setEventCallback(handler);
            quad->setCullCallback(handler);
        }
        else
        {
            // Sanity check, do the same thing as QWidgetImage and
            // QGraphicsViewAdapter but in a separate Qt window.

            graphicsScene = new QGraphicsScene;
            graphicsScene->addWidget(widget);

            QGraphicsView* graphicsView = new QGraphicsView;
            graphicsView->setScene(graphicsScene);

            QMainWindow* mainWindow = new QMainWindow;
            mainWindow->setCentralWidget(graphicsView);
            mainWindow->setGeometry(50, 50, 1024, 768);
            mainWindow->show();
            mainWindow->raise();
        }

        // Add numFloatingWindows windows to the graphicsScene.
        for (unsigned int i = 0; i < (unsigned int)numFloatingWindows; ++i)
        {
            QWidget* window = new QWidget(0, Qt::Window);
            window->setWindowTitle(QString("Window %1").arg(i));
            window->setLayout(new QVBoxLayout);
            window->layout()->addWidget(new QLabel(QString("This window %1").arg(i)));
            window->layout()->addWidget(new MyPushButton(QString("Button in window %1").arg(i)));
            window->setGeometry(100, 100, 300, 300);

            QGraphicsProxyWidget *proxy = new QGraphicsProxyWidget(0, Qt::Window);
            proxy->setWidget(window);
            proxy->setFlag(QGraphicsItem::ItemIsMovable, true);

            graphicsScene->addItem(proxy);
        }

    }

    root->addChild(osgDB::readNodeFile("cow.osg.(15,0,5).trans.(0.1,0.1,0.1).scale"));

    osg::ref_ptr<osgViewer::Viewer> viewer = new osgViewer::Viewer(arguments);
    viewer->setSceneData(root.get());
    viewer->setCameraManipulator(new osgGA::TrackballManipulator());
    viewer->addEventHandler(new osgGA::StateSetManipulator(root->getOrCreateStateSet()));
    viewer->addEventHandler(new osgViewer::StatsHandler);
    viewer->addEventHandler(new osgViewer::WindowSizeHandler);

    viewer->setUpViewInWindow(50, 50, 1024, 768);
    viewer->getEventQueue()->windowResize(0, 0, 1024, 768);

    if (useFrameLoopThread)
    {
        // create a thread to run the viewer's frame loop
        ViewerFrameThread viewerThread(viewer.get(), true);
        viewerThread.startThread();

        // now start the standard Qt event loop, then exists when the viewerThead sends the QApplication::exit() signal.
        return QApplication::exec();

    }
    else
    {
        // run the frame loop, interleaving Qt and the main OSG frame loop
        while(!viewer->done())
        {
            // process Qt events - this handles both events and paints the browser image
            QCoreApplication::processEvents(QEventLoop::AllEvents, 100);

            viewer->frame();
        }

        return 0;
    }
}
void JobViewServer::setupUi() {

  // Paar allgemeine Parameter
  setBackgroundHints(DefaultBackground);
  setHasConfigurationInterface(true);
  setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
  resize(400, 80);

  // Rahmen, der das Hauptlayout enthält
  Plasma::Frame* frame = new Plasma::Frame();
  frame->setFrameShadow(Plasma::Frame::Sunken);
  QGraphicsLinearLayout* fullSpaceLayout = new QGraphicsLinearLayout();
  fullSpaceLayout->setContentsMargins(0,0,0,0);
  setLayout(fullSpaceLayout);
  fullSpaceLayout->addItem(frame);
  QGraphicsLinearLayout* layout = new QGraphicsLinearLayout();
  layout->setContentsMargins(0,0,0,0);
  frame->setLayout(layout);

  // Icon mit History und Queue Indicator
  iconWidget = new Plasma::IconWidget();
  iconWidget->setPreferredWidth(25);
  iconWidget->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
  iconWidget->setIcon(KIcon("arrow-down"));
  layout->addItem(iconWidget);

  // Layout mit Progressbars
  meterContainer = new Plasma::Label();
  meterContainer->nativeWidget()->setWordWrap(true);
  meterLayout = new QGraphicsLinearLayout();
  meterContainer->setLayout(meterLayout);
  layout->addItem(meterContainer);

  // Popup erzeugen
  popup = new Plasma::Dialog();
  QVBoxLayout* popupLayout = new QVBoxLayout();
  popupLayout->setContentsMargins(0,0,0,0);
  popup->setLayout(popupLayout);
  popup->setWindowFlags(Qt::Popup);
  popup->resize(400, 300);

  // GraphicsView und GraphicsScene erzeugen
  QGraphicsScene* popupScene = new QGraphicsScene();
  QGraphicsView* popupView = new QGraphicsView();
  popupView->setScene(popupScene);
  popupView->setFrameStyle(QFrame::NoFrame);
  popupView->setStyleSheet("background-color: transparent;");
  popupView->setAlignment(Qt::AlignHCenter | Qt::AlignTop);
  popupView->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
  popupView->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
  popupLayout->addWidget(popupView);

  // Container mit dem GridLayout zur Scene hinzufügen
  jobViewContainer = new QGraphicsWidget();
  jobViewLayout = new QGraphicsLinearLayout(Qt::Vertical);
  jobViewLayout->setContentsMargins(5,5,5,5);
  jobViewContainer->setLayout(jobViewLayout);
  popupScene->addItem(jobViewContainer);

  // Überschrift-/Nachrichtenbereich
  popupHeadline = new Plasma::Label();
  popupHeadline->nativeWidget()->setAlignment(Qt::AlignCenter);
  jobViewLayout->addItem(popupHeadline);

  QObject::connect(iconWidget, SIGNAL(clicked()), this, SLOT(showPopup()));
}
Beispiel #8
0
void MainWindow::gotoScene(QGraphicsScene *scene){
    QGraphicsView *view = qobject_cast<QGraphicsView *>(centralWidget());
    view->setScene(scene);
    delete this->scene;
    this->scene = scene;
}
Beispiel #9
0
int main(int argc, char *argv[]) {
    QApplication a(argc, argv);

    // open file
    string filename = "input100.txt";
    ifstream input;
    input.open(filename);

    // the vector of points
    vector<Point> points;

    // read points from file
    int N;
    int x;
    int y;

    input >> N;

    for (int i = 0; i < N; ++i) {
        input >> x >> y;
        points.push_back(Point(x, y));
    }
    input.close();

    // setup graphical window
    QGraphicsView *view = new QGraphicsView();
    QGraphicsScene *scene = new QGraphicsScene(0, 0, SCENE_WIDTH, SCENE_HEIGHT);
    view->setScene(scene);
    // draw points to screen all at once
    render_points(scene, points);
    view->scale(1, -1); //screen y-axis is inverted
    view->resize(view->sizeHint());
    view->setWindowTitle("Brute Force Pattern Recognition");
    view->show();

    // sort points by natural order
    // makes finding endpoints of line segments easy
    sort(points.begin(), points.end());
    auto begin = chrono::high_resolution_clock::now();

    //for each point int points
    for (unsigned int i=0;i<points.size();i++){
        //we create a map with the slope as key and a vector of points as value
        map<double,vector<Point>> point_map;

        //for each point that is "larger" than the point we takes its slopes to the current point i
        for (unsigned int j=i+1;j<points.size();++j){
            //and adds it to the maps in the vector with all other points with the same slope
            point_map[points.at(i).slopeTo(points.at(j))].push_back(points.at(j));
        }
        //after this we iterate through each key in the map
        for (map<double,vector<Point>>::iterator it=point_map.begin(); it!=point_map.end(); ++it){
            //and check if the vector has a size of of three or more
            if (it->second.size()>=3){
                //creates a line
                render_line(scene,points.at(i),*(it->second.end()-1));
                //process the event
                a.processEvents();
            }
        }


    }


    auto end = chrono::high_resolution_clock::now();
    cout << "Computing line segments took "
         << std::chrono::duration_cast<chrono::milliseconds>(end - begin).count()
         << " milliseconds." << endl;

    return a.exec(); // start Qt event loop
}
MainWindow::MainWindow() : QMainWindow()
{
    //CSS codes...
    this->setStyleSheet("background-color:gray;");
    //

    // add drop down menus
    QMenu*  fileMenu = menuBar()->addMenu( "&File" );
    //QMenu*  editMenu = menuBar()->addMenu( "&Edit" );
    //QMenu*  viewMenu = menuBar()->addMenu( "&View" );
    //menuBar()->addMenu( "&Simulate" );
    //menuBar()->addMenu( "&Help" );

    // create file menu options
    //QAction* newAction     = fileMenu->addAction( "&New",              this, SLOT(fileNew()) );
    //QAction* saveAction    = fileMenu->addAction( "&Save As...",       this, SLOT(fileSaveAs()) );
    //QAction* openAction    = fileMenu->addAction( "&Open ...",         this, SLOT(fileOpen()) );
    //fileMenu->addSeparator();
    //QAction* previewAction = fileMenu->addAction( "Print pre&view...", this, SLOT(filePrintPreview()) );
    //QAction* printAction   = fileMenu->addAction( "&Print...",         this, SLOT(filePrint()) );
    //fileMenu->addSeparator();
    fileMenu->addAction( "&Quit",             this, SLOT(close()) );
    //newAction->setShortcut( QKeySequence::New );
    //saveAction->setShortcut( QKeySequence::Save );
    //openAction->setShortcut( QKeySequence::Open );
    //printAction->setShortcut( QKeySequence::Print );

    // create undo stack and associated menu actions
    m_undoStack = new QUndoStack( this );
    m_undoView  = 0;
    //viewMenu->addAction( "Undo stack", this, SLOT(showUndoStack()) );
    QAction* undoAction = m_undoStack->createUndoAction( this );
    QAction* redoAction = m_undoStack->createRedoAction( this );
    undoAction->setShortcut( QKeySequence::Undo );
    redoAction->setShortcut( QKeySequence::Redo );
    //editMenu->addAction( undoAction );
    //editMenu->addAction( redoAction );

    // create toolbar, set icon size, and add actions
    //QToolBar*   toolBar = addToolBar( "Standard" );
    QStyle*     style   = this->style();
    QSize       size    = style->standardIcon(QStyle::SP_DesktopIcon).actualSize( QSize(99,99) );
    //toolBar->setIconSize( size );
    //newAction->setIcon( style->standardIcon(QStyle::SP_DesktopIcon) );
    //openAction->setIcon( style->standardIcon(QStyle::SP_DialogOpenButton) );
    //saveAction->setIcon( style->standardIcon(QStyle::SP_DialogSaveButton) );
    //previewAction->setIcon( style->standardIcon(QStyle::SP_FileDialogContentsView) );
    //printAction->setIcon( style->standardIcon(QStyle::SP_ComputerIcon) );
    //undoAction->setIcon( style->standardIcon(QStyle::SP_ArrowBack) );
    //redoAction->setIcon( style->standardIcon(QStyle::SP_ArrowForward) );
    //toolBar->addAction( newAction );
    //toolBar->addAction( openAction );
    //toolBar->addAction( saveAction );
    //toolBar->addSeparator();
    //toolBar->addAction( previewAction );
    //toolBar->addAction( printAction );
    //toolBar->addSeparator();
    //toolBar->addAction( undoAction );
    //toolBar->addAction( redoAction );

    // create scene and central widget view of scene
    m_scene               = new Scene( m_undoStack );
    QGraphicsView*   view = new QGraphicsView( m_scene );
    view->setAlignment( Qt::AlignLeft | Qt::AlignTop );
    view->setFrameStyle( 0 );
    setCentralWidget( view );

    // connect message signal from scene to showMessage slot
    connect( m_scene, SIGNAL(message(QString)), this, SLOT(showMessage(QString)) );

    // add status bar message
    statusBar()->showMessage("You are now attempting in vain to evade several murderous asteroids. Survive if possible. ");

    //sets window size by default
    setFixedSize(WINDOW_WIDTH, WINDOW_HEIGHT);
}
Beispiel #11
0
int main(int argc, char *argv[]) {
    QApplication a(argc, argv);

    // open file
    string filename = "input12800.txt";
    ifstream input;
    input.open(filename);


    // read points from file
    int N;
    int x;
    int y;

    input >> N;

    // the vector of points
    vector<Point> points;
    // a vector of pointers to the points in points
    vector<Point*> pointPointers;

    for (int i = 0; i < N; ++i) {
        input >> x >> y;
        Point* p = new Point(x, y);
        points.push_back(*p);
        pointPointers.push_back(p);
    }
    input.close();

    // setup graphical window
    QGraphicsView *view = new QGraphicsView();
    QGraphicsScene *scene = new QGraphicsScene(0, 0, SCENE_WIDTH, SCENE_HEIGHT);
    view->setScene(scene);
    // draw points to screen all at once
    render_points(scene, points);
    view->scale(1, -1); //screen y-axis is inverted
    view->resize(view->sizeHint());
    view->setWindowTitle("Extra Fast Pattern Recognition");
    view->show();
    auto begin = chrono::high_resolution_clock::now();
    //do all of this using each point as starting point
    for (int startingPoint = 0; startingPoint < N; ++startingPoint) {
        vector<PointComparison> comparisons;
        //iterate over all except the starting point. Instead of
        //checking each point if it is a starting point, iterate first
        //over all points until the starting point, and then after.
        for (int i = 0; i < startingPoint; ++i) {
            //for every point that isn't the starting point, create a PointComparison of
            //the starting point pointer and the point pointer at index i.
            comparisons.push_back(PointComparison(pointPointers[startingPoint], pointPointers[i]));
        }
        for (int i = startingPoint + 1; i < N; ++i) {
            //do the same here.
            comparisons.push_back(PointComparison(pointPointers[startingPoint], pointPointers[i]));
        }
        //sort the comparisons by slope
        sort(comparisons.begin(), comparisons.end());

        //start finding collinear lines. Create an index variable.
        int i = 0;
        //since we are checking two points ahead, and checking every point except the starting point,
        //we check from i = 0 to N-1-2 = N-3.
        while (i < N - 3) {
            //get the slopes of this index and the one two indexes away
            double slope1 = comparisons[i].slope;
            double slope2 = comparisons[i + 2].slope;
            //if they are equal, that means we have found four aligned points (including the startingPoint)!
            //Lets see if we can find more...
            //EXTRATASK E8: Because of how the list is sorted, several equal slopes in a row will be sorted
            //lexicographically, which means that the last of these points will be the upmost right point.
            //This also means that the starting point is the downmost left point if and only if it follows
            //the order of the comparison list. That is, only if it is "less" than the first point with equal
            //slope. Since we only want to draw one single line segment between these lines, we include this
            //as a condition to draw the line.
            if (slope1 == slope2 && *comparisons[0].comparePoint < *comparisons[i].thisPoint) {
                int j = i + 3;
                while (slope1 == comparisons[j].slope && j < N - 1) {
                    //we found another aligned point!
                    j++;
                }
                //okay, so the compared point at comparisons[j] was not aligned, so we will
                //just draw a line from the starting point to the one at j-1 (since that was the
                //last aligned point). We use comparisons[0] to get the starting point but
                //we could just use any element in comparisons since they all have the same
                //pointer to the starting point.
                render_line(scene, *comparisons[0].comparePoint, *comparisons[j-1].thisPoint);
                a.processEvents(); // show rendered line
                //continue searching from where the last aligned point was found.
                i = j - 1;
            } else {
                //okay, we didn't find aligned points here, increment and continue.
                i++;
            }
        }
    }
    //And we're done! Pause the timer.
    auto end = chrono::high_resolution_clock::now();
    cout << "Computing line segments took "
         << std::chrono::duration_cast<chrono::milliseconds>(end - begin).count()
         << " milliseconds." << endl;
    return a.exec();
}
Beispiel #12
0
void tst_QGraphicsLayout::automaticReparenting()
{
    QGraphicsView view;
    QGraphicsScene scene;
    {
        QGraphicsWidget *w = new QGraphicsWidget();
        QGraphicsLinearLayout *l = new QGraphicsLinearLayout(w);
        QGraphicsWidget *w1 = new QGraphicsWidget;
        l->addItem(w1);
        scene.addItem(w);
        QCOMPARE(w1->parentWidget(), w);
        delete w;
    }
    {
        QGraphicsWidget *w = new QGraphicsWidget();
        QGraphicsLinearLayout *l = new QGraphicsLinearLayout(w);
        QGraphicsWidget *w1 = new QGraphicsWidget;
        l->addItem(w1);
        scene.addItem(w);
        QCOMPARE(w1->parentWidget(), w);

        QGraphicsWidget *ww = new QGraphicsWidget();
        QGraphicsLinearLayout *l1 = new QGraphicsLinearLayout(ww);
#if !defined(Q_OS_MAC) && defined(QT_DEBUG)
        QTest::ignoreMessage(QtWarningMsg, "QGraphicsLayout::addChildLayoutItem: QGraphicsWidget \"\""
                             " in wrong parent; moved to correct parent");
#endif
        l1->addItem(w1);
        QCOMPARE(w1->parentWidget(), ww);
        delete w;
    }

    QGraphicsWidget *window = new QGraphicsWidget();
    scene.addItem(window);
    view.show();
    QGraphicsLinearLayout *l1 = new QGraphicsLinearLayout();
    QGraphicsWidget *w1 = new QGraphicsWidget();
    l1->addItem(w1);
    QGraphicsWidget *w2 = new QGraphicsWidget();
    l1->addItem(w2);
    QCOMPARE(w1->parentItem(), static_cast<QGraphicsItem*>(0));
    QCOMPARE(w2->parentItem(), static_cast<QGraphicsItem*>(0));
    scene.addItem(w1);
    QCOMPARE(w1->parentItem(), static_cast<QGraphicsItem*>(0));
    window->setLayout(l1);
    QCOMPARE(w1->parentItem(), static_cast<QGraphicsItem*>(window));
    QCOMPARE(w2->parentItem(), static_cast<QGraphicsItem*>(window));

    // Sublayouts
    QGraphicsLinearLayout *l2 = new QGraphicsLinearLayout();
    QGraphicsWidget *w3 = new QGraphicsWidget();
    l2->addItem(w3);
    QGraphicsWidget *w4 = new QGraphicsWidget();
    l2->addItem(w4);
    QGraphicsLinearLayout *l3 = new QGraphicsLinearLayout();
    l2->addItem(l3);
    QGraphicsWidget *window2 = new QGraphicsWidget();
    scene.addItem(window2);
    window2->setLayout(l2);

    QCOMPARE(w3->parentItem(), static_cast<QGraphicsItem*>(window2));
    QCOMPARE(w4->parentItem(), static_cast<QGraphicsItem*>(window2));

    // graphics item with another parent
    QGraphicsLinearLayout *l5 = new QGraphicsLinearLayout();
    l5->addItem(w1);
    l5->addItem(w2);
    QCOMPARE(w1->parentItem(), static_cast<QGraphicsItem*>(window));
    QCOMPARE(w2->parentItem(), static_cast<QGraphicsItem*>(window));
    QGraphicsLinearLayout *l4 = new QGraphicsLinearLayout();
    l4->addItem(l5);
    QGraphicsWidget *window3 = new QGraphicsWidget();
    scene.addItem(window3);
    window3->setLayout(l4);

    QCOMPARE(w1->parentItem(), static_cast<QGraphicsItem*>(window3));
    QCOMPARE(w2->parentItem(), static_cast<QGraphicsItem*>(window3));
}
Beispiel #13
0
void DDSWidget::enableRichGUI() {
	QWidget *m_objWidget = new QWidget(this);
	QGraphicsScene *entireScene = new QGraphicsScene(0, 0, 800, 600);
	QGraphicsView *entireView = new QGraphicsView(m_objWidget);
	QPixmap obj1 = QPixmap(":/bg.png");
	QBrush obj2 = QBrush(obj1);
	obj2.setStyle(Qt::TexturePattern);
	obj2.setTexture(obj1);
	entireView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
	entireView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
	entireView->setFrameStyle(QFrame::Plain | QFrame::Sunken);
	entireView->setBackgroundBrush(obj2);
	entireView->setScene(entireScene);
	entireView->setGeometry(0, 0, 800, 600);

	ui->grpBarRep->setParent(m_objWidget);
	ui->grpDDS->setParent(m_objWidget);
	ui->grpDrive->setParent(m_objWidget);
	ui->grpGeneral->setParent(m_objWidget);
	ui->grpPPT->setParent(m_objWidget);
	ui->grpTimeBase->setParent(m_objWidget);
	ui->grpAD5293->setParent(m_objWidget);

	ui->grpGeneral->setGeometry(10, 10, 280, 121);
        ui->grpTimeBase->setGeometry(310, 10, 471, 187);
        ui->grpDDS->setGeometry(10, 200, 280, 320);
        ui->grpPPT->setGeometry(310, 200, 470, 130);
        ui->grpDrive->setGeometry(310, 460, 470, 60);
        ui->grpBarRep->setGeometry(310, 333, 470, 130);
        ui->grpAD5293->setGeometry(10, 130, 281, 71);

	m_objLE_ADDR->setStyleSheet(
			"border-width: 2px;border-style: outset;border-color: gray; border-radius: 10px;  padding: 0 8px;     background: black;     selection-background-color: yellow;   color:white;     font: bold 14px;");
	m_objLE_DATA->setStyleSheet(
			"border-width: 2px;border-style: outset;border-color: gray; border-radius: 10px;  padding: 0 8px;     background: black;     selection-background-color: yellow;   color:white;     font: bold 14px;");
	m_objLE_BTU->setStyleSheet(
			"border-width: 2px;border-style: outset;border-color: gray; border-radius: 10px;  padding: 0 8px;     background: black;     selection-background-color: yellow;   color:white;     font: bold 14px;");
	m_objLE_BD->setStyleSheet(
			"border-width: 2px;border-style: outset;border-color: gray; border-radius: 10px;  padding: 0 8px;     background: black;     selection-background-color: yellow;   color:white;     font: bold 14px;");
	m_objLE_OPFreq->setStyleSheet(
			"border-width: 2px;border-style: outset;border-color: gray; border-radius: 10px;  padding: 0 8px;     background: black;     selection-background-color: yellow;   color:white;     font: bold 14px;");
	m_objLE_OPPhase->setStyleSheet(
			"border-width: 2px;border-style: outset;border-color: gray; border-radius: 10px;  padding: 0 8px;     background: black;     selection-background-color: yellow;   color:white;     font: bold 14px;");
	m_objLE_STDLY->setStyleSheet(
			"border-width: 2px;border-style: outset;border-color: gray; border-radius: 10px;  padding: 0 8px;     background: black;     selection-background-color: yellow;   color:white;     font: bold 14px;");
	m_objLE_WDP->setStyleSheet(
                "QLineEdit{border-width: 2px;border-style: outset;border-color: gray; border-radius: 10px;  padding: 0 8px;     background: black;     selection-background-color: yellow;   color:white;     font: bold 14px;}QLineEdit::disabled{border-width: 2px;border-style: outset;border-color: gray; border-radius: 10px;  padding: 0 8px;     background: dark gray;     selection-background-color: yellow;   color:white;     font: bold 14px;}");
	m_objLE_STOPDLY->setStyleSheet(
			"border-width: 2px;border-style: outset;border-color: gray; border-radius: 10px;  padding: 0 8px;     background: black;     selection-background-color: yellow;   color:white;     font: bold 14px;");
	m_objLE_DPC->setStyleSheet(
			"border-width: 2px;border-style: outset;border-color: gray; border-radius: 10px;  padding: 0 8px;     background: black;     selection-background-color: yellow;   color:white;     font: bold 14px;");
        m_objLE_DDSCycle->setStyleSheet(
                "QLineEdit{border-width: 2px;border-style: outset;border-color: gray; border-radius: 10px;  padding: 0 8px;     background: black;     selection-background-color: yellow;   color:white;     font: bold 14px;}QLineEdit::disabled{border-width: 2px;border-style: outset;border-color: gray; border-radius: 10px;  padding: 0 8px;     background: dark gray;     selection-background-color: yellow;   color:white;     font: bold 14px;}");
        m_objLE_DDSVoltage->setStyleSheet(
                "QLineEdit{border-width: 2px;border-style: outset;border-color: gray; border-radius: 10px;  padding: 0 8px;     background: black;     selection-background-color: yellow;   color:white;     font: bold 14px;}QLineEdit::disabled{border-width: 2px;border-style: outset;border-color: gray; border-radius: 10px;  padding: 0 8px;     background: dark gray;     selection-background-color: yellow;   color:white;     font: bold 14px;}");
	ui->leFS->setStyleSheet(
			"border-width: 2px;border-style: outset;border-color: gray; border-radius: 10px;  padding: 0 8px;     background: gray;     selection-background-color: yellow;   color:yellow;     font: bold 14px;");
	ui->leOutputTime->setStyleSheet(
			"border-width: 2px;border-style: outset;border-color: gray; border-radius: 10px;  padding: 0 8px;     background: gray;     selection-background-color: yellow;   color:yellow;     font: bold 14px;");
	ui->leTickFrequency->setStyleSheet(
			"border-width: 2px;border-style: outset;border-color: gray; border-radius: 10px;  padding: 0 8px;     background: gray;     selection-background-color: yellow;   color:yellow;     font: bold 14px;");
	ui->leTickTime->setStyleSheet(
			"border-width: 2px;border-style: outset;border-color: gray; border-radius: 10px;  padding: 0 8px;     background: gray;     selection-background-color: yellow;   color:yellow;     font: bold 14px;");

}
Beispiel #14
0
FenPrincipale::FenPrincipale()
{				
       // setFixedSize(1200,800); // Dimensions fixées à 850x480px
		
		QGridLayout *layout0 = new QGridLayout; // c le layout de base de la page1
		QGraphicsScene *scene =  new QGraphicsScene; 
		QGraphicsView *vue = new QGraphicsView(scene,this);
	
		scene->setSceneRect(0,0,mapLargeur+50,mapHauteur+50); // taille de la scene
		vue->setRenderHints(QPainter::Antialiasing|QPainter::TextAntialiasing);    
		vue->setFixedSize(mapLargeur+100,mapHauteur+100); //taille de la vue
    
		//Mise en place de la map 
		QPixmap map_im ; 
		map_im.load("map.png");
		map=scene->addPixmap(map_im);
		map->setPos(0,0);
		map->setZValue(-1);
		
		//Rectangle test_debug
		QRect rectangle1(15,15,618,418);
		scene->addRect(rectangle1);
		//rectangle1.moveCenter(QPoint(0,0)); // met le centre au centre
		
		//Création de l'origine
		QRect rectangle(0,0,10,10);
		rectangle.moveCenter(QPoint(0,0)); // met le centre au centre
		origine=scene->addRect(rectangle);
		origine->setPos(map_im.width()/2,map_im.height()/2);// au centre de l'image
		
        //Mise en place de du robot
		QPixmap robot_im ; 
		robot_im.load("petit_robot.png");
		robot=scene->addPixmap(robot_im);
		robot->setZValue(2);// au dessus de l'image carte 2>-1
		robot->setOffset(-robot_im.width()/2,-robot_im.height()/2); // origine du robot au centre
		robot->setPos(origine->x(),origine->y());//placer au centre du palteau
		
        //Mise en place de l'obstacle
        
        QPen pen(Qt::black, 1, Qt::SolidLine);
		QBrush brush(Qt::black);
		//scene.addRect(rectangle, pen, brush);
        
        obstacle = scene->addEllipse(0,0,15,15,pen,brush);
        obstacle->setZValue(1);
        obstacle->setPos(origine->x(),origine->y());
        
        obstacle2 = scene->addEllipse(0,0,15,15,pen,brush);
        obstacle2->setZValue(1);
        obstacle2->setPos(origine->x(),origine->y());
        
        //Ajout au layout principale puis à la fenetre
        layout0->addWidget(vue, 0,0);
        setLayout(layout0);	
         
         //Configuration du Timer pas utiliser (debug)
        timer = new QTimer(this);
        // timer->start(1000);   		
         
         //Connection des Signaux/Solts
         connect( timer, SIGNAL(timeout()), this, SLOT(timerOut()) );
         
         //Pacement par defaut
         
         //modifPosition(robot,-750,-1250,90);
         modifPosition(robot,-750,0,0);
         testPosObs(obstacle,100,90);
         
}
void ULLineEditor::keyPressEvent ( QKeyEvent * event )
{
	if ( event->key() == Qt::Key_Return )
	{
		validateLine();
		return;
	}
	if ( event->key() == Qt::Key_G && event->modifiers().testFlag ( Qt::ControlModifier ))
	{
		pushLastGlyphAtFirstOfNextLine();
		return;
	}
	if ( event->key() == Qt::Key_P&& event->modifiers().testFlag ( Qt::ControlModifier ) )
	{
		insertAtLastFirstGlyphOfNextLine();
		return;
	}
	if ( event->key() == Qt::Key_G && event->modifiers().testFlag ( Qt::ShiftModifier ))
	{
		insertAtFirstLastGlyphFromPrevLine();
		pushLastGlyphAtFirstOfNextLine();
		return;
	}
	if ( event->key() == Qt::Key_P&& event->modifiers().testFlag ( Qt::ShiftModifier ) )
	{
		pushFirstGlyphAtLastOfPrevLine();
		insertAtLastFirstGlyphOfNextLine();
		return;
	}
	if ( event->key() == Qt::Key_G )
	{
		pushFirstGlyphAtLastOfPrevLine();
		return;
	}
	if ( event->key() == Qt::Key_P )
	{
		insertAtFirstLastGlyphFromPrevLine();
		return;
	}
	

	QList<QGraphicsItem*> it = selectedItems();
	if ( it.isEmpty() && event->modifiers().testFlag ( Qt::ControlModifier )  && event->modifiers().testFlag ( Qt::ShiftModifier ) )
	{
		switch ( event->key() )
		{
			case Qt::Key_Right : slotJustifyItsVeryBadInterletter ( 0.005 );
				break;
			case Qt::Key_Left : slotJustifyItsVeryBadInterletter ( -0.005 );
				break;
			default:break;
		}

	}
	else if ( it.isEmpty() && event->modifiers().testFlag ( Qt::ControlModifier ) )
	{
		switch ( event->key() )
		{
			case Qt::Key_Right : slotJustifyBlanks ( 0.01 );
				break;
			case Qt::Key_Left : slotJustifyBlanks ( -0.01 );
				break;
			default:break;
		}

	}
	else if ( it.isEmpty() )
	{
		QGraphicsView * v = views().first();
		switch ( event->key() )
		{
			case Qt::Key_Up: v->scale ( 1.2,1.2 );
				break;
			case Qt::Key_Down : v->scale ( 1.0/1.2,1.0/1.2 );
				break;
			case Qt::Key_Right : slotJustifyBlanks ( 0.1 );
				break;
			case Qt::Key_Left : slotJustifyBlanks ( -0.1 );
				break;
			default:break;
		}

	}
	else
	{
        if ( (event->key() == Qt::Key_Delete) || (event->key() == Qt::Key_Backslash) )
		{
			for ( uint i = 0; i < it.count();++i )
			{
				removeItem ( it[i] );
				glyphs.removeAll ( static_cast<ULGlyphItem*> ( it[i] ) );
			}
		}
		else if ( event->key() == Qt::Key_E )
		{
			wantEdit ( static_cast<ULGlyphItem*> ( it.first() ) );
		}

		else
		{
			for ( uint i = 0; i < it.count();++i )
				static_cast<ULGlyphItem*> ( it[i] )->keyForeign ( event );

		}
// 		previewLine();
	}
}
void UBWidgetUniboardAPI::ProcessDropEvent(QGraphicsSceneDragDropEvent *event)
{
    const QMimeData *pMimeData = event->mimeData();

    QString destFileName;
    QString contentType;
    bool downloaded = false;

    QGraphicsView *tmpView = mGraphicsWidget->scene()->views().at(0);
    QPoint dropPoint(mGraphicsWidget->mapFromScene(tmpView->mapToScene(event->pos().toPoint())).toPoint());
    Qt::DropActions dropActions = event->possibleActions();
    Qt::MouseButtons dropMouseButtons = event->buttons();
    Qt::KeyboardModifiers dropModifiers = event->modifiers();
    QMimeData *dropMimeData = new QMimeData;
    qDebug() << event->possibleActions();


    if (pMimeData->hasHtml()) { //Dropping element from web browser
        QString qsHtml = pMimeData->html();
        QString url = UBApplication::urlFromHtml(qsHtml);

        if(!url.isEmpty()) {
            QString str = "test string";

            QMimeData mimeData;
            mimeData.setData(tMimeText, str.toLatin1());

            sDownloadFileDesc desc;
            desc.dest = sDownloadFileDesc::graphicsWidget;
            desc.modal = true;
            desc.srcUrl = url;
            desc.currentSize = 0;
            desc.name = QFileInfo(url).fileName();
            desc.totalSize = 0; // The total size will be retrieved during the download

            desc.dropPoint = event->pos().toPoint(); //Passing pure event point. No modifications
            desc.dropActions = dropActions;
            desc.dropMouseButtons = dropMouseButtons;
            desc.dropModifiers = dropModifiers;

            registerIDWidget(UBDownloadManager::downloadManager()->addFileToDownload(desc));

        }

    } else  if (pMimeData->hasUrls()) { //Local file processing
        QUrl curUrl = pMimeData->urls().first();
        QString sUrl = curUrl.toString();

        if (sUrl.startsWith("file://") || sUrl.startsWith("/")) {
            QString fileName = curUrl.toLocalFile();
            QString extention = UBFileSystemUtils::extension(fileName);
            contentType = UBFileSystemUtils::mimeTypeFromFileName(fileName);

            if (supportedTypeHeader(contentType)) {
                destFileName = getObjDir() + QUuid::createUuid().toString() + "." + extention;

                if (!UBFileSystemUtils::copyFile(fileName, destFileName)) {
                    qDebug() << "can't copy from" << fileName << "to" << destFileName;
                    return;
                }
                downloaded = true;

            }
        }
    }
    qDebug() << destFileName;
    QString mimeText = createMimeText(downloaded, contentType, destFileName);
    dropMimeData->setData(tMimeText, mimeText.toLatin1());

    event->setMimeData(dropMimeData);
}
void ScreenshotService::getScreenshot(TasCommandModel& model, TasResponse& response)
{
    QListIterator<TasTarget*> i(model.targetList());
    QString errorMsg = PARSE_ERROR;
    QImage screenshot;
    QString pictureFormat = "PNG";
    while (i.hasNext()) {
        TasTarget* commandTarget = i.next();
        QString targetId = commandTarget->id();
        QString targetType = commandTarget->type();
        TasCommand* command = commandTarget->findCommand("Screenshot");

        // are required for command completion
        if (targetId.isEmpty() || targetType.isEmpty() || !command) {
            continue;
        }

        if (!command->parameter("format").isEmpty()) {
            pictureFormat = command->parameter("format");
        }

        if (!isFormatSupported(pictureFormat)) {
            errorMsg = "Given format " + pictureFormat + "is not supported. Supported formats are: PNG, JPEG and BMP.";
            break;
        }

        bool draw = (command->parameter("draw") == "true");

        QWidget* widget = 0;
        QQuickWindow* qtQuickWindow = 0;
        WId winId = 0;
        QRect rect(0,0,-1,-1);

        errorMsg = "Taking screenshot failed!";

        if (targetType == TYPE_GRAPHICS_VIEW) {
            //TasLogger::logger()->debug("TYPE_GRAPHICS_VIEW Target id:" + targetId);
            QGraphicsItem* item = findGraphicsItem(targetId);

            if (item) {
                QGraphicsView* view = getViewForItem(item);
                if(view) {
                    ItemLocationDetails locationDetails = TestabilityUtils::getItemLocationDetails(item);
                    rect = QRect(locationDetails.windowPoint.x(),
                                 locationDetails.windowPoint.y(),
                                 locationDetails.width,
                                 locationDetails.height);

                    if (draw) {
                        widget = view->window();
                    } else {
                        winId = view->window()->winId();
                    }
                } else {
                    errorMsg = "Could not find a GraphicsView for the GraphicsItem!";
                }
            } else {
                errorMsg = "Could not find the GraphicsItem!";
            }
        } else if (targetType == TYPE_STANDARD_VIEW) {
            //TasLogger::logger()->debug("TYPE_STANDARD_VIEW about to find widget Target id:" + targetId);
            widget = findWidget(targetId);

            if (widget) {
                if ((widget->isWindow() && !draw) || widget->inherits("QDesktopWidget")) {
                    winId = widget->winId();
                    widget = 0;
                } else if (!draw) {
                    QPoint point = widget->mapToGlobal(QPoint(0,0));
                    QPoint windowPoint = widget->window()->mapFromGlobal(point);

                    rect = QRect(windowPoint.x(),
                                 windowPoint.y(),
                                 widget->rect().width(),
                                 widget->rect().width());
                    winId = widget->window()->winId();
                    widget = 0;
                }
            } else {
                TasLogger::logger()->debug("ScreenshotService::executeService application has no visible ui!");
                errorMsg = "Application has no visible ui!";
            }
        } else if (targetType == TYPE_QSCENEGRAPH) {
            QQuickItem* item = TestabilityUtils::findQuickItem(targetId);

            if (item) {
                QPointF offset = item->mapToScene(QPointF(0,0));
                rect = QRect(-offset.x(), -offset.y(), item->width(), item->height());
                qtQuickWindow = item->window();
            }
        } else {
            //TasLogger::logger()->debug("TYPE_APPLICATION_VIEW about to find application window Target id:" + targetId);
            widget = getApplicationWidget();

            if (!widget) {
                QWindow *window = getApplicationWindow();
                //in case no window false, return the desktop
                qtQuickWindow = qobject_cast<QQuickWindow *>(window);

                if (!window) {
                    widget = qApp->desktop();
                }
            }
        }

        if (widget) {
            screenshot = widget->grab(rect).toImage();

            if (!screenshot.isNull()) {
                screenshot.setText("tas_id", objectId(widget));
            }
        } else if (qtQuickWindow) {
            screenshot = qtQuickWindow->grabWindow();
            if (!screenshot.isNull()) {
                screenshot.setText("tas_id", objectId(qtQuickWindow));
            }
        } else if (winId) {
            screenshot = QPixmap::grabWindow(winId, rect.x(), rect.y(), rect.width(), rect.height()).toImage();

            if (!screenshot.isNull()) {
                screenshot.setText("tas_id", QString::number(winId));
            }
        }

        break;
    }

    if (!screenshot.isNull()) {
        QByteArray bytes;
        QBuffer buffer(&bytes);
        buffer.open(QIODevice::WriteOnly);
        screenshot.save(&buffer, pictureFormat.toLatin1());
        response.setData(bytes);
        buffer.close();
    } else {
        response.setErrorMessage(errorMsg);
    }

}
Beispiel #18
0
void QgsPaperGrid::paint( QPainter* painter, const QStyleOptionGraphicsItem* itemStyle, QWidget* pWidget )
{
  Q_UNUSED( itemStyle );
  Q_UNUSED( pWidget );

  //draw grid
  if ( mComposition )
  {
    if ( mComposition->gridVisible() && mComposition->plotStyle() ==  QgsComposition::Preview
         && mComposition->snapGridResolution() > 0 )
    {
      int gridMultiplyX = static_cast< int >( mComposition->snapGridOffsetX() / mComposition->snapGridResolution() );
      int gridMultiplyY = static_cast< int >( mComposition->snapGridOffsetY() / mComposition->snapGridResolution() );
      double currentXCoord = mComposition->snapGridOffsetX() - gridMultiplyX * mComposition->snapGridResolution();
      double currentYCoord;
      double minYCoord = mComposition->snapGridOffsetY() - gridMultiplyY * mComposition->snapGridResolution();

      painter->save();
      //turn of antialiasing so grid is nice and sharp
      painter->setRenderHint( QPainter::Antialiasing, false );

      if ( mComposition->gridStyle() == QgsComposition::Solid )
      {
        painter->setPen( mComposition->gridPen() );

        //draw vertical lines
        for ( ; currentXCoord <= rect().width(); currentXCoord += mComposition->snapGridResolution() )
        {
          painter->drawLine( QPointF( currentXCoord, 0 ), QPointF( currentXCoord, rect().height() ) );
        }

        //draw horizontal lines
        currentYCoord = minYCoord;
        for ( ; currentYCoord <= rect().height(); currentYCoord += mComposition->snapGridResolution() )
        {
          painter->drawLine( QPointF( 0, currentYCoord ), QPointF( rect().width(), currentYCoord ) );
        }
      }
      else //'Dots' or 'Crosses'
      {
        QPen gridPen = mComposition->gridPen();
        painter->setPen( gridPen );
        painter->setBrush( QBrush( gridPen.color() ) );
        double halfCrossLength = 1;
        if ( mComposition->gridStyle() == QgsComposition::Dots )
        {
          //dots are actually drawn as tiny crosses a few pixels across
          //check QGraphicsView to get current transform
          if ( scene() )
          {
            QList<QGraphicsView*> viewList = scene()->views();
            if ( !viewList.isEmpty() )
            {
              QGraphicsView* currentView = viewList.at( 0 );
              if ( currentView->isVisible() )
              {
                //set halfCrossLength to equivalent of 1 pixel
                halfCrossLength = 1 / currentView->transform().m11();
              }
            }
          }
        }
        else if ( mComposition->gridStyle() == QgsComposition::Crosses )
        {
          halfCrossLength = mComposition->snapGridResolution() / 6;
        }

        for ( ; currentXCoord <= rect().width(); currentXCoord += mComposition->snapGridResolution() )
        {
          currentYCoord = minYCoord;
          for ( ; currentYCoord <= rect().height(); currentYCoord += mComposition->snapGridResolution() )
          {
            painter->drawLine( QPointF( currentXCoord - halfCrossLength, currentYCoord ), QPointF( currentXCoord + halfCrossLength, currentYCoord ) );
            painter->drawLine( QPointF( currentXCoord, currentYCoord - halfCrossLength ), QPointF( currentXCoord, currentYCoord + halfCrossLength ) );
          }
        }
      }
      painter->restore();
    }
  }
}
void MInputContext::setFocusWidget(QWidget *focused)
{
    QObject *focusedObject = focused;
    QGraphicsItem *focusItem = 0;
    qDebug() << "MInputContext" << "in" << __PRETTY_FUNCTION__ << focused;
    QInputContext::setFocusWidget(focused);

    // get detailed focus information from inside qgraphicsview
    QGraphicsView *graphicsView = qobject_cast<QGraphicsView *>(focusWidget());

    if (graphicsView && graphicsView->scene()) {
        focusItem = graphicsView->scene()->focusItem();

        if (focusItem) {
            focusedObject = dynamic_cast<QObject *>(focusItem);
        }
    }

    const QMap<QString, QVariant> stateInformation = getStateInformation();
    if (focused) {
        // for non-null focus widgets, we'll have this context activated
        if (!active) {
            imServer->activateContext();
            active = true;

#ifdef HAVE_MEEGOTOUCH
            // Notify whatever application's orientation is currently.
            notifyOrientationChanged(currOrientation);
#endif
        }

        imServer->updateWidgetInformation(stateInformation, true);

        // check if copyable text is selected
        Qt::InputMethodQuery query = Qt::ImCurrentSelection;
        QVariant queryResult = focused->inputMethodQuery(query);
        if (queryResult.isValid()) {
            copyAvailable = !queryResult.toString().isEmpty();
        }

        if (focusItem) {
            copyAllowed = !(focusItem->inputMethodHints() & Qt::ImhHiddenText);
        } else {
            copyAllowed = !(focused->inputMethodHints() & Qt::ImhHiddenText);
        }

        pasteAvailable = !QApplication::clipboard()->text().isEmpty();

        connect(QApplication::clipboard(), SIGNAL(dataChanged()), this, SLOT(handleClipboardDataChange()), Qt::UniqueConnection);
    } else {
        copyAvailable = false;
        copyAllowed = false;
        imServer->updateWidgetInformation(stateInformation, true);

        disconnect(QApplication::clipboard(), SIGNAL(dataChanged()), this, 0);
    }

    // show or hide Copy/Paste button on input method server
    notifyCopyPasteState();

    if (inputPanelState == InputPanelShowPending && focused) {
        imServer->showInputMethod();
        inputPanelState = InputPanelShown;
    }

    if (connectedObject) {
        connectedObject->disconnect(this);
        connectedObject = 0;
    }

    if (focusedObject && focusedObject->metaObject()) {
        if (focusedObject->metaObject()->indexOfSignal("copyAvailable(bool)") != -1) {
            // for MTextEdit
            connect(focusedObject, SIGNAL(copyAvailable(bool)),
                    this, SLOT(handleCopyAvailabilityChange(bool)));
            connectedObject = focusedObject;
        } else if (focusedObject->metaObject()->indexOfSignal("selectedTextChanged()") != -1) {
Beispiel #20
0
void MainWindow::handleJouer() {
    m_jeux = new Jeux(2);
    QGraphicsView* view = new QGraphicsView(m_jeux->getPlateau());
    this->hide();
    view->show();
}
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/

//! [0]
QGraphicsScene scene;
scene.addText("Hello, world!");

QGraphicsView view(&scene);
view.show();
//! [0]


//! [1]
QGraphicsScene scene;
scene.addRect(QRectF(-10, -10, 20, 20));

QGraphicsView view(&scene);
view.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
view.show();
//! [1]


//! [2]
Beispiel #22
0
bool MouseEventEater::eventFilter(QObject *obj, QEvent *event)
{
    QString theObjName = obj->objectName();
    if((theObjName != "" )&(event->type() != QEvent::None)&(event->type() != 39)&(event->type() != 69)&(event->type() != 74)&(event->type() != 75)&(event->type() != 170))
    {
        //        int test = event->type();
        QMouseEvent *mouseEvent;
        int slot = 0;
        slot = (atoi(theObjName.right(2).toStdString().c_str()))-1;
        frmCurSlotNum = slot;
        bool todisplay = false;
        switch(event->type())
        {
        case QEvent::MouseButtonPress:
            //    case QEvent::MouseButtonDblClick:
            mouseEvent = static_cast<QMouseEvent *>(event);
            switch(mouseEvent->button())
            {
            case Qt::LeftButton:
                theSlot = obj;
                switch(theObjName.toStdString()[2])
                {
                case 'B':
                    if(theObjName.mid(2,5) == "BoxSl")
                    {
                        apkm = &(frmCurBox->pokemon[slot]);
                        ispartypkm_ = false;
                        todisplay = true;
                    }
                    break;
                case 'P':
                    apkm = &(frmParty->pokemon[slot].pkm_data);
                    ispartypkm_ = true;
                    todisplay = true;
                    break;
                default:
                    QPixmap extmarkingspix;
                    int selection = 0;
                    if(theObjName.right(theObjName.length() - 2).toStdString() == "Circle"){
                        temppkm->markings.circle = !(temppkm->markings.circle);
                        selection = (int)Markings::circle;
                        extmarkingspix = getmarkingimage(Markings::circle, temppkm->markings.circle);
                    }
                    if(theObjName.right(theObjName.length() - 2).toStdString() == "Triangle"){
                        temppkm->markings.triangle = !(temppkm->markings.triangle);
                        selection = (int)Markings::triangle;
                        extmarkingspix = getmarkingimage(Markings::triangle, temppkm->markings.triangle);
                    }
                    if(theObjName.right(theObjName.length() - 2).toStdString() == "Square"){
                        temppkm->markings.square = !(temppkm->markings.square);
                        selection = (int)Markings::square;
                        extmarkingspix = getmarkingimage(Markings::square, temppkm->markings.square);
                    }
                    if(theObjName.right(theObjName.length() - 2).toStdString() == "Star"){
                        temppkm->markings.star = !(temppkm->markings.star);
                        selection = (int)Markings::star;
                        extmarkingspix = getmarkingimage(Markings::star, temppkm->markings.star);
                    }
                    if(theObjName.right(theObjName.length() - 2).toStdString() == "Diamond"){
                        temppkm->markings.diamond = !(temppkm->markings.diamond);
                        selection = (int)Markings::diamond;
                        extmarkingspix = getmarkingimage(Markings::diamond, temppkm->markings.diamond);
                    }
                    if(theObjName.right(theObjName.length() - 2).toStdString() == "Heart"){
                        temppkm->markings.heart = !(temppkm->markings.heart);
                        selection = (int)Markings::heart;
                        extmarkingspix = getmarkingimage(Markings::heart, temppkm->markings.heart);
                    }
                    QGraphicsScene * themarkingsscene = (QGraphicsScene*)extmarkingsscene;
                    themarkingsscene = new QGraphicsScene();
                    themarkingsscene->addPixmap(extmarkingspix);
                    QGraphicsView * themarkingsgraphics = (QGraphicsView*)obj;
                    themarkingsgraphics->setScene(themarkingsscene);
                    break;
                }
                if((apkm->species != 0) && todisplay)
                {
                    //                    pview->setWindowTitle(QString::fromStdWString(getpkmnickname(apkm)));
                    pview->setPKM(apkm,frmCurBoxNum, ispartypkm_);
                    pview->displayPKM();
                    pview->show();
                }
                break;
            default:
                break;
            }
            break;
            //        case QEvent::MouseButtonDblClick:
            //            test.setText("Test");
            //            test.show();
            //            break;
        case QEvent::ContextMenu:
            if(theObjName.mid(2,5) == "BoxSl")
            {
                apkm = &(frmCurBox->pokemon[slot]);
                //                send_rightButtonClicked(mouseEvent->globalPos());
                QMenu *menu = new QMenu(static_cast<QWidget*>(this->parent()));
                menu->addAction(new QAction("Delete",static_cast<QWidget*>(this->parent())));
                //    connect(mouseEventEater, SIGNAL(send_rightButtonClicked(const QPoint&)),
                //                this, SLOT(rightButtonClicked(const QPoint&)));
//                connect(menu,SIGNAL(triggered()),static_cast<QWidget*>(this->parent()),
//                        SLOT(MouseEventEater::test(apkm)));
                connect(static_cast<QWidget*>(this->parent()),
                        SIGNAL ( customContextMenuRequested(QPoint) ),
                                static_cast<QWidget*>(this->parent()),
                        SLOT ( test(apkm) ) );
                menu->exec(QCursor::pos());
            }
            break;
        default:
            return QObject::eventFilter(obj, event);
            break;
        }
    }
    else
    {
        if(event->type() == QEvent::MouseButtonPress)
        {
            int slot = obj->property("Index").toInt();
            boxViewer->changebox(slot);
        }
        return false;
    }
    return false;
}
Beispiel #23
0
void MiniMap::updatePosition()
{
	QGraphicsView* parent = static_cast<QGraphicsView*> (parentWidget());

	move(0,parent->viewport()->height() - height() + 2*frameWidth());
}
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QGraphicsScene *scene = new QGraphicsScene();

    Widget *a = new Widget(Qt::blue, Qt::white, "a");
    a->setPreferredSize(100, 100);
    Widget *b = new Widget(Qt::green, Qt::black, "b");
    b->setPreferredSize(100, 100);
    Widget *c = new Widget(Qt::red, Qt::black, "c");
    c->setPreferredSize(100, 100);

    QGraphicsAnchorLayout *layout = new QGraphicsAnchorLayout();
/*
    //! [adding a corner anchor in two steps]
    layout->addAnchor(a, Qt::AnchorTop, layout, Qt::AnchorTop);
    layout->addAnchor(a, Qt::AnchorLeft, layout, Qt::AnchorLeft);
    //! [adding a corner anchor in two steps]
*/
    //! [adding a corner anchor]
    layout->addCornerAnchors(a, Qt::TopLeftCorner, layout, Qt::TopLeftCorner);
    //! [adding a corner anchor]

    //! [adding anchors]
    layout->addAnchor(b, Qt::AnchorLeft, a, Qt::AnchorRight);
    layout->addAnchor(b, Qt::AnchorTop, a, Qt::AnchorBottom);
    //! [adding anchors]

    // Place a third widget below the second.
    layout->addAnchor(b, Qt::AnchorBottom, c, Qt::AnchorTop);

/*
    //! [adding anchors to match sizes in two steps]
    layout->addAnchor(b, Qt::AnchorLeft, c, Qt::AnchorLeft);
    layout->addAnchor(b, Qt::AnchorRight, c, Qt::AnchorRight);
    //! [adding anchors to match sizes in two steps]
*/

    //! [adding anchors to match sizes]
    layout->addAnchors(b, c, Qt::Horizontal);
    //! [adding anchors to match sizes]

    // Anchor the bottom-right corner of the third widget to the bottom-right
    // corner of the layout.
    layout->addCornerAnchors(c, Qt::BottomRightCorner, layout, Qt::BottomRightCorner);

    QGraphicsWidget *w = new QGraphicsWidget(0, Qt::Window | Qt::CustomizeWindowHint | Qt::WindowTitleHint);
    w->setPos(20, 20);
    w->setMinimumSize(100, 100);
    w->setPreferredSize(320, 240);
    w->setLayout(layout);
    w->setWindowTitle(QApplication::translate("simpleanchorlayout", "QGraphicsAnchorLayout in use"));
    scene->addItem(w);

    QGraphicsView *view = new QGraphicsView();
    view->setScene(scene);
    view->setWindowTitle(QApplication::translate("simpleanchorlayout", "Simple Anchor Layout"));
    view->resize(360, 320);
    view->show();

    return app.exec();
}
void MultiTouchListener::handleEvent( TUIO::TuioCursor* tcur,
                                      const QEvent::Type eventType )
{
    QGraphicsView* view = _graphicsViewProxy->getGraphicsView();
    if( !view )
        return;

    const QPoint& viewPos = view->mapToGlobal( view->pos());
    const QRectF& sceneRect = view->sceneRect();
    const int viewWidth = view->geometry().width();
    const int viewHeight = view->geometry().height();

    const qreal w = viewWidth / sceneRect.width();
    const qreal h = viewHeight / sceneRect.height();
    const int x = qreal(viewWidth - w) * .5;
    const int y = qreal(viewHeight - h) * .5;
    const QPoint sceneOffset( x, y );

    const QPointF normPos( tcur->getX(), tcur->getY( ));
    const QPoint pos( w * normPos.x(), h * normPos.y( ));
    const QPoint screenPos( viewPos + sceneOffset + pos );

    const QPoint wallPos( g_configuration->getTotalWidth() * tcur->getX(),
                          g_configuration->getTotalHeight() * tcur->getY( ));

    QTouchEvent::TouchPoint touchPoint( tcur->getCursorID( ));
    touchPoint.setPressure( 1.0 );
    touchPoint.setNormalizedPos( normPos );
    touchPoint.setPos( wallPos ); // need for pan gesture recognition
    touchPoint.setScenePos( normPos );
    touchPoint.setScreenPos( screenPos ); // need for hotspot & itemAt

    Qt::TouchPointStates touchPointStates = 0;
    if( tcur->getCursorID() == 0 )
        touchPointStates |= Qt::TouchPointPrimary;

    switch( eventType )
    {
    case QEvent::TouchBegin:
        touchPointStates = Qt::TouchPointPressed;

        touchPoint.setStartNormalizedPos( normPos );
        touchPoint.setStartPos( touchPoint.pos( ));
        touchPoint.setStartScreenPos( screenPos );
        touchPoint.setStartScenePos( touchPoint.scenePos( ));

        touchPoint.setLastNormalizedPos( normPos );
        touchPoint.setLastPos( touchPoint.pos( ));
        touchPoint.setLastScreenPos( screenPos );
        touchPoint.setLastScenePos( touchPoint.scenePos( ));
        break;

    case QEvent::TouchUpdate:
    case QEvent::TouchEnd:
    {
        if( eventType == QEvent::TouchUpdate )
            touchPointStates = tcur->isMoving() ? Qt::TouchPointMoved
                                                : Qt::TouchPointStationary;
        else
            touchPointStates = Qt::TouchPointReleased;

        const QTouchEvent::TouchPoint& prevPoint = _touchPointMap.value( tcur->getCursorID( ));
        touchPoint.setStartNormalizedPos( prevPoint.startNormalizedPos( ));
        touchPoint.setStartPos( prevPoint.startPos( ));
        touchPoint.setStartScreenPos( prevPoint.startScreenPos( ));
        touchPoint.setStartScenePos( prevPoint.startScenePos( ));

        touchPoint.setLastNormalizedPos( prevPoint.normalizedPos( ));
        touchPoint.setLastPos( prevPoint.pos( ));
        touchPoint.setLastScreenPos( prevPoint.screenPos( ));
        touchPoint.setLastScenePos( prevPoint.scenePos( ));
        break;
    }

    default:
        put_flog( LOG_ERROR, "Got wrong touch event type %i", eventType );
        return;
    }

    touchPoint.setState( touchPointStates );
    _touchPointMap.insert( tcur->getCursorID(), touchPoint );

    QEvent* touchEvent = new QTouchEvent( eventType, QTouchEvent::TouchScreen,
                                          Qt::NoModifier, touchPointStates,
                                          _touchPointMap.values( ));
    QApplication::postEvent( view->viewport(), touchEvent );

    if( eventType == QEvent::TouchEnd )
        _touchPointMap.remove( tcur->getCursorID( ));
}
Beispiel #26
0
Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    QHBoxLayout * hbox = new QHBoxLayout;
    QGraphicsView * view = new QGraphicsView;
    GraphicsScene * scene = new GraphicsScene;

    QPolygonF polygon;
    qreal side = 20;
    qreal dx = qSqrt(3)/2 * side;
    polygon
            // standing on a point
            << QPointF(dx, -side/2)
            << QPointF(0, -side)
            << QPointF(-dx, -side/2)
            << QPointF(-dx, side/2)
            << QPointF(0, side)
            << QPointF(dx, side/2);
    // Sitting flat
    //            << QPointF(-side/2, dx)
    //            << QPointF(-side, 0)
    //            << QPointF(-side/2, -dx)
    //            << QPointF(side/2, -dx)
    //            << QPointF(side, 0)
    //            << QPointF(side/2, dx);

    int h = 9;
    int w = 17;
    int mid_h = h/2;
    int mid_w = w/2;

    for(int r = 0; r < h; r++)
    {
        for(int c = 0; c < w; c++)
        {
            if(qAbs(mid_h - r) + qAbs(mid_w - c) > 8
                    || (r % 2 != c % 2))
            {
                // don't add a hexagon, it isn't on the board!
            }
            else
            {
                BoardHexagon * hexagon = new BoardHexagon(0);
                hexagon->setPolygon(polygon);
                scene->addItem(hexagon);
                hexagon->setPos(dx * c, side * 1.5 * r);
                hexagon->setToolTip(QString::number(r) + "," + QString::number(c));
            }
        }
    }

    QGraphicsEllipseItem * ellipse = scene->addEllipse(-20, -20, 20, 20,QPen(), QBrush(QColor(Qt::green)));
    this->makeDraggable(ellipse);


    view->setRenderHint(QPainter::Antialiasing);
    view->setScene(scene);

    view->setMouseTracking(true);

    hbox->addWidget(view);
    this->setLayout(hbox);

    this->resize(600, 400);
}
/*!
  Traverse QObject based items.
*/
void TasQtTraverse::traverseObject(TasObject* objectInfo, QObject* object, TasCommand* command)
{
     // Embedded apps must use coordinates for operations, as the parent has no knowledge of the
    // Actual items
    bool embeddedApp = false;
    if (command && command->parameter("embedded") == "true") {
        embeddedApp = true;
    }
    //TasLogger::logger()->debug("TasQtTraverse::traverseObject in");
    mTraverseUtils->addObjectDetails(objectInfo, object);
    QGraphicsObject* graphicsObject = qobject_cast<QGraphicsObject*>(object);
    if(graphicsObject){
        objectInfo->addAttribute("objectType", embeddedApp? TYPE_WEB : TYPE_GRAPHICS_VIEW);
        mTraverseUtils->addGraphicsItemCoordinates(objectInfo, graphicsObject, command);
        mTraverseUtils->printGraphicsItemProperties(objectInfo, graphicsObject);

        //add details only for graphicsitems
        QGraphicsWidget* graphicsWidget = qobject_cast<QGraphicsWidget*>(object);
        if(graphicsWidget){
            mTraverseUtils->addFont(objectInfo, graphicsWidget->font());
            // Elided format "this is a text" -> "this is a..." text for
            // items that have the "text" property.
            QVariant text = graphicsWidget->property("text");
            if (text.isValid()) {
                mTraverseUtils->addTextInfo(objectInfo, text.toString(), graphicsWidget->font(), graphicsWidget->size().width());

            }
            QVariant plainText = graphicsWidget->property("plainText");
            if (plainText.isValid()) {
                mTraverseUtils->addTextInfo(objectInfo, plainText.toString(), graphicsWidget->font(), graphicsWidget->size().width());
            }
        }
    }
    else{
        QQuickItem* quickObject = qobject_cast<QQuickItem*>(object);

        if (quickObject) {
            objectInfo->addAttribute("objectType", TYPE_QSCENEGRAPH );
        }
        //make sure that we are dealing with a widget
        else if (object->isWidgetType()){
            QWidget* widget = qobject_cast<QWidget*>(object);
            objectInfo->addAttribute("objectType", TYPE_STANDARD_VIEW );

            addWidgetCoordinates(objectInfo, widget,command);
            mTraverseUtils->addFont(objectInfo, widget->font());
            //check is the widget a viewport to graphicsscene
            QWidget* parentWidget = widget->parentWidget();
            bool isViewPort = false;
            if(parentWidget && parentWidget->inherits("QGraphicsView")){
                QGraphicsView* view = qobject_cast<QGraphicsView*>(parentWidget);
                if(view->viewport() == widget){
                    isViewPort = true;
                }
            }
            //add transformation details
            QGraphicsView* graphicsView = qobject_cast<QGraphicsView*>(object);
            if(graphicsView){
                objectInfo->addBooleanAttribute("isTransformed", graphicsView->isTransformed());
                if(graphicsView->isTransformed()){
                    QTransform tr = graphicsView->transform();
                    objectInfo->addAttribute("transformM11",tr.m11());
                    objectInfo->addAttribute("transformM12",tr.m12());
                    objectInfo->addAttribute("transformM13",tr.m13());
                    objectInfo->addAttribute("transformM21",tr.m21());
                    objectInfo->addAttribute("transformM22",tr.m22());
                    objectInfo->addAttribute("transformM23",tr.m23());
                    objectInfo->addAttribute("transformM31",tr.m31());
                    objectInfo->addAttribute("transformM32",tr.m32());
                    objectInfo->addAttribute("transformM33",tr.m33());
                }
            }
            objectInfo->addBooleanAttribute("isViewPort", isViewPort);
// Add special window id attribute into qwidget atttributes
#if defined(Q_WS_X11)
            unsigned long wid = static_cast<unsigned long>(widget->effectiveWinId());
            objectInfo->addAttribute("xWindow", (int)wid); // can this fail due to precision?
#endif


        } else if(object->isWindowType()) {
            objectInfo->addAttribute("objectType", TYPE_WINDOW_VIEW);
        } else {
            if(object != qApp){
                objectInfo->addAttribute("objectType", embeddedApp? TYPE_WEB : TYPE_STANDARD_VIEW );
            }
        }

    }
}
Beispiel #28
0
//-----------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------
void MyVTK::key_canvas(QWidget *key_page)
{
//    QGraphicsScene* scene = new QGraphicsScene(QRect(0, 0, 130, 280));
    QGraphicsScene* scene = new QGraphicsScene(QRect(0, 0, 130, 310));
    QBrush brush;
    QGraphicsTextItem *text;

//    brush.setColor(QColor(255,128,77));
    brush.setColor(QColor(150,100,0));      // dark brown
    brush.setStyle(Qt::SolidPattern);
	scene->addEllipse(10,10,20,20,Qt::NoPen, brush);
	text = scene->addText("FDC");
    text->setPos(35, 10);

//    brush.setColor(QColor(255,77,128));
    brush.setColor(QColor(200,60,100));     // dark red
    brush.setStyle(Qt::SolidPattern);
    scene->addEllipse(10,40,20,20,Qt::NoPen, brush);
    text = scene->addText("MRC");
    text->setPos(35, 40);

    brush.setColor(QColor(30,20,255));      // dark blue
    scene->addEllipse(10,70,20,20,Qt::NoPen, brush);
	text = scene->addText("Naive B cell");
    text->setPos(35, 70);

    brush.setColor(QColor(0,200,255));      // light blue
    scene->addEllipse(10,100,20,20,Qt::NoPen, brush);
	text = scene->addText("CCR7 UP");
    text->setPos(35, 100);

    brush.setColor(QColor(50,255,150));     // light green
    scene->addEllipse(10,130,20,20,Qt::NoPen, brush);
	text = scene->addText("EBI2 UP");
    text->setPos(35, 130);

//    brush.setColor(QColor(255,255,0));      // yellow
    brush.setColor(Qt::yellow );      // yellow
    scene->addEllipse(10,160,20,20,Qt::NoPen, brush);
	text = scene->addText("BCL6 HI");
    text->setPos(35, 160);

    brush.setColor(QColor(0,150,0));        // dark green
    scene->addEllipse(10,190,20,20,Qt::NoPen, brush);
	text = scene->addText("BCL6 LO");
    text->setPos(35, 190);

    brush.setColor(QColor(128,128,128));    // grey
    scene->addEllipse(10,220,20,20,Qt::NoPen, brush);
	text = scene->addText("Max divisions");
    text->setPos(35, 220);

    brush.setColor(QColor(255,0,0));        // red
    scene->addEllipse(10,250,20,20,Qt::NoPen, brush);
	text = scene->addText("Plasma cell");
    text->setPos(35, 250);

    brush.setColor(QColor(255,130,0));      // orange
    scene->addEllipse(10,280,20,20,Qt::NoPen, brush);
    text = scene->addText("CD4 T cell");
    text->setPos(35, 280);

	QGraphicsView* view = new QGraphicsView(key_page);
    view->setScene(scene);
//    view->setGeometry(QRect(0, 0, 150, 300));
    view->setGeometry(QRect(0, 0, 150, 330));
    view->show();
}
Beispiel #29
0
SEXP
qt_qfitScene_QGraphicsView(SEXP v) {
  QGraphicsView *view = unwrapQObject(v, QGraphicsView);
  view->fitInView(view->sceneRect());
  return R_NilValue;
}
Beispiel #30
0
void Guideline::rangeOfAttachedObjects(double& min, double& max) const
{
    min = DBL_MAX;
    max = -DBL_MAX;

    for (RelsList::const_iterator curr = relationships.begin(); curr != relationships.end(); ++curr)
    {
        QRectF itemRect;
        if ((*curr)->shape)
        {
            itemRect = (*curr)->shape->boundingRect();
            itemRect.moveCenter((*curr)->shape->pos());
        }
        else if ((*curr)->distro)
        {
            itemRect = (*curr)->distro->boundingRect();
            itemRect.moveCenter((*curr)->distro->pos());
        }
        else if ((*curr)->separation)
        {
            itemRect = (*curr)->separation->boundingRect();
            itemRect.moveCenter((*curr)->separation->pos());
        }

        if (itemRect.isValid())
        {
            if (get_dir() == GUIDE_TYPE_HORI)
            {
                min = qMin(min, itemRect.left());
                max = qMax(max, itemRect.right());
            }
            else
            {
                min = qMin(min, itemRect.top());
                max = qMax(max, itemRect.bottom());
            }
        }
    }

    // Cope with the case where there are no attached objects.
    if ((min == DBL_MAX) && (max = -DBL_MAX) && canvas())
    {
        QList<QGraphicsView *> views = canvas()->views();
        QRectF sceneBounds;

        // Determine bounds by taking the union of all view bounds.
        for (int v = 0; v < views.size(); ++v)
        {
            QGraphicsView *view = views.at(v);

            sceneBounds = sceneBounds.united(QRectF(view->mapToScene(0,0),
                    view->mapToScene(view->width(), view->height())));
        }

        if (get_dir() == GUIDE_TYPE_HORI)
        {
            min = sceneBounds.left();
            max = sceneBounds.right();
        }
        else
        {
            min = sceneBounds.top();
            max = sceneBounds.bottom();
        }
    }
}