Skip to content

Instantly share code, notes, and snippets.

@kapb14
Created October 9, 2018 07:53
Show Gist options
  • Select an option

  • Save kapb14/82d586905a872ab33167019fc58c2619 to your computer and use it in GitHub Desktop.

Select an option

Save kapb14/82d586905a872ab33167019fc58c2619 to your computer and use it in GitHub Desktop.
QT5 with python first steps
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>MainWindow</class>
<widget class="QMainWindow" name="MainWindow">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>309</width>
<height>247</height>
</rect>
</property>
<property name="minimumSize">
<size>
<width>309</width>
<height>247</height>
</size>
</property>
<property name="windowTitle">
<string>QT5 Test UI</string>
</property>
<widget class="QWidget" name="centralwidget">
<widget class="QWidget" name="layoutWidget">
<property name="geometry">
<rect>
<x>10</x>
<y>200</y>
<width>291</width>
<height>25</height>
</rect>
</property>
<layout class="QHBoxLayout" name="ctrlButtonsLayout">
<item>
<widget class="QPushButton" name="btnStart">
<property name="text">
<string>Start</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnStop">
<property name="text">
<string>Stop</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="btnEdit">
<property name="text">
<string>Edit Config</string>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="">
<property name="geometry">
<rect>
<x>9</x>
<y>9</y>
<width>291</width>
<height>61</height>
</rect>
</property>
<layout class="QVBoxLayout" name="selectWsgiLayout">
<item>
<widget class="QListWidget" name="listWidget"/>
</item>
<item>
<widget class="QPushButton" name="btnBrowseFile">
<property name="text">
<string>Выберите .wsgi файл</string>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="">
<property name="geometry">
<rect>
<x>10</x>
<y>81</y>
<width>291</width>
<height>81</height>
</rect>
</property>
<layout class="QVBoxLayout" name="selectApacheLayout">
<item>
<widget class="QListWidget" name="listWidgetApache"/>
</item>
<item>
<widget class="QPushButton" name="btnBrowseFileApache">
<property name="text">
<string>Выберите httpd.exe</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="lblApacheCfgCheck">
<property name="text">
<string>httpd.exe -t</string>
</property>
</widget>
</item>
</layout>
</widget>
<widget class="QWidget" name="">
<property name="geometry">
<rect>
<x>10</x>
<y>170</y>
<width>291</width>
<height>24</height>
</rect>
</property>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<layout class="QHBoxLayout" name="selectPortLayout">
<item>
<widget class="QLabel" name="labelPortNum">
<property name="text">
<string>Port Number</string>
</property>
<property name="alignment">
<set>Qt::AlignCenter</set>
</property>
</widget>
</item>
<item>
<widget class="QSpinBox" name="spinboxPortNum">
<property name="minimum">
<number>1024</number>
</property>
<property name="maximum">
<number>65535</number>
</property>
<property name="value">
<number>8555</number>
</property>
</widget>
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="statusLayout">
<item>
<widget class="QLabel" name="statusLabel">
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="statusResult">
<property name="text">
<string>TextLabel</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
</widget>
<widget class="QStatusBar" name="statusbar"/>
</widget>
<resources/>
<connections/>
</ui>
@echo off
pyuic5.exe apache_wsgi_ctl.ui -o apache_wsgi_ctl.py
TIMEOUT /T 5
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import sys # sys нужен для передачи argv в QApplication
import os # os нужен для отображения содержимого директории
import subprocess # нужен для управления процессами апача
from PyQt5 import QtWidgets
import apache_wsgi_ctl as design # Это наш конвертированный файл дизайна
class ExampleApp(QtWidgets.QMainWindow, design.Ui_MainWindow):
def __init__(self):
# Это здесь нужно для доступа к переменным, методам
# и т.д. в файле apache_wsgi_ctl.py
super().__init__()
self.setupUi(self) # Это нужно для инициализации нашего дизайна
self.statusBar().showMessage("Запустились")
# self.btnBrowseFile.clicked.connect(self.browse_folder)
self.btnBrowseFile.clicked.connect(self.browse_wsgi_file)
self.btnBrowseFileApache.clicked.connect(self.browse_httpd_exe)
def _select_file(self, text, start_path="C:\\www\\"):
file = QtWidgets.QFileDialog.getOpenFileName(self, text, start_path)[0]
if os.path.isfile(file):
return file
def browse_httpd_exe(self):
self.listWidgetApache.clear()
self.httpd_exe = self._select_file("Укажите httpd.exe", "C:\\www\\Apache24\\bin\\httpd.exe")
self.statusBar().showMessage("Выбран httpd.exe")
self.listWidgetApache.addItem(self.httpd_exe)
self.show_httpd_configcheck()
def browse_wsgi_file(self):
self.listWidget.clear()
# file = QtWidgets.QFileDialog.getOpenFileName(self, 'Выберите WSGI файл', 'C:\\www\\')[0]
# if os.path.isfile(file):
# self.listWidget.addItem(file)
wsgi_file = self._select_file("Выберите WSGI файл")
self.statusBar().showMessage("Выбран WSGI конфиг")
self.listWidget.addItem(wsgi_file)
def browse_folder(self):
self.listWidget.clear() # На случай, если в списке уже есть элементы
directory = QtWidgets.QFileDialog.getExistingDirectory(self, "Выберите папку")
# открыть диалог выбора директории и установить значение переменной
# равной пути к выбранной директории
if directory: # не продолжать выполнение, если пользователь не выбрал директорию
for file_name in os.listdir(directory): # для каждого файла в директории
self.listWidget.addItem(file_name) # добавить файл в listWidget
def _get_httpd_configcheck(self):
proc = subprocess.Popen([self.httpd_exe, "-t"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
outs, errs = proc.communicate(timeout=15)
except TimeoutExpired:
proc.kill()
outs, errs = proc.communicate()
print("_get_httpd_configcheck OUT: %s" % outs)
print("_get_httpd_configcheck ERR: %s" % errs)
return outs, errs
def show_httpd_configcheck(self):
check_out, check_err = self._get_httpd_configcheck()
if check_err:
label_txt = 'Configuration check failed!'
elif check_out:
label_txt = str(check_out)
else:
label_txt = 'Unknown'
self.statusBar().showMessage("Apache config check: %s" % label_txt)
self.lblApacheCfgCheck.setText(label_txt)
def main():
app = QtWidgets.QApplication(sys.argv) # Новый экземпляр QApplication
window = ExampleApp() # Создаём объект класса ExampleApp
window.show() # Показываем окно
app.exec_() # и запускаем приложение
if __name__ == '__main__': # Если мы запускаем файл напрямую, а не импортируем
main() # то запускаем функцию main()
PyQt5
pyqt5-tools
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment