Добавьте вкладки в заголовокPython

Программы на Python
Ответить
Anonymous
 Добавьте вкладки в заголовок

Сообщение Anonymous »

сделал клон окон в блокноте и не могу заставить вкладки располагаться в той же строке, что и заголовок

Код: Выделить всё

import sys
from PySide6.QtWidgets import QApplication, QMainWindow, QTabWidget, QWidget, QVBoxLayout, QTextEdit, QFileDialog
from PySide6.QtGui import QAction

class Notepad(QMainWindow):
def __init__(self):
super().__init__()

self.setWindowTitle("Notepad with Tabs")
self.setGeometry(300, 100, 800, 600)

self.tab_widget = QTabWidget()
self.setCentralWidget(self.tab_widget)
self.tab_widget.setTabsClosable(True)
self.tab_widget.tabCloseRequested.connect(self.close_tab)
self.create_tab()

self.init_menu()

def init_menu(self):
menubar = self.menuBar()
file_menu = menubar.addMenu('File')

new_action = QAction('New', self)
new_action.triggered.connect(self.create_tab)
file_menu.addAction(new_action)

open_action = QAction('Open', self)
open_action.triggered.connect(self.open_file)
file_menu.addAction(open_action)

save_action = QAction('Save', self)
save_action.triggered.connect(self.save_file)
file_menu.addAction(save_action)

exit_action = QAction('Exit', self)
exit_action.triggered.connect(self.close)
file_menu.addAction(exit_action)

def create_tab(self):
new_tab = QWidget()
layout = QVBoxLayout()
text_edit = QTextEdit()
layout.addWidget(text_edit)
new_tab.setLayout(layout)
index = self.tab_widget.addTab(new_tab, "New Tab")
self.tab_widget.setCurrentIndex(index)

def close_tab(self, index):
self.tab_widget.removeTab(index)

def open_file(self):
options = QFileDialog.Options()
file_name, _ = QFileDialog.getOpenFileName(self, "Open File", "", "Text Files (*.txt);;All Files (*)", options=options)
if file_name:
with open(file_name, 'r') as file:
content = file.read()
self.create_tab()
current_widget = self.tab_widget.currentWidget()
text_edit = current_widget.layout().itemAt(0).widget()
text_edit.setText(content)
self.tab_widget.setTabText(self.tab_widget.currentIndex(), file_name.split('/')[-1])

def save_file(self):
current_widget = self.tab_widget.currentWidget()
text_edit = current_widget.layout().itemAt(0).widget()
content = text_edit.toPlainText()
options = QFileDialog.Options()
file_name, _ = QFileDialog.getSaveFileName(self, "Save File", "", "Text Files (*.txt);;All Files (*)", options=options)
if file_name:
with open(file_name, 'w') as file:
file.write(content)
self.tab_widget.setTabText(self.tab_widget.currentIndex(), file_name.split('/')[-1])

if __name__ == '__main__':
app = QApplication(sys.argv)
notepad = Notepad()
notepad.show()
sys.exit(app.exec())

пытаюсь разместить вкладки, как в блокноте в Windows, с вкладками на той же линии, что и строка заголовка, с вкладкой рядом со значком и на той же строке, что и кнопки закрытия минимального и максимального значения с кривой табуляции. это касается редактирования вкладок и файлов, а также текстовой панели.
пробовал пользовательские строки заголовка, но безуспешно, пытаясь встроить вкладки в один ряд с кнопками закрытия с переносом вкладок в блокнот Windows имеет
tab +newtab [min][max][close]
file
textpad
Где файл вкладки и текстовая панель свернуты вместе, как блокнот Windows< /p>
редактировать: сделал черновой вариант в tkinter

Код: Выделить всё

import tkinter as tk
from tkinter import ttk

def new_file():
# Create a new tab with a new frame and custom menubar
tab_name = f"Tab {len(notebook.tabs()) + 1}"
new_tab_frame = create_tab_frame()
notebook.add(new_tab_frame, text=tab_name)

def open_file():
# Open file dialog and read the file content into a new tab (omitted for simplicity)
pass

def save_file():
# Save content of textpad to a file (omitted for simplicity)
pass

def close_window(event=None):
root.quit()

def create_tab_frame():
# Create a new tab frame
tab_frame = tk.Frame(notebook)
tab_frame.pack(fill="both", expand=True)

# Add a custom menubar inside the tab
tab_menubar = tk.Frame(tab_frame, bg="lightgray", height=30)
tab_menubar.pack(fill="x", side="top")

# Add buttons to the custom menubar
new_button = tk.Button(tab_menubar, text="New", command=new_file)
new_button.pack(side="left", padx=5)

save_button = tk.Button(tab_menubar, text="Save", command=save_file)
save_button.pack(side="left", padx=5)

# Add a textpad below the custom menubar
text_pad = tk.Text(tab_frame, wrap="word", font=("Arial", 12))
text_pad.pack(fill="both", expand=True)

return tab_frame

# Create the main window
root = tk.Tk()
root.geometry("600x400")
root.title("Custom Title Bar Example")
root.overrideredirect(True)

# Create a custom title bar
title_bar = tk.Frame(root, bg="gray", relief="raised", bd=2, height=30)
title_bar.pack(fill="x", side="top")

title_label = tk.Label(title_bar, text="Custom Title Bar Example", bg="gray", fg="white", font=("Arial", 14))
title_label.pack(side="left", padx=10)

close_button = tk.Button(title_bar, text="X", command=close_window, bg="gray", fg="white", bd=0)
close_button.pack(side="right", padx=5)

# Create a notebook (tabbed interface)
notebook = ttk.Notebook(root)
notebook.pack(fill="both", expand=True, padx=10, pady=5)

# Create the initial tab with a custom menubar
initial_tab = create_tab_frame()
notebook.add(initial_tab, text="Tab 1")

root.mainloop()
чтобы новая вкладка и сохранение находились между текстовой вкладкой и текстовой панелью вкладок. как мне сделать вкладку теперь в пользовательской строке заголовка, например в блокноте Windows по умолчанию

Подробнее здесь: https://stackoverflow.com/questions/792 ... e-titlebar
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»