t
tettaMay 8, 2017, 6:34 a.m.

Перенос окна

Вот по этой статье я пытался сделать так , что бы окно пересувалось, но у меня выдает дофига ошибок, помогите, что куда вписывать. Вот код заголовочного файла:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QPoint>
#include <QMainWindow>
#include <QMessageBox>
#include <QAction>
#include <QToolBar>
#include <QToolButton>
#include <QDockWidget>
#include <QLayout>
#include <QMdiArea>
#include <QMouseEvent>
#include <QStandardItemModel>
#include <QWidget>

#include "stylehelper.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT


public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();


//slots for menuBar
private slots:
    void s_file(){
        QMessageBox msg;
            msg.setText("Action");
            msg.exec();
    }
    void exit(){
        close();
    }
    void f_fsm(){
        if(this->isMaximized()){
         this->showFullScreen();
        }else{
            this->showMaximized();
        }
    }
    void about(){
        QMessageBox msg;
            msg.setText("I say about this programe now!");
            msg.exec();
    }


private:
    Ui::MainWindow *ui;

    //for toolBar(Add more toolBar)

     //oToolBar
      QToolBar *oToolBar;
      QToolButton *oToolButton;
     //tToolBar
      QToolBar *tToolBar;
      QToolButton *tToolButton;

    //mouse position

};

#endif // MAINWINDOW_H
А это реализация:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QStyle>
#include <QtWidgets>
#include <QToolBar>
#include <QMenuBar>
#include <QAction>
#include <QtGui>
#include <QLineEdit>
#include <QLabel>
#include <QWidget>
#include <QTabBar>
#include <QPushButton>
#include <QMainWindow>
#include <QToolBar>
#include <QToolButton>
#include <QIcon>
#include <QDockWidget>
#include <QLayout>
#include <QStyle>
#include <QStyleHints>
#include <QGridLayout>
#include <QFileDialog>
#include <QDir>
#include <QGraphicsDropShadowEffect>
#include <QSizePolicy>
#include <QSpacerItem>
#include <QComboBox>

#include "stylehelper.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);


    //setting UI
      this->setWindowFlags(Qt::FramelessWindowHint);
      this->setStyleSheet(StyleHelper::getWindowStyleSheet());

   //
    QGridLayout *qgl = new QGridLayout(this);

    //close, maximize, minimize
      //close
       QPushButton *cls = new QPushButton(this);
       connect(cls, &QPushButton::clicked, this, &QWidget::close);
       cls->setStyleSheet(StyleHelper::getClsStyleSheet());
       cls->setGeometry(cls->geometry().x() + 1000 ,cls->geometry().y() + 90, cls->width() - 53, cls->height() - 9);
       cls->setIcon(QIcon("url(/icon/project.png)"));
       qgl->addItem(new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding), 30, 0, 1, 2);
       qgl->addWidget(cls, 1, 0);
       qgl->addItem(new QSpacerItem(20, 40, QSizePolicy::Expanding, QSizePolicy::Minimum), 10, 10);


       ui->btn_close->setStyleSheet(StyleHelper::getCloseStyleSheet());
      //maximize
       ui->btn_maximize->setStyleSheet(StyleHelper::getMaximizeStyleSheet());
      //minimize
       ui->btn_minimize->setStyleSheet(StyleHelper::getMinimizeStyleSheet());

    //connect close, maximize, minimize
       connect(ui->btn_minimize, &QToolButton::clicked, this, &QWidget::showMinimized);
       connect(ui->btn_maximize, &QToolButton::clicked, [this](){
        if (this->isMaximized()) {
           ui->btn_maximize->setStyleSheet(StyleHelper::getMaximizeStyleSheet());
            this->layout()->setMargin(9);
            this->showNormal();
        } else {
           ui->btn_maximize->setStyleSheet(StyleHelper::getRestoreStyleSheet());
            this->layout()->setMargin(0);
            this->showMaximized();
        }
       });
       connect(ui->btn_close, &QToolButton::clicked, this, &QWidget::close);

   //menuBar(Add more buttons)
    menuBar()->setStyleSheet(StyleHelper::getQMenuStyleSheet());

    //file
     QToolButton *fileF = new QToolButton();
      QMenu *file = menuBar()->addMenu(tr("File"));
      file->setStyleSheet(StyleHelper::getMenuBarStyleSheet());

       //new
        QAction *newFile = new QAction (tr("New"),this);
         newFile->setShortcut(QKeySequence::New);
         connect(newFile,SIGNAL(triggered()),this,SLOT(s_file()));
          file->addAction(newFile);

       //open
        QAction *openFile = new QAction (tr("Open"),this);
         openFile->setShortcut(QKeySequence::Open);

          file->addAction(openFile);

       //open as
         QAction *openAsFile = new QAction (tr("Open as"),this);

           file->addAction(openAsFile);

       //the last document
         QAction *lastFile = new QAction (tr("The last document"),this);

            file->addAction(lastFile);

       file->addSeparator();

       //save
         QAction *saveFile = new QAction (tr("Save"),this);
           saveFile->setShortcut(QKeySequence::Save);

            file->addAction(saveFile);

       //save as
         QAction *saveAsFile = new QAction (tr("Save as"),this);
           saveAsFile->setShortcut(QKeySequence::SaveAs);

            file->addAction(saveAsFile);

       //save all
         QAction *saveAllFile = new QAction (tr("Save all"),this);
            saveAllFile->setShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_S);

             file->addAction(saveAllFile);

       file->addSeparator();

       //exit
         QAction *exitFile = new QAction (tr("Exit"),this);
             exitFile->setShortcut(Qt::CTRL+Qt::Key_Q);
             connect(exitFile,SIGNAL(triggered()),this,SLOT(exit()));
              file->addAction(exitFile);


       fileF->setMenu(file);
    //edit
      QToolButton *editF = new QToolButton();
      QMenu *edit = menuBar()->addMenu(tr("&Edit"));
      edit->setStyleSheet(StyleHelper::getMenuBarStyleSheet());

       //undo
         QAction *undoFile = new QAction (tr("Undo"),this);
              undoFile->setShortcut(Qt::CTRL+Qt::Key_Z);
               edit->addAction(undoFile);

       editF->setMenu(edit);
    //window
     //  QToolButton *windowF = new QToolButton(this);
       QMenu *window = menuBar()->addMenu(tr("&Window"));
       window->setStyleSheet(StyleHelper::getMenuBarStyleSheet());

       //full screen mode
         QAction *fsm = new QAction (tr("Full screen mode"),this);
              fsm->setShortcut(Qt::Key_F5);
              connect(fsm,SIGNAL(triggered()),this,SLOT(f_fsm()));
                window->addAction(fsm);

       windowF->setMenu(window);
    //reference
       QToolButton *referenceF = new QToolButton();
       QMenu *reference = menuBar()->addMenu(tr("&Reference"));
       reference->setStyleSheet(StyleHelper::getMenuBarStyleSheet());

      //About the program "Project"
         QAction *atp = new QAction (tr("About the program Project"),this);
               connect(atp,SIGNAL(triggered()),this,SLOT(about()));
                reference->addAction(atp);

          referenceF->setMenu(reference);
    //Header


       //toolBar(Add setting for toolBar)

         //oToolBar
          oToolBar = new QToolBar("First ToolBar");
          oToolButton = new QToolButton(this);
          oToolButton->setIcon(QIcon("../../Синий.jpg"));
          oToolBar->addWidget(oToolButton);
          oToolBar->setStyleSheet(StyleHelper::getToolBStyleSheet());
          addToolBar(oToolBar);


         //tToolBar
           tToolBar = new QToolBar("Second ToolBar");
           tToolButton = new QToolButton(this);
           tToolButton->setIcon(QIcon("../../Красный.jpg"));
           tToolBar->addWidget(tToolButton);
           tToolBar->setStyleSheet(StyleHelper::getToolBStyleSheet());
           addToolBar(tToolBar);


}

MainWindow::~MainWindow()
{
    delete ui;
}
(Знаю, что громадный)
We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

2
t
  • May 8, 2017, 6:35 a.m.

Вот по этой статье (Чет не прицепилось)

    Evgenii Legotckoi
    • May 8, 2017, 11:53 p.m.

    Весь проект в таком случае прикреплять надо. Там до чёртиков включений посторонних файлов. Если бы всё что там было написано, было только в составе класса MainWindow, тогда лады, а так там StyleHelper, ресурсные файлы и т.д. А так, что Вам тут подсказывать? Какие ошибки выпадают Вы не привели. Скопипастить в свой проект и запустить компиляцию? А толку-то? Первое, на что сругается компилятор - это будет отсутствие заголовочного файла stylehelper.h, который явно не является причиной ваших ошибок. Удалять всё, что не включено? Опять же никакого толку. Ну удалю я лишнее, сделаю рабочий вариант класса, но у вас всё равно опыта не хватит, чтобы внедрить это к себе в проект.

      Comments

      Only authorized users can post comments.
      Please, Log in or Sign up
      d
      • dsfs
      • April 26, 2024, 4:56 a.m.

      C ++ - Test 004. Pointers, Arrays and Loops

      • Result:80points,
      • Rating points4
      d
      • dsfs
      • April 26, 2024, 4:45 a.m.

      C++ - Test 002. Constants

      • Result:50points,
      • Rating points-4
      d
      • dsfs
      • April 26, 2024, 4:35 a.m.

      C++ - Test 001. The first program and data types

      • Result:73points,
      • Rating points1
      Last comments
      k
      kmssrFeb. 8, 2024, 6:43 p.m.
      Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
      Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
      EVA
      EVADec. 25, 2023, 10:30 a.m.
      Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
      J
      JonnyJoDec. 25, 2023, 8:38 a.m.
      Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
      G
      GvozdikDec. 18, 2023, 9:01 p.m.
      Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
      Now discuss on the forum
      Evgenii Legotckoi
      Evgenii LegotckoiMay 2, 2024, 2:07 p.m.
      Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Добрый день. По моему мнению - да, но то, что будет касаться вызовов к функционалу Андроида, может создать огромные трудности.
      IscanderChe
      IscanderCheApril 30, 2024, 4:22 a.m.
      Во Flask рендер шаблона не передаётся в браузер Доброе утро! Имеется вот такой шаблон: <!doctype html><html> <head> <title>{{ title }}</title> <link rel="stylesheet" href="{{ url_…
      G
      GarApril 22, 2024, 5:46 a.m.
      Clipboard Как скопировать окно целиком в clipb?
      Павел Дорофеев
      Павел ДорофеевApril 14, 2024, 2:35 a.m.
      QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
      f
      fastrexApril 4, 2024, 4:47 a.m.
      Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

      Follow us in social networks