Перейти к содержимому

Как сделать еще одно окно qt python

  • автор:

Русские Блоги

[PyQt5] Нажмите на главное окно, чтобы открыть другое окно

1. Используйте Qt designer для проектирования двух окон, одно из которых является основным, а другое — подокном.


Главное окно — это Новое главное окно, а подокно — диалоговая форма.

Два окна не могут быть одного типа, в противном случае они вылетят.

И сохраните его как EyeTracking_main.ui и EyeTracking_process.ui (потому что я занимаюсь отслеживанием глаз, поэтому имя формы связано с тем же, что и здесь и далее), и используйте инструмент UIC для преобразования его в файл .py.

2. Напишите функцию драйвера для вызова двух форм

Основная форма Eyetracking_main.py

Назовите функцию драйвера EyeTracking_ui.py

Поскольку в будущем оно будет работать с каждым окном, главное окно и дочернее окно создаются в двух классах parentWindow и childWindow соответственно, которые наследуют родительские классы QMainWindow и QDialog:

Позже создайте экземпляры двух окон для окна и потомка соответственно:

Свяжите две формы, определив значение кнопки:

Когда кнопка нажата, отображается подокно.
Как показано на рисунке ниже, когда вы нажимаете «Обработка данных движения глаз», появляется окно процесса обработки:

[PyQt5] Open another window in the main window

As mentioned in the title, when we use PyQt5 compose the interface, we often need another sub-window that is different from the main window. It may be a different function, it may be a setting of the main program . anything is possible.

In PyQt5, it is not so difficult to open another window. Below, I use a simple example to demo how to open the sub-window.

Open Window

To complete another window is actually very simple: just write another window program. For example, I now have a main window:

At the same time, I also have another sub-window that is about to be opened:

Then when I click the button of the main window, it will show the window of the sub-window:

Как создать новое окно в PyQt5?

Есть созданное в Designer главное окно с кнопкой. Все это сохранено в файл test.ui.
Также в Designer создано новое пустое окно класса QWidget и сохранено в файл test2.ui.

В файле нового окна test2.py содержится:

В файле главного окна test.py:

Если нажать в главном окне на кнопку, то новое окно откроется и сразу закроется. Подскажите, пожалуйста, как заставить это окно постоянно отображаться?

  • Вопрос задан более трёх лет назад
  • 8227 просмотров
  • Facebook
  • Вконтакте
  • Twitter

причина: переменная new_window умирает сразу как заканчивается функция new_form() (почему? во славу Сатаны конечно!)
Пути решения:

1) создать какую нибудь глобальную переменную. Но глобальные переменные это плохой тон (незнаю почему) :

2) создать переменную глобальный массив окон (так делаю я — это всё ещё «плохой тон» но зато потом можно циклом разом удалить все создаваемые окна например. ) :

3) назначить new_window дочерю main_window (идиологически правильный вариант):

4) new_window должна быть переменной того обьекта который гарантировано не будет удалён (незнаю насчёт идиалогии. все варианты правильные. ):

Creating additional windows
Opening new windows for your application

In an earlier tutorial we’ve already covered how to open dialog windows. These are special windows which (by default) grab the focus of the user, and run their own event loop, effectively blocking the execution of the rest of your app.

However, quite often you will want to open a second window in an application, without interrupting the main window — for example, to show the output of some long-running process, or display graphs or other visualizations. Alternatively, you may want to create an application that allows you to work on multiple documents at once, in their own windows.

It’s relatively straightforward to open new windows but there are a few things to keep in mind to make sure they work well. In this tutorial we’ll step through how to create a new window, and how to show and hide external windows on demand.

Creating a new window

In Qt any widget without a parent is a window. This means, to show a new window you just need to create a new instance of a widget. This can be any widget type (technically any subclass of QWidget ) including another QMainWindow if you prefer.

There is no restriction on the number of QMainWindow instances you can have. If you need toolbars or menus on your second window you will have to use a QMainWindow to achieve this. This can get confusing for users however, so make sure it’s necessary.

As with your main window, creating a window is not sufficient, you must also show it.

A main window with a button to launch a child window,A main window with a button to launch a child window,

If you run this, you’ll see the main window. Clicking the button may show the second window, but if you see it it will only be visible for a fraction of a second. What’s happening?

Inside this method, we are creating our window (widget) object, storing it in the variable w and showing it. However, once we leave the method we no longer have a reference to the w variable (it is a local variable) and so it will be cleaned up – and the window destroyed. To fix this we need to keep a reference to the window somewhere, for example on the self object.

Now, when you click the button to show the new window, it will persist.

However, what happens if you click the button again? The window will be re-created! This new window will replace the old in the self.w variable, and – because there is now no reference to it – the previous window will be destroyed.

You can see this in action if you change the window definition to show a random number in the label each time it is created.

The __init__ block is only run when creating the window. If you keep clicking the button the number will change, showing that the window is being re-created.

One solution is to simply check whether the window has already being created before creating it. The example below shows this in action.

Child window with a label randomly generated on creation.Child window with a label randomly generated on creation.

Using the button you can pop up the window, and use the window controls to close it. If you click the button again, the same window will re-appear.

This approach is fine for windows that you create temporarily – for example if you want to pop up a window to show a particular plot, or log output. However, for many applications you have a number of standard windows that you want to be able to show/hide them on demand.

In the next part we’ll look at how to work with these types of windows.

Toggling a window

Often you’ll want to toggle the display of a window using an action on a toolbar or in a menu. As we previously saw, if no reference to a window is kept, it will be discarded (and closed). We can use this behaviour to close a window, replacing the show_new_window method from the previous example with –

By setting self.w to None the reference to the window will be lost, and the window will close.

If we set it to any other value that None the window will still close, but the if self.w is None test will not pass the next time we click the button and so we will not be able to recreate a window.

This will only work if you have not kept a reference to this window somewhere else. To make sure the window closes regardless, you may want to explicitly call .close() on it. The full example is shown below.

Martin Fitzpatrick Python GUIs Coaching & Training

1:1 Python GUIs Coaching & Training

Comprehensive code reviewBugfixes & improvements • Maintainability advice and architecture improvements • Design and usability assessment • Suggestions and tips to expand your knowledgePackaging and distribution help for Windows, Mac & Linux • Find out more.

Persistent windows

So far we’ve looked at how to create new windows on demand. However, sometimes you have a number of standard application windows. In this case rather than create the windows when you want to show them, it can often make more sense to create them at start-up, then use .show() to display them when needed.

In the following example we create our external window in the __init__ block for the main window, and then our show_new_window method simply calls self.w.show() to display it.

If you run this, clicking on the button will show the window as before. However, note that the window is only created once and calling .show() on an already visible window has no effect.

Showing & hiding persistent windows

Once you have created a persistent window you can show and hide it without recreating it. Once hidden the window still exists, but will not be visible and accept mouse/other input. However you can continue to call methods on the window and update it’s state — including changing it’s appearance. Once re-shown any changes will be visible.

Below we update our main window to create a toggle_window method which checks, using .isVisible() to see if the window is currently visible. If it is not, it is shown using .show() , if it is already visible we hide it with .hide() .

The complete working example of this persistent window and toggling the show/hide state is shown below.

Note that, again, the window is only created once — the window’s __init__ block is not re-run (so the number in the label does not change) each time the window is re-shown.

Multiple windows

You can use the same principle for creating multiple windows — as long as you keep a reference to the window, things will work as expected. The simplest approach is to create a separate method to toggle the display of each of the windows.

A mainwindow with two child windows.A mainwindow with two child windows.

However, you can also create a generic method which handles toggling for all windows — see transmitting extra data with Qt signals for a detailed explanation of how this works. The example below shows that in action, using a lambda function to intercept the signal from each button and pass through the appropriate window. We can also discard the checked value since we aren’t using it.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *